πŸ‘︎ 210
πŸ’¬︎
πŸ‘€︎ u/thinker227
πŸ“…︎ Jan 30 2022
🚨︎ report
"arr.forEach()" vs "for(i=0; i < arr.length; i++){}"

What's the difference?

πŸ‘︎ 71
πŸ’¬︎
πŸ‘€︎ u/abzurt_96
πŸ“…︎ Jan 28 2022
🚨︎ report
Hopefully, one look, we can differentiate onEach and forEach
πŸ‘︎ 57
πŸ’¬︎
πŸ‘€︎ u/ElyeProj
πŸ“…︎ Jan 22 2022
🚨︎ report
Similar but completely different: map, onEach, and forEach
πŸ‘︎ 68
πŸ’¬︎
πŸ‘€︎ u/ElyeProj
πŸ“…︎ Jan 23 2022
🚨︎ report
QuerySelectorAll ForEach not working

[SOLVED] Hi,

I got a little issue. I have a possible ton of buttons and with the class .post-action-btn and want to give them all a click eventlistener. But somehow the forEach does not work.

Here's my code:

document.querySelectorAll(".post-action-btn").forEach(elem =&gt; {
    elem.addEventListener("click", function(){
        console.log(elem);
        switch(elem.dataset.action){
            case "like":
                console.log("Like: " + elem);
                break;
            case "comment":
                console.log("Comment: " + elem);
                break;
            case "save":
                console.log("Save: " + elem);
                break;
            case "more":
                console.log("More: " + elem);
                break;
        }
    });
});

The queryselector is correct and does what it should, but as soon as we come to the forEach(), nothing is working anymore.

Does someone know what's the issue here?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/ncls-
πŸ“…︎ Jan 19 2022
🚨︎ report
How can I use a ForEach value to refer to a let variable part? First picture is how I want it to work, second is how it works - but without using the ForEach value reddit.com/gallery/rud0n0
πŸ‘︎ 13
πŸ’¬︎
πŸ‘€︎ u/lau796
πŸ“…︎ Jan 02 2022
🚨︎ report
Flow Designer Ask for Approval in foreach loop

I'm building a flow in flow designer that looks up multiple user records, creates a req, then creates a ritm for each record returned and will create a service catalog task based on the approval action. I can create my req and ritm(for each user record returned) but when I use a for each loop for the ask for approval, it will not move to the next ritm until the previous approval has been responded to. I need all approval requests to be generated at the same time. Is this possible in flow designer?

πŸ‘︎ 5
πŸ’¬︎
πŸ“…︎ Jan 14 2022
🚨︎ report
Understand ForEach

let strings = ["Red", "Green", "Blue"]

ForEach(strings, id: .self) {

Button($0, action: {})

}

I looked at documentation and tutorials on this and it was above my level.

ForEach takes three arguments? Data, Id, and Content. The data is obviously something iterable, and the content is obviously the loop body.

β€œThe collection’s elements must conform to Identifiable.”

This is a protocol which guarantees that an object has some kind of identifier attribute? But it doesn’t care what that attribute is called?

So strings happen to have a .self attribute? I imagine many objects have this attribute?

And it returns some random numerical hash or something?

My understanding is basically you can either pass a variable name for the iterator:

ForEach(strings) { s in

print(s)

}

or use an β€œidentifiable” attribute in which case you would use $0 to reference it.

Can anyone comment on this β€œs in” syntax - I’ve never seen anything like it. It’s just the SwiftUI way of declaring a name for the namespace of a View? Does it support multiple variables ever, β€œs, l in”?

I can also use

strings.forEach { s in

print(s)

}

and

for s in strings {

print(s)

}

So does that mean basically:

The bottom is the most basic.

The above is just an alternative syntax to be called as an object method on some iterable object.

The topmost (ForEach) is just a third choice which allows you to use the β€œidentifiable” of some object?

Thanks very much.

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/jssmith42
πŸ“…︎ Jan 24 2022
🚨︎ report
Changing list values in foreach

I know you can't modify a list while its being scanned in a foreach statement or you get the InvalidOperationException: Collection was modified; enumeration operation may not execute.

I'm using a list => _list = list<string, Vector4>

foreach (listvalue value in _list) {

_list.Remove(value);

}

are there any workarounds to be able to do this?

πŸ‘︎ 3
πŸ’¬︎
πŸ“…︎ Jan 22 2022
🚨︎ report
Still can't wrap my head around jobs. Want to start a new one foreach object in my object

Hey all. I want to speed up this process as it obviously takes several minutes to ping a hundred servers and give me results. How can I set it up so that each object gets its own job, and the output is one object with all of those results?

$Test = foreach($ip in $list){
try{$connection=(invoke-webrequest -uri $($ip.ip) -TimeoutSec 5).StatusDescription}
catch{$connection="$_"}
$ping = if(((ping $ip.ip -n 1 -w 500)[5]) -like "*100% loss*"){"FAILED"}else{"SUCCESS"}
    [pscustomobject]@{
        Room = $ip.room
        Description = $ip.c
        IP = $ip.ip
        Ping = $ping
        Status = $connection
    }
}

The current output is like this, and this is what I want to end up with:

PS C:\Users\ME\Desktop&gt; $Test | ft

Room Description              IP           Ping    Status                                
---- -----------              --           ----    ------                                
111  Touch Button Controller  1.1.1.1      SUCCESS OK                                    
111  Touch Panel              1.1.1.1      SUCCESS Unable to connect to the remote server
111  Room Display             1.1.1.1      SUCCESS OK                                    
111  Control System Processor 1.1.1.1      FAILED  OK                                    
111  Touch Panel              1.1.1.1      SUCCESS Unable to connect to the remote server

Thanks for any assistance! My biggest confusion is receiving the results and pooling it into a single variable I guess.

πŸ‘︎ 24
πŸ’¬︎
πŸ‘€︎ u/MyOtherSide1984
πŸ“…︎ Dec 10 2021
🚨︎ report
ForEach and identificable

Hi all, this a probably a silly question, but why when using a foreach is required to pass self for the id when the collection of items don’t conform identificable? Couldn’t directly use the index in the collection as the id of each object?

πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/Open_Bug_4196
πŸ“…︎ Dec 26 2021
🚨︎ report
Issue with foreach loop

Hi, so I am trying to iterate through a list of words and saving the word with the highest value but I am running into the issue where when my word changes in the foreach loop, the value of my highest value word also changes. I'm not entirely sure how to fix it.

foreach (char[] word; range){
    value = GetValue(word);
    if (value &gt; highestValue){
        myWord = word;
        highestValue = value;
    }
writeln(myWord);
}

This is my code and it will always print the current word in the range regardless of if line 3 returns true or false. Any help is appreciated

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/sailor_ash
πŸ“…︎ Jan 15 2022
🚨︎ report
Can I include new Map() inside forEach function?

This is a question for a more elegant way of writing this line of code.

I have a list of dictionarys.

let array1 = [
  { key: "apple", value: 38498 },
  { key: "banana", value: 102854 },
  { key: "grape", value: 138762 },
  { key: "orange", value: 162017 },
];

To convert them to a map and my desired output I use this:

let map1Β =Β new Map();
array1.forEach(e =&gt;Β {Β map1.set(e.key,Β e.value)});

console.log(map1);

---

Map(4) {
  'apple' =&gt; 38498,
  'banana' =&gt; 102854,
  'grape' =&gt; 138762,
  'orange' =&gt; 162017
}

This works fine, but I am not quite happy of needing to create a new empty map.

I imagine it has to be possible to create a new map inside the forEach function and then return the map. How is this possible? I cant figure it out.

I imagine something like this:

 map1 = array1.forEach(e =&gt;Β {Β new Map().set(e.key,Β e.value)});

But this is obviously terribly wrong. Do you understand what I am trying to do?

πŸ‘︎ 3
πŸ’¬︎
πŸ“…︎ Jan 22 2022
🚨︎ report
How can I properly use TIMESHIFT to offset the animation of individual object in a FOREACH loop?

I want to offset the press of each individual button by a couple of frames so that they don't press at the same time. However, timeshift in a foreach loop doesn't work. Is there a different method to offsetting individual copytopoints objects in a foreach loop? Would be grateful for some help.(the animation is made by translating a sphere)

https://imgur.com/gallery/yKxZFxo

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/iriseq
πŸ“…︎ Jan 15 2022
🚨︎ report
Can this foreach / if else code be optimized (Performance wise)

Foreseeing answers such as "It doesn't make much impact so doesn't need optimization" I just want to clarify that this method will be called by timer x100 times per second, and I need to do so without triggering a higher performance CPU state, and keeping CPU at the lowest possible state.

My question is: is there a way to optimize the performance of this method?
Pastebin: https://pastebin.com/f3M3jg83

πŸ‘︎ 4
πŸ’¬︎
πŸ“…︎ Dec 22 2021
🚨︎ report
Draw a Line based on the previous line in a foreach loop

I am trying to draw a pattern based on some numbers. An example of the numbers would be 3891247. The code is below

Function Draw-Sigal {
    param (
        [string]$SigCode
    )
    [void][reflection.assembly]::LoadWithPartialName( "System.Windows.Forms")
    [void][reflection.assembly]::LoadWithPartialName( "System.Drawing")
    $Form            = New-Object Windows.Forms.Form
    $Form.ClientSize = "1000,1000"
    $FormGraphics    = $Form.CreateGraphics()
    $Pen             = new-object Drawing.Pen black
    
    $0 = "0","509","135"
    $1 = "1","275","210"
    $2 = "2","717","210"
    $3 = "3","153","386"
    $4 = "4","843","386"
    $5 = "5","153","614"
    $6 = "6","843","614"
    $7 = "7","275","788"
    $8 = "8","717","788"
    $9 = "9","509","864"

    $SigCodeToArray = $SigCode.ToCharArray()

    $DrawCode = @()
    foreach ($SCA in $SigCodeToArray) {
        if ($0 -contains $SCA) {$DrawCode += "$($0[1]),$($0[2])"}
        if ($1 -contains $SCA) {$DrawCode += "$($1[1]),$($1[2])"}
        if ($2 -contains $SCA) {$DrawCode += "$($2[1]),$($2[2])"}
        if ($3 -contains $SCA) {$DrawCode += "$($3[1]),$($3[2])"}
        if ($4 -contains $SCA) {$DrawCode += "$($4[1]),$($4[2])"}
        if ($5 -contains $SCA) {$DrawCode += "$($5[1]),$($5[2])"}
        if ($6 -contains $SCA) {$DrawCode += "$($6[1]),$($6[2])"}
        if ($7 -contains $SCA) {$DrawCode += "$($7[1]),$($7[2])"}
        if ($8 -contains $SCA) {$DrawCode += "$($8[1]),$($8[2])"}
        if ($9 -contains $SCA) {$DrawCode += "$($9[1]),$($9[2])"}
    }
    $DrawCode
    $PreviousCode = $DrawCode[0]
    foreach ($Code in $DrawCode) {
        $Pen          = New-Object Drawing.Pen black
        $ChildAnchor  = New-Object System.Drawing.PointF ("$($PreviousCode.Split(',')[0])","$($PreviousCode.Split(',')[1])")
        $ParentAnchor = New-Object System.Drawing.PointF ("$($Code.Split(',')[0])","$($Code.Split(',')[1])")
        $Form.add_paint({$FormGraphics.DrawLine($Pen, "$($PreviousCode.Split(',')[0])","$($PreviousCode.Split(',')[1])", "$($Code.Split(',')[0])","$($Code.Split(',')[1])")})
        {$FormGraphics.DrawLine($Pen, $ChildAnchor, $ParentAnchor)}.GetNewClosure()
        $PreviousCode = $Code
    }
    $Form.ShowDialog()
}

I am basing this code off some code I found on reddit ([https://w

... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/randomadhdman
πŸ“…︎ Jan 26 2022
🚨︎ report
Stuck with uninstall string in a foreach loop

I don't think this one would be too tricky to solve.

what I have so far:

$2013x86 = Get-ItemProperty -Path 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Where-Object {$_.Displayname -like 'Microsoft Visual C++ 2013 x86*'}

the above query will return about 6 results.

foreach($App in $2013x86) { Invoke-Command -ScriptBlock {&amp; $App.QuietUninstallString} }

the foreach loop isn't interpreting the "& $App.QuietUninstallString" as it should. it should interpret it as: & "C:\ProgramData\Package Cache\{f65db027-aff3-4070-886a-0d87064aabb1}\vcredist_x86.exe" /quiet /uninstall and execute the uninstall string. when I paste this manually into a PS console, it uninstalls quietly as it should. yet when it runs though the foreach loop I get:

& : The term '"C:\ProgramData\Package Cache\{050d4fc8-5d48-4b8f-8972-47c82c46020f}\vcredist_x64.exe" /uninstall /quiet' is not recognized as the name of a cmdlet, function, script file, or operable program.

Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

what am I missing here, or am I completely barking up the wrong tree when it comes to uninstalls? Thanks.

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/kHartouN
πŸ“…︎ Jan 06 2022
🚨︎ report
Foreach (2.3+)

Foreach made using macros. That means you don't have to pass variables as arguments

- arrays, lists, maps, structs, grids, strings and number ranges

https://github.com/mh-cz/GameMaker-Foreach

You can see some warnings about non existing variables. That's fine. These variables are created at runtime

πŸ‘︎ 18
πŸ’¬︎
πŸ‘€︎ u/maras_u11
πŸ“…︎ Jan 26 2022
🚨︎ report
Foreach loop damage

Hello

I am trying to use a foreach loop to detect enemy with specific tag.

I use it in a collision event but when I damage a enemy it applies to all the enemies with that tag.

Can I use foreach loop to damage only the enemy I am attacking?

thank you

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/hrohibil
πŸ“…︎ Jan 20 2022
🚨︎ report
Help with ForEach and Invoke Command

Hello All, I’m still new and learning powershell so go easy on me if this is a n00b question. I’ve managed to successfully create a For-Each script and an Invoke-Command script. Now I’m looking to combine these two together to run from my machine to remote machines, to install updates, but thats where I’m having issues. I’m not sure what int he script could be wrong. Here’s a sample of it:

#define sources $source = β€œ\sharedrive\software\excelUpdate.msp” $source2 = β€œ\sharedrive\software\wordUpdate.msp”

#Text file where IP address are stored $ForTest = Get-Content -Path β€œC:\temp\IPaddresses.txt”

ForEach ($name1 in $ForTest) {

Invoke-Command -ComputerName $name1 {

Copy-Item -Path $source -Destination β€œ\$name1\c$\temp” Copy-Item -Path $source2 -Destination β€œ\$name1\c$\temp”

Start-Process C:\temp\excelUpdate.msp Start-Sleep -Seconds 10

Start-Process C:\temp\wordUpdate.msp

} }

And I keep getting the error message saying:

Cannot bind argument to parameter β€˜Path’ because it is null. And Cannot validate argument β€˜ComputerName’. The argument is null or empty. Provide and argument that is not null or empty and then try the command again.

But Computer name shouldnt be empty because it should be the name1 which is a PC within the ForTest text file. I’m not sure where I’m going wrong with this..

πŸ‘︎ 15
πŸ’¬︎
πŸ‘€︎ u/Tito_Santana
πŸ“…︎ Nov 09 2021
🚨︎ report
ForEach loop logic fail

Working on the excercise "04_removeFromArray " and cannot understand the logic:

const removeFromArray = function(...args){

myArray = args[0]; newArray = [ ];

myArray.forEach(element=>{ if(!args.includes(element)){ newArray.push(element); } });

return newArray };

removeFromArray([1,2,3], 3, 4);

// this will return [1, 2] -> which is correct. Now, I don't understand why: since args = [1, 2, 3, 3, 4] and myArray = [ 1, 2 , 3], The forEach loops through myArray and if it finds an element which is not present in args, the element is sent to newArray.

But all elements in myArray is also in args. So I dont understand it. I am obviously not reading the meaning of what is in the if statement properly:

If element not included in the array 'args', then send it to 'newArray' which doesnt make sense given the answer I get.

Can someone please educate me?

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/Anna-Schmidt-RE
πŸ“…︎ Jan 02 2022
🚨︎ report
I'm making a "foreach" loop to use for an item order queue, and deleting from it aborts the process. What should I do instead?

I apologize but I think to truly spell this out I may need to post the whole code. This is intended to be more-or-less a replica of Command & Conquer games' construction system. Those familiar with that will probably get more of where I'm going with the code, but just in case they don't, I will explain it. Here's the code:

public class UnitProduction : MonoBehaviour
{
    public GameObject controller;
    public GameObject unit1;
    public float unit1Cost;
    public float currentUnitCost;
    public float paymentDue;
    public float paymentProgress;
    public float buildingProgress;
    //This variable was moved here from StatsAndStuff when it was discovered this script had trouble accessing it.
    public float myFunds;

    public enum productionPhase
    {
        INACTIVE,
        STALLED,
        PAYING,
        BUILDING,
        UNITREADY,
    };
    public productionPhase currentPhase;

    public List&lt;GameObject&gt; productionQueue = new List&lt;GameObject&gt;();
    

    // Start is called before the first frame update
    void Start()
    {
        currentPhase = productionPhase.INACTIVE;
        unit1Cost = unit1.GetComponent&lt;MoveInTheMesh&gt;().hitPoints + unit1.GetComponent&lt;MoveInTheMesh&gt;().moveSpeed
        + unit1.GetComponent&lt;MoveInTheMesh&gt;().attackStrength + unit1.GetComponent&lt;MoveInTheMesh&gt;().attackSpeed
        + unit1.GetComponent&lt;MoveInTheMesh&gt;().attackRange;
    }

    // Update is called once per frame
    void Update()
    {
        if (productionQueue.Count &gt; 0)
            {
                foreach (GameObject currentlyBuildingUnit in productionQueue)
                {
                    currentUnitCost = (currentlyBuildingUnit.GetComponent&lt;MoveInTheMesh&gt;().hitPoints + currentlyBuildingUnit.GetComponent&lt;MoveInTheMesh&gt;().moveSpeed
        + currentlyBuildingUnit.GetComponent&lt;MoveInTheMesh&gt;().attackStrength + currentlyBuildingUnit.GetComponent&lt;MoveInTheMesh&gt;().attackSpeed
        + currentlyBuildingUnit.GetComponent&lt;MoveInTheMesh&gt;().attackRange);
                    paymentDue = currentUnitCost / 5;
                    if (currentPhase == productionPhase.INACTIVE)
                    {
                        if (paymentDue &gt; myFunds)
                        {
... keep reading on reddit ➑

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/Flodo_McFloodiloo
πŸ“…︎ Dec 07 2021
🚨︎ report
foreach problem

Please can you tell me why this cycle doesn't work? $cleandata should be a list of item. But is $null. foreach should cycle through lines and give me all the lines..

$StockData = @(

"Date,Open,High,Low,Close,Volume,Adj Close"

"2012-03-30,32.40,32.41,32.04,32.26,31749400,32.26"

"2012-03-29,32.06,32.19,31.81,32.12,37038500,32.12"

"2012-03-28,32.52,32.70,32.04,32.19,41344800,32.19"

"2012-03-27,32.65,32.70,32.40,32.52,36274900,32.52"

"2012-03-26,32.19,32.61,32.15,32.59,36758300,32.59"

"2012-03-23,32.10,32.11,31.72,32.01,35912200,32.01"

"2012-03-22,31.81,32.09,31.79,32.00,31749500,32.00"

"2012-03-21,31.96,32.15,31.82,31.91,37928600,31.91"

"2012-03-20,32.10,32.15,31.74,31.99,41566800,31.99"

"2012-03-19,32.54,32.61,32.15,32.20,44789200,32.20"

"2012-03-16,32.91,32.95,32.50,32.60,65626400,32.60"

"2012-03-15,32.79,32.94,32.58,32.85,49068300,32.85"

"2012-03-14,32.53,32.88,32.49,32.77,41986900,32.77"

"2012-03-13,32.24,32.69,32.15,32.67,48951700,32.67"

"2012-03-12,31.97,32.20,31.82,32.04,34073600,32.04"

"2012-03-09,32.10,32.16,31.92,31.99,34628400,31.99"

"2012-03-08,32.04,32.21,31.90,32.01,36747400,32.01"

"2012-03-07,31.67,31.92,31.53,31.84,34340400,31.84"

"2012-03-06,31.54,31.98,31.49,31.56,51932900,31.56"

"2012-03-05,32.01,32.05,31.62,31.80,45240000,31.80"

"2012-03-02,32.31,32.44,32.00,32.08,47314200,32.08"

"2012-03-01,31.93,32.39,31.85,32.29,77344100,32.29"

"2012-02-29,31.89,32.00,31.61,31.74,59323600,31.74"

)

$cleandata = foreach ($date in $StockData){

$s= $date -split ','

}

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Rich-Spinach-7824
πŸ“…︎ Nov 27 2021
🚨︎ report
Foreach loop that copies picture on to another picture

I have two directories with the exact same file names, but they are different pictures:

Directory1                  Directory2
----------------------------------------------
01A-001-EF13.png            01A-001-EF13.png
1092159E+11.png             1092159E+11.png
1.png                       1.png
1-0001A-ROOF.png            1-0001A-ROOF.png

Yesterday I found a function called Add-Logo where you can copy one picture and paste it on to the other. I would like to have a loop that runs through each file name, compares the two to make sure they match, then perform the copy (copy the picture from Directory2 onto the picture in Directory1)

What I have so far is:

$Codes = Get-ChildItem -Recurse -Path "D:\Codes"
$Assets = Get-ChildItem -Recurse -Path "D:\Assets"

foreach ($_ in $Codes) {
    if ($_ -eq $Assets) {
        Add-Logo -LogoPictureFile $Assets -BackgroundPictureFile $_ -ProportionFactor 2
    }
}

It will run and not throw any errors at me, but it doesn't create the new picture with both of them merged. I can get it to work with a single file by using:

$Original = "D:\Codes\01A-001-EF13.png"
$Label = "D:\Assets\01A-001-EF13.png"

Add-Logo -LogoPictureFile $Label -BackgroundPictureFile $Original -ProportionFactor 2

But I have 22k pictures I need to merge and would like to come up with an automated way to do it rather than type each filename one by one.

Ideas? :)

UPDATE: GOT IT! Thanks to r/engageant :D

Here is the final code in case it might help anyone out (I left the Add-Logo function condensed for readability):

function Add-Logo {
}

## Directory locations
$Codes = Get-ChildItem -Recurse -Path "D:\QRCodes"
$Assets = Get-ChildItem -Recurse -Path "D:\Assets"

## If the file name matches, copy it to the QR Code
foreach ($file in $Assets) {
    if ($file.Name -in $Assets.Name) {
        Add-Logo -LogoPictureFile "D:\Assets\$($file.Name)" -BackgroundPictureFile "D:\QRCodes\$($file.Name)" -ProportionFactor 2
    }
}

This ensures that both picture filenames are the same. If so, it will copy the picture from Assets to the QRCodes picture with the same name.

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/ZebulaJams
πŸ“…︎ Dec 02 2021
🚨︎ report
[Q] Variable "of" not found in foreach loop?

[Solved]

Hello everyone!

I'm a real beginner with Stata as I do most of my stuff with R, and I'm facing some trouble trying to execute a do file. Stata gives me the following error.

https://preview.redd.it/5rhc7ya4f1481.png?width=222&format=png&auto=webp&s=444ce45d8fb504f85139dc02a80cb33adf07adbd

I know that what the do file is doing is some kind of for loop, so the "of" shouldn't be recognized as a variable. I'm running Stata 15. Is there anything i'm doing wrong? Please let me know-it's important.

Edit: Ah, whatever, code below:

cap ssc install sumdist
gen quintall=.
levelsof wave , local(W)
cap recode r16 (.c=0), gen(tempr16)
foreach w of local W {
    if `w'==2004 levelsof pais if wave==`w' &amp; inrange(pais, 1, 10), local(K)
    if `w'==2006 levelsof pais if wave==`w' &amp; inrange(pais, 1, 13) | pais==16 | inrange(pais, 18, 24), local(K)
    if `w'==2008 levelsof pais if wave==`w' &amp; inrange(pais, 1, 24) | pais==26 , local(K)
    if inrange(`w', 2010, 2018) levelsof pais if wave==`w' &amp; pais&lt;40, local(K)
    foreach k of local K {
        qui levels of ur if pais==`k' &amp; wave==`w', local(U)
        foreach u of local U {
            if `w'==2004 qui pca r1 r3 r4 r5 r6 r7 r12 if pais==`k' &amp; ur==`u' &amp; wave==`w'
            if inlist(`w', 2006, 2008) qui pca r1 r3 r4 r4a r5 r6 r7 r8 r12 r14 r15 if pais==`k' &amp; ur==`u' &amp; wave==`w'
            if `w'==2010 qui pca r1 r3 r4 r4a r5 r6 r7  r8 r12 r14 r15 r16 r18 if pais==`k' &amp; ur==`u' &amp; wave==`w'
            if `w'==2012 qui pca r1 r3 r4 r4a r5 r6 r7 r8 r12 r14 r15 r16 if pais==`k' &amp; ur==`u' &amp; wave==`w'
            if inrange(`w', 2014, 2018) qui pca r1 r3 r4 r4a r5 r6 r7 r8 r12 r14 r15 tempr16 r18 if pais==`k'&amp; ur==`u' &amp; wave==`w'
            qui predict _f1 if pais==`k' &amp; ur==`u' &amp; wave==`w'
            qui sumdist _f1 !mi(_f1), n(5) qgp(_quint)
            qui replace quintall=_quint if pais==`k' &amp; ur==`u' &amp; wave==`w'
            drop _quint _f1
        }
    }
}
cap drop tempr16

Edit 2: This question has been solved! Thank you all who contributed, turns out there were two errors. First, as told by u/rogomatic and u/anAnonymousEconomist, it should be levelsof, not levels of. Then, an ! invalid name error poped up, which was because it should have been qui sumdist_f1 if !mi(); e.g. an if was missing in this

... keep reading on reddit ➑

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/damageinc355
πŸ“…︎ Dec 07 2021
🚨︎ report
[2021 Day 06 part2] [JS] forEach loop efficiency problem?

Hi, I am trying to solve day6's part2 but the forEach loop doens't seems to end and never returns a answer.

I used a for loop because it worked at part1, but I was told that it only results because it's only 80 days and with 256 it would cause an eddiciency problem, so I switched to a forEach loop, but it stills doesn't work...

const fs = require("fs");

var input = fs.readFileSync(`${__dirname}/input.txt`, "utf8");
var fishes = input.split(",").map(n =&gt; Number(n));

const days = 256;
var totalFishNumber;

for(i = 0; i &lt; days; i++)
{
	var j = 0;
    fishes.forEach(fish =&gt; {

        if(fish === 0)
        {
            fishes[j] = 6;
            fishes.push(8);
        }
        else
        {
            fishes[j]--;
        }

		j++;
	});
}

totalFishNumber = fishes.length;
console.log(`\nLanternfishes: ${totalFishNumber}`);

Update:

I modified my code as suggested in the comments section and after a long time, I finally understand what I needed to do. I had seen this solution in another posts as well but I didn't really understood the logic.

I posted my solution on github with some comments trying to explain the logic.

Thank you

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/JPTRON
πŸ“…︎ Dec 13 2021
🚨︎ report
PS Newbie : Working with multiple variables in an foreach loop

Hi,
I could use some help using powershell.
I need a script which shares a list of folders as the foldername

I found the following powershell line to get what i need.

New-SmbShare -Name TestShare -path c:\temp\sharefolder -FullAccess Administrators

I also have 2 command lines to get the info in a variable.
This puts the complete path to the shared folder in $Folders

$Folders = Get-ChildItem -Path C:\temp\ShareFolder -Recurse -Directory | Select-Object Fullname

And i have a command line to put the name of the share in the variable $shares

$shares = Get-ChildItem -Path C:\temp\ShareFolder -Recurse | Select-Object Name

I need a script with a foreach command (i think) which takes a $share from $shares and a $folder from $folders to create a share.

Thanks for the help.

πŸ‘︎ 22
πŸ’¬︎
πŸ‘€︎ u/Cookie197211
πŸ“…︎ Nov 10 2021
🚨︎ report
workflow weirdness with foreach -parallel

I'm trying to learn about workflows. This code output randomly repeats the input. Why?

$coll = $null
$numbers = 1..10
Write-host "Count of input:$($numbers.count)"
workflow test-parallel {           
  param(
    [object]$things
  )        
  $report_output = @()
  foreach -parallel ($thing in $things) {  
    InlineScript {
      $result = $using:thing
      $result
    }
    $workflow:report_output += $result     
  }
  $report_output                          
}
$coll = test-parallel -things $numbers
Write-host "Count of output:$($coll.count)"

Example output. https://drive.google.com/file/d/1HzWzAUBs7NnvfqqgWZAqsExUjZcw81ql/view

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/smarsha
πŸ“…︎ Dec 22 2021
🚨︎ report
Remove-LocalUser with foreach vs ForEach-Object

Hi Guys,

I just encountered something weird that I cannot explain.

I created a function to add localusers, and then I tried to get them, and pass them to Remove-LocalUser, but only half the users get removed.

My original function can be found here : https://gist.github.com/webtroter/70047cd16aa1bbf6b8e7a3914723a4d2

Example :

I create five users, and I can display them with Get-LocalUser | ? {$_.Description -eq "Created Automatically"} :

Name        Enabled Description
----        ------- -----------
test_user_0 True    Created Automatically
test_user_1 True    Created Automatically
test_user_2 True    Created Automatically
test_user_3 True    Created Automatically
test_user_4 True    Created Automatically

But I cannot remove them all with Get-LocalUser | ? {$_.Description -eq "Created Automatically"} | Remove-LocalUser, test_user_1 and test_user_3 are still there. Even more weird, running the same command with -WhatIf gives me the 5 users to be removed.

Then I tried with Get-LocalUser | ? {$_.Description -eq "Created Automatically"} | % { Remove-LocalUser $_ }, with the same result, half the user were left.

Finally, I was able to remove them all with foreach ($curUser in (Get-LocalUser | ? {$_.Description -eq "Created Automatically"})) { Remove-LocalUser $curUser}.

Can someone explain why?

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/webtroter
πŸ“…︎ Dec 01 2021
🚨︎ report
Perl blead has a new foreach syntax for hashes

Ricardo Signes just landed a new foreach syntax in Perl blead. The next version of Perl will have a cleaner way to iterate over a hash:

Previous:

foreach my $key (keys %hash) {
    my $val = $hash{$key};
    
    print "$key =&gt; $val\n";
}

New:

foreach my ($key, $val) (%hash) {
    print "$key =&gt; $val\n";
}
πŸ‘︎ 41
πŸ’¬︎
πŸ‘€︎ u/scottchiefbaker
πŸ“…︎ Oct 16 2021
🚨︎ report
Can variables not be passed into ForEach-Object loops?

I'm finding that when I attempt to create a variable for an overall script, but then call that variable inside of a foreach-object loop, the loop doesn't seem to think the variable has anything inside of it. But other parts of the script work as if the variable is just fine.

So this fails to work as desired, just pulls some random set of mailboxes.

$UserUPN = first.last@domain.com
$allmailbox = Get-ExoMailbox -ResultSize Unlimited
$allmailbox | ForEach-Object -parallel {
Get-ExoMailboxFolderPermission -Identity "$($_.PrimarySmtpAddress):\calendar" | Where-object {$_.User -match $UserUPN}}

The only way I got the loop to behave as desired was to put the same variable into the start of the loop, so it effectively sets the variable over and over again. Works, but it's weird and I'd rather set a single variable that all parts of the script can use than try to remember to set it in multiple places.

$allmailbox = Get-ExoMailbox -ResultSize Unlimited  
$allmailbox | ForEach-Object -parallel {  
$UserUPN = first.last@domain.com 
Get-ExoMailboxFolderPermission -Identity "$($_.PrimarySmtpAddress):\calendar" | Where-object {$_.User -match $UserUPN}}

ETA: I found the scriptblock documentation expanding variables into them. Not sure that's the ideal method here.

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/Maladal
πŸ“…︎ Nov 02 2021
🚨︎ report
let your notebook feels foreach with this sticker. Link in comments
πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/hallysuper
πŸ“…︎ Dec 22 2021
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.