How can I reliably set the backroundimage of a picturebox to be a random color? - powershell

I have a fairly simple color randomization snippet that I am using so I can accurately see the bounds of an image matrix I am making on screen. Problem is that I can not get it to work 100% of the time.
$listingImage = [System.Windows.Forms.PictureBox]::new()
...
# Temp color code to help with visual
$listingImage.BackColor = ([System.Drawing.Color](Get-Random -Minimum 1 -Maximum 999999))
The rest of the code follows in the question but that is the heart of what I am trying to do. I have seen it working several times but repeated executions show what seem like, empty, blank or otherwise invisible picture boxes. If I hard code a colour like $listingImage.BackColor = [System.Drawing.Color]::DarkCyan I can see that working fine every time. I want different colours though so I can see how to boxes are lining up with each other.
The code you can use for testing is as follows:
Add-Type -AssemblyName System.Windows.Forms
$imageContainerSize = [Drawing.Size]::new(100,100) # Width, Height
$numberOfImages = [pscustomobject]#{
Horizontal = 5
Vertical = 4
}
$formOverallSize = [Drawing.Size]::new(
$imageContainerSize.Width * $numberOfImages.Horizontal,
$imageContainerSize.Height * $numberOfImages.Vertical
)
$listingImageForm = New-Object System.Windows.Forms.Form
$listingImageForm.Text = $listing.URL
$listingImageForm.Size = $formOverallSize
$listingImageForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$listingImageForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$imageMatrixXOffset = 0
$imageMatrixYOffset = 0
# Load the image place holder image.
$placeholderImagePath = "m:\scripts\test.png"
# $placeholderImage = [system.drawing.image]::FromStream([IO.MemoryStream]::new([System.IO.File]::ReadAllBytes($placeholderImagePath)))
# Create an image matrix from the images provided in a listing group
for ($verticalImageIndex = 0; $verticalImageIndex -lt $numberOfImages.Vertical; $verticalImageIndex++){
for ($horizonalImageIndex = 0; $horizonalImageIndex -lt $numberOfImages.Horizontal; $horizonalImageIndex++){
$listingImage = [System.Windows.Forms.PictureBox]::new()
$listingImage.Size = $imageContainerSize
$listingImage.BorderStyle = [System.Windows.Forms.BorderStyle]::None
$listingImage.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
$listingImage.Location = [System.Drawing.Point]::new($horizonalImageIndex * $listingImage.Size.Width + $imageMatrixXOffset,
$verticalImageIndex * $listingImage.Size.Height + $imageMatrixYOffset )
# Temp color code to help with visual
$listingImage.BackColor = ([System.Drawing.Color](Get-Random -Minimum 1 -Maximum 999999))
# Place the image based
# $listingImage.Image = $placeholderImage
$listingImage.Tag = "h:$horizonalImageIndex v:$verticalImageIndex"
# Download the image as a memory stream to bypass saving the file
$listingImageForm.Controls.Add($listingImage)
}
}
# Adjust the size of the form to account for the title bar and the width of the form.
$formBorderWidth = ($listingImageForm.Width - $listingImageForm.ClientSize.Width) / 2
$formTitleBarHeight = $listingImageForm.Height – $listingImageForm.ClientSize.Height – 2 * $formBorderWidth
# Adjust for based on previosly calculated values
$listingImageForm.Size.Height = $listingImageForm.Size.Height + $formTitleBarHeight + ($formBorderWidth * 2)
$listingImageForm.Size.Width = $listingImageForm.Size.Width + ($formBorderWidth * 2)
$listingImageForm.Add_Shown({$listingImageForm.Activate()})
[void]$listingImageForm.ShowDialog()
"Form Height : $($listingImageForm.Size.Height)"
"Form Width : $($listingImageForm.Size.Width)"
"Image Height: $($imageContainerSize.Height)"
"Image Width : $($imageContainerSize.Width)"
$listingImageForm.Dispose()
Why is my randomization not working correctly? I really don't think it is the randomization itself since I can run

The problem is with the randomization upperbound.
[System.Drawing.Color](Get-Random -Minimum 1 -Maximum 999999)
So this will only generate values of a maximum 999999. The number will never get high enough to change the alpha channel / opacity value of the 'random' colour. If you kept trying that code in the command line you will see the A value is always zero.
([System.Drawing.Color](Get-Random -Minimum 1 -Maximum 999999))
R : 10
G : 177
B : 51
A : 0
IsKnownColor : False
IsEmpty : False
IsNamedColor : False
IsSystemColor : False
Name : ab133
A larger testing set to prove the point.
1..1000 | ForEach-Object {
([system.Drawing.Color](Get-Random -Minimum 1 -Maximum 999999))} |
Group-Object -Property A -NoElement
Count Name
----- ----
1000 0
This is why it did not appear to work as the opacity was always zero. I suspect it was periodically working as you might have been changing the randomization code between tests and not correlating the changes.
RGBA Values can be represented as int32 integers values. Setting your randomization to use that as your upper bound will prove more fruitful.
[System.Drawing.Color](Get-Random ([int32]::MaxValue))
Yes, it is possible you could randomize all 0 alpha again but for simple testing that should work just fine.
Click image to embiggen
Or, as Ansgar Wiechers mentions in comments, this might be a friendlier solution to the issue
[Drawing.Color]::FromArgb((Random 256),(Random 256),(Random 256),(Random 256))

Related

ORTOOLS - CPSAT - Objective to minimize a value by intervals

I my model in ORTools CPSAT, I am computing a variable called salary_var (among others). I need to minimize an objective. Let’s call it « taxes ».
to compute the taxes, the formula is not linear but organised this way:
if salary_var below 10084, taxes corresponds to 0%
between 10085 and 25710, taxes corresponds to 11%
between 25711 and 73516, taxes corresponds to 30%
and 41% for above
For example, if salary_var is 30000 then, taxes are:
(25710-10085) * 0.11 + (30000-25711) * 0.3 = 1718 + 1286 = 3005
My question: how can I efficiently code my « taxes » objective?
Thanks for your help
Seb
This task looks rather strange, there is not much context and some parts of the task might touch some not-so-nice areas of finite-domain based solvers (large domains or scaling / divisions during solving).
Therefore: consider this as an idea / template!
Code
from ortools.sat.python import cp_model
# Data
INPUT = 30000
INPUT_UB = 1000000
TAX_A = 11
TAX_B = 30
TAX_C = 41
# Helpers
# new variable which is constrained to be equal to: given input-var MINUS constant
# can get negative / wrap-around
def aux_var_offset(model, var, offset):
aux_var = model.NewIntVar(-INPUT_UB, INPUT_UB, "")
model.Add(aux_var == var - offset)
return aux_var
# new variable which is equal to the given input-var IFF >= 0; else 0
def aux_var_nonnegative(model, var):
aux_var = model.NewIntVar(0, INPUT_UB, "")
model.AddMaxEquality(aux_var, [var, model.NewConstant(0)])
return aux_var
# Model
model = cp_model.CpModel()
# vars
salary_var = model.NewIntVar(0, INPUT_UB, "salary")
tax_component_a = model.NewIntVar(0, INPUT_UB, "tax_11")
tax_component_b = model.NewIntVar(0, INPUT_UB, "tax_30")
tax_component_c = model.NewIntVar(0, INPUT_UB, "tax_41")
# constraints
model.AddMinEquality(tax_component_a, [
aux_var_nonnegative(model, aux_var_offset(model, salary_var, 10085)),
model.NewConstant(25710 - 10085)])
model.AddMinEquality(tax_component_b, [
aux_var_nonnegative(model, aux_var_offset(model, salary_var, 25711)),
model.NewConstant(73516 - 25711)])
model.Add(tax_component_c == aux_var_nonnegative(model,
aux_var_offset(model, salary_var, 73516)))
tax_full_scaled = tax_component_a * TAX_A + tax_component_b * TAX_B + tax_component_c * TAX_C
# Demo
model.Add(salary_var == INPUT)
solver = cp_model.CpSolver()
status = solver.Solve(model)
print(list(map(lambda x: solver.Value(x), [tax_component_a, tax_component_b, tax_component_c, tax_full_scaled])))
Output
[15625, 4289, 0, 300545]
Remarks
As implemented:
uses scaled solving
produces scaled solution (300545)
no fiddling with non-integral / ratio / rounding stuff BUT large domains
Alternative:
Maybe something around AddDivisionEquality
Edit in regards to Laurents comments
In some scenarios, solving the scaled problem but being able to reason about the real unscaled values easier might make sense.
If i interpret the comment correctly, the following would be a demo (which i was not aware of and it's cool!):
Updated Demo Code (partial)
# Demo -> Attempt of demonstrating the objective-scaling suggestion
model.Add(salary_var >= 30000)
model.Add(salary_var <= 40000)
model.Minimize(salary_var)
model.Proto().objective.scaling_factor = 0.001 # DEFINE INVERSE SCALING
solver = cp_model.CpSolver()
solver.parameters.log_search_progress = True # SCALED BACK OBJECTIVE PROGRESS
status = solver.Solve(model)
print(list(map(lambda x: solver.Value(x), [tax_component_a, tax_component_b, tax_component_c, tax_full_scaled])))
print(solver.ObjectiveValue()) # SCALED BACK OBJECTIVE
Output (excerpt)
...
...
#1 0.00s best:30 next:[30,29.999] fixed_bools:0/1
#Done 0.00s
CpSolverResponse summary:
status: OPTIMAL
objective: 30
best_bound: 30
booleans: 1
conflicts: 0
branches: 1
propagations: 0
integer_propagations: 2
restarts: 1
lp_iterations: 0
walltime: 0.0039022
usertime: 0.0039023
deterministic_time: 8e-08
primal_integral: 1.91832e-07
[15625, 4289, 0, 300545]
30.0

Odd and even pages footer - page X of Y in powershell

I would like to generate word documents in Powershell with different footer on even and odd pages.
I would like to have text with data on left side, and Page X of Y on right side on one page and reverse combination on next page.
First problem is in X of Y format. And second problem I have with placing text with field in one footer. If I put field, the text was disappear, and when I put text, field was disappearing.
PowerShell add field codes to ms word footer - does not work in my case.
I will be grateful for your help.
$dat = Get-Date -Format yyyy-MM-dd
$word = New-Object -ComObject word.application
$word.Visible = $false
$doc = $word.documents.add()
$doc.PageSetup.OddAndEvenPagesHeaderFooter = $true
$selection = $word.Selection
# ...
# content
# ...
$section = $doc.sections.item(1)
$footer = $section.Footers(1)
$Range = $footer.Range
$Range.Text = "Some text($dat)"
$Range.ParagraphFormat.Alignment = 0
$footer.PageNumbers.Add(2)
$Range.Font.Size = 10
$footer = $section.Footers(3)
$Range = $footer.Range
$Range.Text = "Some text($dat)"
$Range.ParagraphFormat.Alignment = 2
$footer.PageNumbers.Add(0)
$Range.Font.Size = 10
$outputPath = 'C:\FileToDocx.docx'
$doc.SaveAs($outputPath)
$doc.Close()
$word.Quit()
The problem is also that the $footer.PageNumbers.Add() is global and it does not depend from my odd and even footer range.
Also I was tried resolve my problem by swap PageNumbers to combination of $Range.Fields.Add($Range, 26) and $Range.Fields.Add($Range, 33), e.g.
$fieldsPage = $Range.Fields.Add($Range, 33)
$sumField = $fieldsPage.Result.Text
$fieldsNumPages = $Range.Fields.Add($Range, 26)
$sumField += ' of ' + $fieldsNumPages.Result.Text
$range.Text = "Some text($dat)`t`tPage $sumField"
but in this case I have static string. I don't know how to use this two type of fields with static text with $dat in footer without conversion to string. The footer forces me to use fields, because only they can be different on each page.

QlikSense - Set Analysis - Handling complexities - Arithmetic, Fields, Variables, Variables within variables, Greater than etc

I am somewhat new to QlikSense, but am getting a hang of it. Set Analysis is probably my weak spot and no matter how much I read, I tend to forget everything within hours. Plus, the guides don't do a great job explaining how to handle more complex/'tricky' situations (aka Level II or III complexity) than what they deem complex (aka Level 1 complexity) .
I went through this, this and this, still no dice. The only thing left for me to do is to bang my head to the wall and see if something shakes up.
The actual file is pretty big and proprietary, so can't post it here... so I would appreciate if you can give me an idea and point me in the right direction.
GOAL:
I have an expression that works, but I need it in the form of set analysis. Simple, right?
BACKGROUND:
//IN LOAD SCRIPT - set some default values
SET dMinSOS = 20000;
SET dMaxSUSPD = 225;
SET dSUR = 1;
SET dSOR = 0.3;
//IN LOAD SCRIPT - generate some custom inputs so user can select a value
FOR i = 1 to 20
LET counter = i*5000;
LOAD * INLINE [
Min. SOS
$(counter)
];
NEXT i
FOR i = 0 to 9
LET counter = i/10;
LOAD * INLINE [
SOR
$(counter)
];
NEXT i
FOR i = 1 to 30
LET counter = i/10;
LOAD * INLINE [
SUR
$(counter)
];
NEXT i
FOR i = 1 to 15
LET counter = i*25;
LOAD * INLINE [
Max. SUSPD
$(counter)
];
NEXT i
//IN LOAD SCRIPT - if user selects a value from above, then get the max because they can select multiple; otherwise use default values
SET vMinSOS = "IF(ISNULL([Min. SOS]), $(dMinSOS), MAX([Min. SOS]))";
SET vMaxSUSPD = "IF(ISNULL([Max. SUSPD]), $(dMaxSUSPD), MAX([Max. SUSPD]))";
SET vSUR = "IF(ISNULL([SUR]), $(dSUR), MAX([SUR]))";
SET vSOR = "IF(ISNULL([SOR]), $(dSOR), MAX([SOR]))";
//EXPRESSION - works! - [Size], [Heads], [SPD] are direct fields in a table, the return value of 1 or 0 is strictly for reference
=IF(
[Size] >= $(vMinSOS) AND
[Size] - ((([Heads] * IF([SPD] >= $(vMaxSUSPD), $(vMaxSUSPD), [SPD])) / $(vSUR)) + ([Size] * $(vSOR))) >= 0,
1, 0)
//SET ANALYSIS - this needs fixing - i.e. replicate 2nd condition in expression above - Show just the results where both the conditions above are true
=SUM({<
[Size]={">=$(=$(vMinSOS))"},
[Size]={">= #### What goes here? #### "},
>}[Size])
Open to recommendations on better ways of solving this.
=SUM({
"=[Size] >= $(vMinSOS) AND [Size] - ((([Heads] * IF([SPD] >= $(vMaxSUSPD), $(vMaxSUSPD), [SPD])) / $(vSUR)) + ([Size] * $(vSOR))) >= 0"
}>} [Size] )

PowerShell HashTable - self referencing during initialization

I have a theoretical problem - how to reference a hash table during its initialization, for example, to compute a member based other already stated members.
Remove-Variable myHashTable -ErrorAction Ignore
$myHashTable =
#{
One = 1
Two= 2
Three = ??? # following expressions do not work
# $This.One + $This.Two or
# $_.One + $_.Two
# $myHashTable.One + $myHashTable.Two
# ????
}
$myHashTable.Three -eq 3 # make this $true
Any ideas how to do it? Is it actually possible?
Edit:
This was my solution:
$myHashTable =
#{
One = 1
Two= 2
}
$myHashTable.Three = $myHashTable.One + $myHashTable.Two
This won't be possible using the object initializer syntax I'm afraid. While it is possible to use variables, you'll have to compute the values before creating the object.
I cannot recommend this, but you can iterate the initializer twice or more:
(0..1) | %{
$a = #{
One = 1
Two = $a.One + 1
}
}
(0..2) | %{
$b = #{
One = 1
Two = $b.One + 1
Three = $b.Two + 1
}
}
Make sure all calculations are idempotent, i.e. do not depend on a number of iterations.
You can also recur to this...
sometimes when the hashtable is very long
and can be defined only in 2 or three recurrences...
works fine:
$AAA = #{
DAT = "C:\MyFolderOfDats"
EXE = "C:\MyFolderOfExes"
}
$AAA += #{
Data = $AAA.DAT + "\#Links"
Scripts = $AAA.EXE + "\#Scripts"
ScriptsX = $AAA.EXE + "\#ScriptsX"
}
Note in the second part we are just adding ( += ) more items to the first part... but now... we can refer the items in first part
of the hashtable

List of images as subpart in Typo3

At current I'm making a list of images for a banner slider using code as follows:
page.10.marks.topimage = IMAGE
page.10.marks.topimage {
file.import.data = levelmedia: -1, "slide"
file.import = fileadmin/user_upload/
file.import.override.field = media
file.import.current = 1
file.import.listNum = 0
border = 0
file.height = 670
file.width = 1800
altText = Banner
titleText = Banner
wrap = <div id="slides">|
}
page.10.marks.topimage1 = IMAGE
page.10.marks.topimage1 {
file.import.data = levelmedia: -1, "slide"
file.import = fileadmin/user_upload/
file.import.override.field = media
file.import.current = 1
file.import.listNum = 1
border = 0
file.height = 670
file.width = 1800
altText = Banner
titleText = Banner
}
etc...
However, this means, every time the other admins want to add a new slide or remove one from the total count, I have to change this code. Adding the content of the slides is not a problem, they simply upload to user_upload and it pulls 0 to 3 at current. However, they want to be able to upload 5 images and have it show 5 or just 3 and have it show 3 and I need a more dynamic way to implement this. I'm still new to Typo3 (i really don't understand it, php is 10,000X easier!), so if anyone could, please explain to me better than the docs, how subparts work or what my solution might be.
And no I can't just write an extension to do it. Been there and tried that and still can't figure out how to get extensions in without breaking it.
FYI, if you could break it down and help me "like" it, that would be great, because at current, I'd rather they use wordpress or joomla or ANYTHING but this. If you've seen my other questions, then you'll realize, i've had 0 fun working with this cms and mostly because the documentation and/or "help" i've received has been almost completely useless to me. I only mention this so that maybe someone will break this down for me like i break down jquery/php/.net questions for others. It doesn't hurt to be polite and show a nub "step-by-step" instructions!
page.10.marks.topimage = TEXT
page.10.marks.topimage {
# retrieve data
data = levelmedia: -1, "slide"
override.field = media
# we have some filenames in a list, let us split the list
# and create images one by one
# if there are five images selected, the CARRAY "1" will be executed
# five times where current is loaded with only one filename
split {
# the images are separated via ","
token = ,
# you can do funny stuff with options split, f.e. if you want to give first
# and last image a different class... but thats another topic;)
# we just say, render every splitted object via CARRAY "1"
cObjNum = 1
1 {
# just render the single image,
# now there should be one filename in current only
10 = IMAGE
10 {
file.import.wrap = fileadmin/user_upload/|
file.import.current = 1
border = 0
file.height = 670
file.width = 1800
altText = Banner
titleText = Banner
}
}
}
}