问:
App Center automate branch deployments without manually cloning configuration
The issue I have is at the moment if I push a new branch to GitHub I have to go to App Center and manually clone/configure the build for this branch.

I would like to have a common build configuration for let's say all branches prefixed with featured that would be used in App Center and trigger a build on push.

Is it possible to deploy new branches on push without manually configuring/cloning the build in App Center?

答:
Yes its possible via AppCenter CLI - here is an example script:

Related discussion

```<code>#!/usr/bin/env bash

CURRENT_BRANCH=$(git branch --show-current)
OWNER_NAME="XXXXXXX"
APP_NAME_IOS="xxxxxx"
APP_NAME_ANDROID="xxxxxx"

function clone_build {
  local current_branch_encoded=$(sed 's/\//\%2f/g' <<< $1)  # replace strings in branch name, change "/" to "%2f" and others non url friendly
  local os=$2
  local app=$3
  local token=$4
  local from_clone=$5

  printMsg "Cloning app: ${app}, branch: ${CURRENT_BRANCH}"
  printMsg "Validating if AppCenter config is currently defined"
  if [ "$(curl -sL -w "%{http_code}" -X GET "https://api.appcenter.ms/v0.1/apps/${OWNER_NAME}/${app}/branches/${current_branch_encoded}/config" -H "accept: application/json" -H "X-API-Token:${token}" -o /dev/null)" = 200 ]; then
    printMsg "AppCenter config already defined"
  else
    if [ "$(curl -sL -w "%{http_code}" -X POST "https://api.appcenter.ms/v0.1/apps/${OWNER_NAME}/${app}/branches/${current_branch_encoded}/config" -H "accept: application/json" -H "X-API-Token:${token}" -H "Content-Type: application/json" -d "{\"cloneFromBranch\": \"${from_clone}\"}" -o /dev/null)" = 200 ]; then
      printMsg "AppCenter config cloned successfully"
    else
      printMsg "AppCenter config cloned failed"
    fi
  fi

  echo ""
}

# Android
clone_build $CURRENT_BRANCH "Android" ${APP_NAME_ANDROID} "$API_TOKEN" "$CLONE_BRANCH"
appcenter build queue --branch $CURRENT_BRANCH --app ${OWNER_NAME}/${APP_NAME_ANDROID}

# IOS
clone_build $CURRENT_BRANCH "iOS" ${IOS_APP_NAME} "$API_TOKEN" "$CLONE_BRANCH"
appcenter build queue --branch $CURRENT_BRANCH --app ${OWNER_NAME}/${IOS_APP_NAME}
</code>```

Body:
Yes its possible via AppCenter CLI - here is an example script:

Related discussion

#!/usr/bin/env bash

CURRENT_BRANCH=$(git branch --show-current)
OWNER_NAME="XXXXXXX"
APP_NAME_IOS="xxxxxx"
APP_NAME_ANDROID="xxxxxx"

function clone_build {
  local current_branch_encoded=$(sed 's/\//\%2f/g' <<< $1)  # replace strings in branch name, change "/" to "%2f" and others non url friendly
  local os=$2
  local app=$3
  local token=$4
  local from_clone=$5

  printMsg "Cloning app: ${app}, branch: ${CURRENT_BRANCH}"
  printMsg "Validating if AppCenter config is currently defined"
  if [ "$(curl -sL -w "%{http_code}" -X GET "https://api.appcenter.ms/v0.1/apps/${OWNER_NAME}/${app}/branches/${current_branch_encoded}/config" -H "accept: application/json" -H "X-API-Token:${token}" -o /dev/null)" = 200 ]; then
    printMsg "AppCenter config already defined"
  else
    if [ "$(curl -sL -w "%{http_code}" -X POST "https://api.appcenter.ms/v0.1/apps/${OWNER_NAME}/${app}/branches/${current_branch_encoded}/config" -H "accept: application/json" -H "X-API-Token:${token}" -H "Content-Type: application/json" -d "{\"cloneFromBranch\": \"${from_clone}\"}" -o /dev/null)" = 200 ]; then
      printMsg "AppCenter config cloned successfully"
    else
      printMsg "AppCenter config cloned failed"
    fi
  fi

  echo ""
}

# Android
clone_build $CURRENT_BRANCH "Android" ${APP_NAME_ANDROID} "$API_TOKEN" "$CLONE_BRANCH"
appcenter build queue --branch $CURRENT_BRANCH --app ${OWNER_NAME}/${APP_NAME_ANDROID}

# IOS
clone_build $CURRENT_BRANCH "iOS" ${IOS_APP_NAME} "$API_TOKEN" "$CLONE_BRANCH"
appcenter build queue --branch $CURRENT_BRANCH --app ${OWNER_NAME}/${IOS_APP_NAME}


来源: stackexchange

问:
jQuery Address / Deep Linking Issue
I have a tabbed section on a website I'm currently developing, and would like to enable unique URLs for each tab, as well as history support.

It seems the jQuery Address plugin is the way to go, but I'm having trouble implementing it. I'm able to assign URLs and change the address bar. The back button traverses URLs, but doesn't actually change the tabs.

The Address documentation isn't great. I'm assuming I'm missing some sort of event listener, but I'm not sure how to initialize it or what to apply it to.

Here is my JS

```<code>$('.sm-tab').click(function() {
    $.address.value($('a', this).attr('href'));
    smReset();
    $('#sm-tabs').find('.active').each(function() {
        $(this).removeClass('active');
        $(this).addClass('inactive');
    });
    $(this).removeClass('inactive');
    $(this).addClass('active');
    var smClassArray = $(this).attr('class').split(" ");
    var smDivClass = smClassArray[1];
    $('#'+smDivClass).show();
});
</code>```

My HTML looks something like this

```<code><div id="sm-tabs">
    <div class="sm-tab inactive twitter">
        <span class="twitter sprite-sm-twitter"><a href="?tab=twitter" class="hidetext">Twitter</a></span>
    </div>
    <div class="sm-tab inactive youtube">
        <span class="youtube sprite-sm-youtube"><a href="?tab=youtube" class="hidetext">YouTube</a></span>
    </div>
</div>

<div id="sm-widgets">
    <div id="twitter">
        Content
    </div>
    <div id="youtube">
        Content
    </div>
</div>
</code>```

答:
Using hashes for ajax navigation is going to open you to a whole can of worms.

Try this deep-linking script which uses the HTML5 History API instead.

ContentLicense: CC BY-SA 3.0

Title: jQuery Address / Deep Linking Issue

Body:
I have a tabbed section on a website I'm currently developing, and would like to enable unique URLs for each tab, as well as history support.

It seems the jQuery Address plugin is the way to go, but I'm having trouble implementing it. I'm able to assign URLs and change the address bar. The back button traverses URLs, but doesn't actually change the tabs.

The Address documentation isn't great. I'm assuming I'm missing some sort of event listener, but I'm not sure how to initialize it or what to apply it to.

Here is my JS

$('.sm-tab').click(function() {
    $.address.value($('a', this).attr('href'));
    smReset();
    $('#sm-tabs').find('.active').each(function() {
        $(this).removeClass('active');
        $(this).addClass('inactive');
    });
    $(this).removeClass('inactive');
    $(this).addClass('active');
    var smClassArray = $(this).attr('class').split(" ");
    var smDivClass = smClassArray[1];
    $('#'+smDivClass).show();
});

My HTML looks something like this

        Twitter

        YouTube

        Content

        Content


问:
Difference when executing a piece of code in main versus calling it as a function in golang
I am trying to do a CPU-intensive operation in GO. The code is pretty straight forward and I am trying to measure it as well. The measurement code looks like this

However, when I try to execute the same code as a function (invoked from main) it seems to work much faster. Any idea as to why this is happening?
package main

```<code>import (
       "fmt";
       "time"
    )

func addlist1 (from uint64, to uint64) {
var i uint64;
var l uint64;
var j uint64;
var sum1 uint64;
var  count uint64;

   count = 0;
   for i=1;i<1001;i++ {
      for l=from;l<(from+to);l++ {
           j = l*l;
           count = count + 1;
           sum1 = sum1 + (j*j*j*j*j*j*j*j*j*j);
      }
   }
}

func main () {
   var sum1 uint64;
   var j uint64;
   var i uint64;
   var l uint64;
   var num uint64;
   var count  uint64;

   sum1 = 0;
   num = 100000000;
   start88 := time.Now ();
   addlist1(1,num);
   elapsed88 := time.Since(start88);
   fmt.Println("The time taken is ", elapsed88,sum1,num);
   time.Sleep(1*time.Second);

   sum1 = 0;
   count  = 0;
   start := time.Now();
   for i=1;i<1001;i++ {
      for l=1;l<num;l++ {
         j = l*l;
         sum1 = sum1 + (j*j*j*j*j*j*j*j*j*j);
         count = count+1;
      }
   }
   elapsed := time.Since(start);
   fmt.Println("The total time without function is", elapsed,sum1,num,count);
   time.Sleep(1*time.Second);

}
</code>```

The first println gives an output of 29 seconds whereas the second one gives an output of 4m 57seconds. The difference is huge. It is consistent as well.

I am running this in a Debian distribution that has 4 cores.

Any ideas why this is so?

Sincerely,
Sudarsan.D

答:
The code inside main and addlist1 is not the same.

In the function addlist1, no values are returned. The compiler can completely optimize it away into nothing, because the function does nothing (it does not modify memory or return a value).

This is not true of the code in main(), which prints the value of sum1.

To make the code the same, return sum1 and count from your function and print it from main:

```<code>func addlist1(from uint64, to uint64) (uint64, uint64) {
    ...
    return sum1, count
}

func main() {
    ...
    start := time.Now()
    sum, count := addlist1(1, num)
    elapsed := time.Since(start)
    fmt.Println("The time taken is ", elapsed, sum1, num);
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do a CPU-intensive operation in GO. The code is pretty straight forward and I am trying to measure it as well. The measurement code looks like this

However, when I try to execute the same code as a function (invoked from main) it seems to work much faster. Any idea as to why this is happening?
package main

import (
       "fmt";
       "time"
    )

func addlist1 (from uint64, to uint64) {
var i uint64;
var l uint64;
var j uint64;
var sum1 uint64;
var  count uint64;

   count = 0;
   for i=1;i<1001;i++ {
      for l=from;l<(from+to);l++ {
           j = l*l;
           count = count + 1;
           sum1 = sum1 + (j*j*j*j*j*j*j*j*j*j);
      }
   }
}

func main () {
   var sum1 uint64;
   var j uint64;
   var i uint64;
   var l uint64;
   var num uint64;
   var count  uint64;

   sum1 = 0;
   num = 100000000;
   start88 := time.Now ();
   addlist1(1,num);
   elapsed88 := time.Since(start88);
   fmt.Println("The time taken is ", elapsed88,sum1,num);
   time.Sleep(1*time.Second);

   sum1 = 0;
   count  = 0;
   start := time.Now();
   for i=1;i<1001;i++ {
      for l=1;l<num;l++ {
         j = l*l;
         sum1 = sum1 + (j*j*j*j*j*j*j*j*j*j);
         count = count+1;
      }
   }
   elapsed := time.Since(start);
   fmt.Println("The total time without function is", elapsed,sum1,num,count);
   time.Sleep(1*time.Second);

}

The first println gives an output of 29 seconds whereas the second one gives an output of 4m 57seconds. The difference is huge. It is consistent as well.

I am running this in a Debian distribution that has 4 cores.

Any ideas why this is so?

Sincerely,
Sudarsan.D

Body:
The code inside main and addlist1 is not the same.

In the function addlist1, no values are returned. The compiler can completely optimize it away into nothing, because the function does nothing (it does not modify memory or return a value).

This is not true of the code in main(), which prints the value of sum1.

To make the code the same, return sum1 and count from your function and print it from main:

func addlist1(from uint64, to uint64) (uint64, uint64) {
    ...
    return sum1, count
}

func main() {
    ...
    start := time.Now()
    sum, count := addlist1(1, num)
    elapsed := time.Since(start)
    fmt.Println("The time taken is ", elapsed, sum1, num);
    ...
}


问:
Algorithm that reduces an array of integers to a single value
Given an array of integers.

Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.

That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.

At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.

The process continues until there's only one element left in the array.

Here is the code I have:

```<code>        int[] arr= {1,2,3,4,5}; // orignal array

        int[] newArr = new int[arr.length];
        int[] result = new int[newArr.length];
        for(int i = 1;i<n;i++)
        {

            newArr = Arrays.copyOf(arr, arr.length - i);
            System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.

            //System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
            //result[0] = newArr[newArr.length - 1];
            //result = Arrays.copyOf(result,result.length-1);
            //System.out.println(Arrays.toString(result));
        }
</code>```

output should come like this

```<code>[1, 2, 3, 4, 5] // original array

[1, 2, 3, 4] // array after deletion

[4, 1, 2, 3] // array after rotaion

[4, 1, 2]// again after deletion from previous array

[2, 4, 1]// array after rotaion

[2, 4]// again after deletion from previous array

[4, 2]// array after rotation

[4]

final answer is 4
</code>```

答:
I would not recommend doing everything in a single method. Start by writing a method to perform the rotation. I would name it rotate and it might look something like

```<code>private static void rotate(int[] arr) {
    int v = arr[arr.length - 1];
    for (int i = arr.length - 1; i > 0; i--) {
        arr[i] = arr[i - 1];
    }
    arr[0] = v;
}
</code>```

Then you can use that and a loop to express the algorithm you described

```<code>int[] arr = { 1, 2, 3, 4, 5 };
// While there are more than one elements
while (arr.length > 1) {
    // Print the elements
    System.out.println(Arrays.toString(arr));
    // Remove the last element from the array
    arr = Arrays.copyOf(arr, arr.length - 1);
    // Rotate the array
    rotate(arr);
}
// Only one value left
System.out.println(Arrays.toString(arr));
</code>```

Outputs (as requested)

```<code>[1, 2, 3, 4, 5]
[4, 1, 2, 3]
[2, 4, 1]
[4, 2]
[4]
</code>```

Body:
Given an array of integers.

Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.

That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.

At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.

The process continues until there's only one element left in the array.

Here is the code I have:

        int[] arr= {1,2,3,4,5}; // orignal array

        int[] newArr = new int[arr.length];
        int[] result = new int[newArr.length];
        for(int i = 1;i<n;i++)
        {

            newArr = Arrays.copyOf(arr, arr.length - i);
            System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.

            //System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
            //result[0] = newArr[newArr.length - 1];
            //result = Arrays.copyOf(result,result.length-1);
            //System.out.println(Arrays.toString(result));
        }

output should come like this

[1, 2, 3, 4, 5] // original array

[1, 2, 3, 4] // array after deletion

[4, 1, 2, 3] // array after rotaion

[4, 1, 2]// again after deletion from previous array

[2, 4, 1]// array after rotaion

[2, 4]// again after deletion from previous array

[4, 2]// array after rotation

[4]

final answer is 4

Body:
I would not recommend doing everything in a single method. Start by writing a method to perform the rotation. I would name it rotate and it might look something like

private static void rotate(int[] arr) {
    int v = arr[arr.length - 1];
    for (int i = arr.length - 1; i > 0; i--) {
        arr[i] = arr[i - 1];
    }
    arr[0] = v;
}

Then you can use that and a loop to express the algorithm you described

int[] arr = { 1, 2, 3, 4, 5 };
// While there are more than one elements
while (arr.length > 1) {
    // Print the elements
    System.out.println(Arrays.toString(arr));
    // Remove the last element from the array
    arr = Arrays.copyOf(arr, arr.length - 1);
    // Rotate the array
    rotate(arr);
}
// Only one value left
System.out.println(Arrays.toString(arr));

Outputs (as requested)

[1, 2, 3, 4, 5]
[4, 1, 2, 3]
[2, 4, 1]
[4, 2]
[4]


问:
Listview file for specific folder/directory
Hello guy's can any body help me about a assignment given to us by our proof. I'm new to programming but I'm learning via Google, but upon searching in Google i can't seem to find my question so I'm using the platform as the last resort. But first things first pls Bare with me for my bad English...

My question is how can i load a Listview file with specific folder
Like for example it's on document but the thing is FolderBrowseDialog need to choose where folder should i load. Ty for the help

答:
Lets do it step by step

Getting the directory using FolderBrowserDialog

Add System.IO namespace on top of your form's code. like:

using System.IO;

Add all needed controls to your form. lets say Button, FolderBrowserDialog and ListView

Double click on the form to open code window for Button's click event.

Add the following code:

```<code>if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
}
</code>```

Using the directory in ListView

Use any of the code below that suites your requirements:

To Only Show files:

Used FileInfo class to access the files in the directory and access their names.

```<code>if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
   FileInfo[] Files = dir.GetFiles();
   foreach (FileInfo item in Files)
   {
       listView1.Items.Add(item.Name);
   }
}
</code>```

To Only Show directories:

Used DirectoryInfo class to read Subdirectories inside a folder and access their names.

```<code>if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
   DirectoryInfo[] subdirs = dir.GetDirectories();
   foreach (DirectoryInfo item in subdirs)
   {
       listView1.Items.Add(item.Name);
   }
}
</code>```

To Show everything:

Used FileSystemInfo class to query each file and directory and access their names.

```<code>if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
   FileSystemInfo[] allElements = dir.GetFileSystemInfos();
   foreach (FileSystemInfo item in allElements)
   {
       listView1.Items.Add(item.Name);
   }
}
</code>```

Overall code

```<code>using System;
using System.IO;
using System.Windows.Forms;

namespace ListViewDirectory
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog()== DialogResult.OK)
            {
                DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo item in files)
                {
                    listView1.Items.Add(item.Name);
                }
            }
        }
    }
}
</code>```

Output

Body:
Lets do it step by step

Getting the directory using FolderBrowserDialog

Add System.IO namespace on top of your form's code. like:

using System.IO;

Add all needed controls to your form. lets say Button, FolderBrowserDialog and ListView

Double click on the form to open code window for Button's click event.

Add the following code:

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
}

Using the directory in ListView

Use any of the code below that suites your requirements:

To Only Show files:

Used FileInfo class to access the files in the directory and access their names.

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
   FileInfo[] Files = dir.GetFiles();
   foreach (FileInfo item in Files)
   {
       listView1.Items.Add(item.Name);
   }
}

To Only Show directories:

Used DirectoryInfo class to read Subdirectories inside a folder and access their names.

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
   DirectoryInfo[] subdirs = dir.GetDirectories();
   foreach (DirectoryInfo item in subdirs)
   {
       listView1.Items.Add(item.Name);
   }
}

To Show everything:

Used FileSystemInfo class to query each file and directory and access their names.

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
   DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
   FileSystemInfo[] allElements = dir.GetFileSystemInfos();
   foreach (FileSystemInfo item in allElements)
   {
       listView1.Items.Add(item.Name);
   }
}

Overall code

using System;
using System.IO;
using System.Windows.Forms;

namespace ListViewDirectory
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog()== DialogResult.OK)
            {
                DirectoryInfo dir = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo item in files)
                {
                    listView1.Items.Add(item.Name);
                }
            }
        }
    }
}

Output


问:
Enable Angular button when radio is selected
I'm trying to enable a button when either one of two radio buttons have been selected. I have the button defaulted to disabled with both of the radios defaulted to being unselected. The button should become enabled when either one of the radios has been selected. How can I do this? Here is my HTML:

```<code>    <input
          id="regions"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />
        <label
          for="regions"
          >
          {{ 'budgetOnboarding.welcomeScreen.regionsDistribution' | i18next }}
        </label>
      </div>
      <div>
        <input
          id="individual_account"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />
        <label
          for="individual_account">
          {{ 'budgetOnboarding.welcomeScreen.individualDistribution' | i18next }}
        </label>
      </div>
    </div>
    <div>
      <button
        type="button"
        id="beginButton"
        (click)="beginWizard()"
        disabled
      >
        {{ 'budgetOnboarding.welcomeScreen.begin' | i18next }}
      </button>
</code>```

Here is my ts:

```<code>import { ChangeDetectorRef, Component, EventEmitter, Output } from '@angular/core';

import { DEFAULT_WELCOME_STEPS } from '../../constants';
import { BudgetHierarchy } from '../../enumerations';
import { ProgramBudgetFacade } from '../../facades';

@Component({
  selector: 'app-welcome-screen',
  templateUrl: './welcome-screen.component.html'
})
export class WelcomeScreenComponent {
  @Output() public readonly onScreenChange = new EventEmitter<boolean>();

  public steps: string[] = [...DEFAULT_WELCOME_STEPS];
  public isRegionHierarchy = true;

  constructor(
    private readonly _changeDetectorRef: ChangeDetectorRef,
    private readonly _budgetFacade: ProgramBudgetFacade
  ) {}

  public toggleSelectedDistribution(): void {
    this.isRegionHierarchy = !this.isRegionHierarchy;

    this.isRegionHierarchy
      ? (this.steps = [...DEFAULT_WELCOME_STEPS])
      : this.steps.splice(2, 2, 'budgetOnboarding.welcomeScreen.accountThirdStep');

    this._changeDetectorRef.detectChanges();
  }

  public beginWizard(): void {
    const budgetHierarchy = this.isRegionHierarchy ? BudgetHierarchy.regions : BudgetHierarchy.none;
    this.onScreenChange.emit(this.isRegionHierarchy);
    this._budgetFacade.setBudgetHierarchy({ budgetHierarchy });
  }
}
</code>```

答:
```<code><input #radio1
      id="regions"
      name="distribution"
      type="radio"
      (change)="toggleSelectedDistribution()"
    />
    <label
      for="regions"
      >
      {{ 'budgetOnboarding.welcomeScreen.regionsDistribution' | i18next }}
    </label>
  </div>
  <div>
    <input #radio2
      id="individual_account"
      name="distribution"
      type="radio"
      (change)="toggleSelectedDistribution()"
    />
    <label
      for="individual_account">
      {{ 'budgetOnboarding.welcomeScreen.individualDistribution' | i18next }}
    </label>
  </div>
</div>
<div>
  <button
    type="button"
    id="beginButton"
    (click)="beginWizard()"
    [disabled]="!(radio1.checked || radio2.checked)"
  >
    {{ 'budgetOnboarding.welcomeScreen.begin' | i18next }}
  </button>
</code>```

Body:
I'm trying to enable a button when either one of two radio buttons have been selected. I have the button defaulted to disabled with both of the radios defaulted to being unselected. The button should become enabled when either one of the radios has been selected. How can I do this? Here is my HTML:

    <input
          id="regions"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />

          {{ 'budgetOnboarding.welcomeScreen.regionsDistribution' | i18next }}

        <input
          id="individual_account"
          name="distribution"
          type="radio"
          (change)="toggleSelectedDistribution()"
        />

          {{ 'budgetOnboarding.welcomeScreen.individualDistribution' | i18next }}

      <button
        type="button"
        id="beginButton"
        (click)="beginWizard()"
        disabled
      >
        {{ 'budgetOnboarding.welcomeScreen.begin' | i18next }}
      </button>

Here is my ts:

import { ChangeDetectorRef, Component, EventEmitter, Output } from '@angular/core';

import { DEFAULT_WELCOME_STEPS } from '../../constants';
import { BudgetHierarchy } from '../../enumerations';
import { ProgramBudgetFacade } from '../../facades';

@Component({
  selector: 'app-welcome-screen',
  templateUrl: './welcome-screen.component.html'
})
export class WelcomeScreenComponent {
  @Output() public readonly onScreenChange = new EventEmitter<boolean>();

  public steps: string[] = [...DEFAULT_WELCOME_STEPS];
  public isRegionHierarchy = true;

  constructor(
    private readonly _changeDetectorRef: ChangeDetectorRef,
    private readonly _budgetFacade: ProgramBudgetFacade
  ) {}

  public toggleSelectedDistribution(): void {
    this.isRegionHierarchy = !this.isRegionHierarchy;

    this.isRegionHierarchy
      ? (this.steps = [...DEFAULT_WELCOME_STEPS])
      : this.steps.splice(2, 2, 'budgetOnboarding.welcomeScreen.accountThirdStep');

    this._changeDetectorRef.detectChanges();
  }

  public beginWizard(): void {
    const budgetHierarchy = this.isRegionHierarchy ? BudgetHierarchy.regions : BudgetHierarchy.none;
    this.onScreenChange.emit(this.isRegionHierarchy);
    this._budgetFacade.setBudgetHierarchy({ budgetHierarchy });
  }
}


问:
How to alias a prototype function using es6 syntax
The requirement is to have an alias to a prototype function.

Currently I'm doing this, which is adding an additional function and execution context, when called, as opposed to just a reference:

```<code>class X {
  x() {
    // stuff
  }

  y() {
    this.x();
  }
}
</code>```

Because I don't know how to do this, in es5:

```<code>function X() {

}
X.prototype.x = function () {
  // stuff
}
X.prototype.y = X.prototype.x;
</code>```

Is it possible?

答:
You can do the same thing with classes as well, because they use the same underlying prototype-based structure.

So,

```<code>class X {
  x() {
    // stuff
  }
}

X.prototype.y = X.prototype.x
</code>```

works fine.

If you want to define it in the class, the only way is your approach:

```<code>class X {
  x() {
    // stuff
  }

  y(...args) {
    return this.x(...args);
  }
}
</code>```

However, this will still behave differently if x is overridden in a subclass (which might actually be what you want, if you want a true alias).

Body:
The requirement is to have an alias to a prototype function.

Currently I'm doing this, which is adding an additional function and execution context, when called, as opposed to just a reference:

class X {
  x() {
    // stuff
  }

  y() {
    this.x();
  }
}

Because I don't know how to do this, in es5:

function X() {

}
X.prototype.x = function () {
  // stuff
}
X.prototype.y = X.prototype.x;

Is it possible?

Body:
You can do the same thing with classes as well, because they use the same underlying prototype-based structure.

So,

class X {
  x() {
    // stuff
  }
}

X.prototype.y = X.prototype.x

works fine.

If you want to define it in the class, the only way is your approach:

class X {
  x() {
    // stuff
  }

  y(...args) {
    return this.x(...args);
  }
}

However, this will still behave differently if x is overridden in a subclass (which might actually be what you want, if you want a true alias).


问:
What is wrong with this sorting of dictionary?
I am trying to sort the dictionary here:

```<code>car =   {
  "brand": ["Ford","Honda","Toyota","Tesla","Ford"],
  "model": ["Mustang","CRV","RAV4","X","Transit"],
  "year": [1964,2010,2015,2022,1964],
  "color": ["Red","Yellow","Green","Blue","Black"]
}

sortedbyval1={k: v for k, v in sorted(car.items(),key=lambda v:v[1])}
</code>```

I keep getting error message like below. There is no < in the code!!!

```<code>TypeError: '<' not supported between instances of 'int' and 'str'
</code>```

I am trying to sort the car dictionary by model, year, color etc.

If possible, by color AND year.

答:
Try this beauty:

car = {
  "brand": [ "Ford", "Honda", "Toyota", "Tesla", "Ford" ],
  "model": [ "Mustang", "CRV", "RAV4", "X", "Transit" ],
  "year":  [ 1964, 2010, 2015, 2022, 1964 ],
  "color": [ "Red", "Yellow", "Green", "Blue", "Black" ]
}

criteria = "model";

sorted_dict = {
    k: v for k, v in [
        (a, [
            car[a][b] for b in [
                c for (c, _) in sorted(
                    zip(
                        [
                            c for c in range(0, len(car[criteria]) )
                        ],
                        car[criteria]
                    ),
                    key = lambda x: x[1]
                )
            ]
        ]) for a in car.keys()
    ]
};

print(sorted_dict)
```

Hope it helps! (Don't forget to click the green tick if this is what you wanted :D)

Body:
I am trying to sort the dictionary here:

car =   {
  "brand": ["Ford","Honda","Toyota","Tesla","Ford"],
  "model": ["Mustang","CRV","RAV4","X","Transit"],
  "year": [1964,2010,2015,2022,1964],
  "color": ["Red","Yellow","Green","Blue","Black"]
}

sortedbyval1={k: v for k, v in sorted(car.items(),key=lambda v:v[1])}

I keep getting error message like below. There is no < in the code!!!

TypeError: '<' not supported between instances of 'int' and 'str'

I am trying to sort the car dictionary by model, year, color etc.

If possible, by color AND year.

Body:
Try this beauty:

car = {
  "brand": [ "Ford", "Honda", "Toyota", "Tesla", "Ford" ],
  "model": [ "Mustang", "CRV", "RAV4", "X", "Transit" ],
  "year":  [ 1964, 2010, 2015, 2022, 1964 ],
  "color": [ "Red", "Yellow", "Green", "Blue", "Black" ]
}

criteria = "model";

sorted_dict = {
    k: v for k, v in [
        (a, [
            car[a][b] for b in [
                c for (c, _) in sorted(
                    zip(
                        [
                            c for c in range(0, len(car[criteria]) )
                        ],
                        car[criteria]
                    ),
                    key = lambda x: x[1]
                )
            ]
        ]) for a in car.keys()
    ]
};

print(sorted_dict)

Hope it helps! (Don't forget to click the green tick if this is what you wanted :D)


问:
Why am i getting a result for the components of my return values as opposed to the complete set of return values
Hi all (my first post :) )
Why am getting different results for the individual components of function results as opposed to the set of them?</p>
```<code>import random

def test():
    di1 = random.randint(1, 6)
    di2 = random.randint(1, 6)
    diTotal = di1+di2

    return diTotal, di1, di2

print(test()[0], test()[1], test()[2], test())
</code>```

答:
Each time you call your function, two new random numbers are produced. You call the test function 4 times in print(test()[0], test()[1], test()[2], test()). So, 4 pairs of random numbers are produced, and they are different.

If you call the test function just once, you'll have the same result:

```<code>import random

def test():
    di1 = random.randint(1, 6)
    di2 = random.randint(1, 6)
    diTotal = di1+di2

    return diTotal, di1, di2

test_output = test()
print(test_output[0], test_output[1], test_output[2], test_output)
</code>```

The output:

```<code>(3, 1, 2, (3, 1, 2))
</code>```

Body:
Hi all (my first post :) )
Why am getting different results for the individual components of function results as opposed to the set of them?

import random

def test():
    di1 = random.randint(1, 6)
    di2 = random.randint(1, 6)
    diTotal = di1+di2

    return diTotal, di1, di2

print(test()[0], test()[1], test()[2], test())

Body:
Each time you call your function, two new random numbers are produced. You call the test function 4 times in print(test()[0], test()[1], test()[2], test()). So, 4 pairs of random numbers are produced, and they are different.

If you call the test function just once, you'll have the same result:

import random

def test():
    di1 = random.randint(1, 6)
    di2 = random.randint(1, 6)
    diTotal = di1+di2

    return diTotal, di1, di2

test_output = test()
print(test_output[0], test_output[1], test_output[2], test_output)

The output:

(3, 1, 2, (3, 1, 2))


问:
Chess Engine Wrong Number of 4 Plie Board States
I'm writing a chess engine, and am trying to make it as fast as possible, so I'm using bitboards to represent each type of piece. I was printing out the number of different board states at each plie (Plie = 1 person moving) and on plie 4 it gets the wrong number.

Is there any way to figure out what is going wrong without sifting through all 200k 4 plie positions?

Also, note I haven't implemented castling, check, en passent, pawn promotion or any draw rules yet, as none of them should have any affect until after the 4th plie.

(Wikipedia link that gives the number of board states per plie, vs mine: 20, 400, 8902, 197742)

```<code>import json

with open('White_Pawn.json', 'r') as f:
    white_pawn_table = json.load(f)
    white_pawn_table = {int(q):w for q, w in white_pawn_table.items()}

with open('White_Pawn_Captures.json', 'r') as f:
    white_pawn_captures_table = json.load(f)
    white_pawn_captures_table = {int(q):w for q, w in white_pawn_captures_table.items()}

with open('Black_Pawn.json', 'r') as f:
    black_pawn_table = json.load(f)
    black_pawn_table = {int(q):w for q, w in black_pawn_table.items()}

with open('Black_Pawn_Captures.json', 'r') as f:
    black_pawn_captures_table = json.load(f)
    black_pawn_captures_table = {int(q):w for q, w in black_pawn_captures_table.items()}

with open('Knight.json', 'r') as f:
    knight_table = json.load(f)
    knight_table = {int(q):w for q, w in knight_table.items()}

with open('Bishop.json', 'r') as f:
    bishop_table = json.load(f)
    bishop_table = {int(q):w for q, w in bishop_table.items()}

with open('Rook.json', 'r') as f:
    rook_table = json.load(f)
    rook_table = {int(q):w for q, w in rook_table.items()}

string_to_int = lambda x:int(x, 2)
int_to_string = lambda x:'0' * (66 - len(bin(x))) + bin(x)[2:]
x_in_y = lambda x, y:(x & y) != 0

def show(x):
    for q in range(8):
        print(' '.join([w for w in x[(q * 8):((q + 1) * 8)]]))
    print()

class Board:
    def __init__(self, args = False):
        if args:
            self.maps, self.turn = args
        else:
            self.maps, self.turn = {'White Pawns':65280, 'White Knights':66, 'White Bishops':36, 'White Rooks':129, 'White Queens':16, 'White Kings':8, 'Black Pawns':71776119061217280, 'Black Knights':4755801206503243776, 'Black Bishops':2594073385365405696, 'Black Rooks':9295429630892703744, 'Black Queens':1152921504606846976, 'Black Kings':576460752303423488}, 1

    def move(self, colour, not_colour, piece, move):
        board = Board(args = (self.maps.copy(), not self.turn))

        board.maps[f'{colour} {piece}s'] ^= move[0]
        board.maps[f'{colour} {piece}s'] |= move[1]

        for q in board.maps:
            if not_colour in q:
                board.maps[q] &= ~move[1]

        return board

    def moves(self):
        # Get Pieces and Colours
        colour, not_colour = ['White', 'Black'][::self.turn if self.turn else -1]
        pieces, not_pieces = 0, 0
        for q, w in self.maps.items():
            if colour in q:
                pieces |= w
            else:
                not_pieces |= w

        # Pawn
        if colour == 'White':
            move_table, capture_table = white_pawn_table, white_pawn_captures_table
        else:
            move_table, capture_table = black_pawn_table, black_pawn_captures_table

        temp_pawns = self.maps[f'{colour} Pawns']
        while temp_pawns:
            pawn = temp_pawns & -temp_pawns
            temp_pawns ^= pawn

            for next_pawn in move_table[pawn]:
                if x_in_y(next_pawn, pieces | not_pieces):
                    break
                else:
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

            for next_pawn in capture_table[pawn]:
                if x_in_y(next_pawn, not_pieces):
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

        # Knight
        temp_knights = self.maps[f'{colour} Knights']
        while temp_knights:
            knight = temp_knights & -temp_knights
            temp_knights ^= knight

            for next_knight in knight_table[knight]:
                if not x_in_y(next_knight, pieces):
                    yield self.move(colour, not_colour, 'Knight', (knight, next_knight))

        # Bishop
        temp_bishops = self.maps[f'{colour} Bishops']
        while temp_bishops:
            bishop = temp_bishops & -temp_bishops
            temp_bishops ^= bishop

            for direction in bishop_table[bishop]:
                for next_bishop in direction:
                    if x_in_y(next_bishop, pieces): break

                    yield self.move(colour, not_colour, 'Bishop', (bishop, next_bishop))

                    if x_in_y(next_bishop, not_pieces): break

        # Rook
        temp_rooks = self.maps[f'{colour} Rooks']
        while temp_rooks:
            rook = temp_rooks & -temp_rooks
            temp_rooks ^= rook

            for direction in rook_table[rook]:
                for next_rook in direction:
                    if x_in_y(next_rook, pieces): break

                    yield self.move(colour, not_colour, 'Rook', (rook, next_rook))

                    if x_in_y(next_rook, not_pieces): break

        # Queen
        temp_queens = self.maps[f'{colour} Queens']
        while temp_queens:
            queen = temp_queens & -temp_queens
            temp_queens ^= queen

            for direction in rook_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

            for direction in bishop_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

        # King
        king = self.maps[f'{colour} Kings']
        for direction in rook_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king , next_king))

        for direction in bishop_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king, next_king))

    def next_states(self):
        for q in self.moves():
            yield q

    def __str__(self):
        find = {'Black Kings':'♔ ', 'Black Queens':'♕ ', 'Black Rooks':'♖ ', 'Black Bishops':'♗ ', 'Black Knights':'♘ ', 'Black Pawns':'♙ ', 'White Pawns':'♟ ', 'White Knights':'♞ ', 'White Bishops':'♝ ', 'White Rooks':'♜ ', 'White Queens':'♛ ', 'White Kings':'♚ '}
        map = lambda y:([q for q in self.maps if self.maps[q] & (2**y)] + [False])[0]
        output = '    A    B    C    D    E    F    G    H\n  ╔════╤════╤════╤════╤════╤════╤════╤════╗\n'
        for q in range(8):
            if q % 2 == 0:
                output += '%i ║ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '  ' if w % 2 == 0 else '░░' for w in range(8)] + [8 - q])
            else:
                output += '%i ║░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s ║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '░░' if w % 2 == 0 else '  ' for w in range(8)] + [8 - q])

        output += '\x1b[1A\x1b[2K' + '  ╚════╧════╧════╧════╧════╧════╧════╧════╝\n    A    B    C    D    E    F    G    H'
        return output

chess = Board()

next_states = [chess]
while True:
    current_states, next_states = next_states, []

    for state in current_states:
        for next_state in state.next_states():
            next_states.append(next_state)

    print(len(next_states))
</code>```

The json files are too large to put here but you can assume they're correct. Each file has a dictionary with keys 2^0-2^63 each representing a possible position for the piece the file is named after. The values are the different positions they can go from there.

答:
```<code>1. e2-e4 f7-f5
2. Bf1-b5
</code>```

Pawn at d7 is pinned and can't move.

Body:
I'm writing a chess engine, and am trying to make it as fast as possible, so I'm using bitboards to represent each type of piece. I was printing out the number of different board states at each plie (Plie = 1 person moving) and on plie 4 it gets the wrong number.

Is there any way to figure out what is going wrong without sifting through all 200k 4 plie positions?

Also, note I haven't implemented castling, check, en passent, pawn promotion or any draw rules yet, as none of them should have any affect until after the 4th plie.

(Wikipedia link that gives the number of board states per plie, vs mine: 20, 400, 8902, 197742)

import json

with open('White_Pawn.json', 'r') as f:
    white_pawn_table = json.load(f)
    white_pawn_table = {int(q):w for q, w in white_pawn_table.items()}

with open('White_Pawn_Captures.json', 'r') as f:
    white_pawn_captures_table = json.load(f)
    white_pawn_captures_table = {int(q):w for q, w in white_pawn_captures_table.items()}

with open('Black_Pawn.json', 'r') as f:
    black_pawn_table = json.load(f)
    black_pawn_table = {int(q):w for q, w in black_pawn_table.items()}

with open('Black_Pawn_Captures.json', 'r') as f:
    black_pawn_captures_table = json.load(f)
    black_pawn_captures_table = {int(q):w for q, w in black_pawn_captures_table.items()}

with open('Knight.json', 'r') as f:
    knight_table = json.load(f)
    knight_table = {int(q):w for q, w in knight_table.items()}

with open('Bishop.json', 'r') as f:
    bishop_table = json.load(f)
    bishop_table = {int(q):w for q, w in bishop_table.items()}

with open('Rook.json', 'r') as f:
    rook_table = json.load(f)
    rook_table = {int(q):w for q, w in rook_table.items()}

string_to_int = lambda x:int(x, 2)
int_to_string = lambda x:'0' * (66 - len(bin(x))) + bin(x)[2:]
x_in_y = lambda x, y:(x & y) != 0

def show(x):
    for q in range(8):
        print(' '.join([w for w in x[(q * 8):((q + 1) * 8)]]))
    print()

class Board:
    def __init__(self, args = False):
        if args:
            self.maps, self.turn = args
        else:
            self.maps, self.turn = {'White Pawns':65280, 'White Knights':66, 'White Bishops':36, 'White Rooks':129, 'White Queens':16, 'White Kings':8, 'Black Pawns':71776119061217280, 'Black Knights':4755801206503243776, 'Black Bishops':2594073385365405696, 'Black Rooks':9295429630892703744, 'Black Queens':1152921504606846976, 'Black Kings':576460752303423488}, 1

    def move(self, colour, not_colour, piece, move):
        board = Board(args = (self.maps.copy(), not self.turn))

        board.maps[f'{colour} {piece}s'] ^= move[0]
        board.maps[f'{colour} {piece}s'] |= move[1]

        for q in board.maps:
            if not_colour in q:
                board.maps[q] &= ~move[1]

        return board

    def moves(self):
        # Get Pieces and Colours
        colour, not_colour = ['White', 'Black'][::self.turn if self.turn else -1]
        pieces, not_pieces = 0, 0
        for q, w in self.maps.items():
            if colour in q:
                pieces |= w
            else:
                not_pieces |= w

        # Pawn
        if colour == 'White':
            move_table, capture_table = white_pawn_table, white_pawn_captures_table
        else:
            move_table, capture_table = black_pawn_table, black_pawn_captures_table

        temp_pawns = self.maps[f'{colour} Pawns']
        while temp_pawns:
            pawn = temp_pawns & -temp_pawns
            temp_pawns ^= pawn

            for next_pawn in move_table[pawn]:
                if x_in_y(next_pawn, pieces | not_pieces):
                    break
                else:
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

            for next_pawn in capture_table[pawn]:
                if x_in_y(next_pawn, not_pieces):
                    yield self.move(colour, not_colour, 'Pawn', (pawn, next_pawn))

        # Knight
        temp_knights = self.maps[f'{colour} Knights']
        while temp_knights:
            knight = temp_knights & -temp_knights
            temp_knights ^= knight

            for next_knight in knight_table[knight]:
                if not x_in_y(next_knight, pieces):
                    yield self.move(colour, not_colour, 'Knight', (knight, next_knight))

        # Bishop
        temp_bishops = self.maps[f'{colour} Bishops']
        while temp_bishops:
            bishop = temp_bishops & -temp_bishops
            temp_bishops ^= bishop

            for direction in bishop_table[bishop]:
                for next_bishop in direction:
                    if x_in_y(next_bishop, pieces): break

                    yield self.move(colour, not_colour, 'Bishop', (bishop, next_bishop))

                    if x_in_y(next_bishop, not_pieces): break

        # Rook
        temp_rooks = self.maps[f'{colour} Rooks']
        while temp_rooks:
            rook = temp_rooks & -temp_rooks
            temp_rooks ^= rook

            for direction in rook_table[rook]:
                for next_rook in direction:
                    if x_in_y(next_rook, pieces): break

                    yield self.move(colour, not_colour, 'Rook', (rook, next_rook))

                    if x_in_y(next_rook, not_pieces): break

        # Queen
        temp_queens = self.maps[f'{colour} Queens']
        while temp_queens:
            queen = temp_queens & -temp_queens
            temp_queens ^= queen

            for direction in rook_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

            for direction in bishop_table[queen]:
                for next_queen in direction:
                    if x_in_y(next_queen, pieces): break

                    yield self.move(colour, not_colour, 'Queen', (queen, next_queen))

                    if x_in_y(next_queen, not_pieces): break

        # King
        king = self.maps[f'{colour} Kings']
        for direction in rook_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king , next_king))

        for direction in bishop_table[king]:
            next_king = direction[0]
            if not x_in_y(next_king, pieces):
                yield self.move(colour, not_colour, 'King', (king, next_king))

    def next_states(self):
        for q in self.moves():
            yield q

    def __str__(self):
        find = {'Black Kings':'♔ ', 'Black Queens':'♕ ', 'Black Rooks':'♖ ', 'Black Bishops':'♗ ', 'Black Knights':'♘ ', 'Black Pawns':'♙ ', 'White Pawns':'♟ ', 'White Knights':'♞ ', 'White Bishops':'♝ ', 'White Rooks':'♜ ', 'White Queens':'♛ ', 'White Kings':'♚ '}
        map = lambda y:([q for q in self.maps if self.maps[q] & (2**y)] + [False])[0]
        output = '    A    B    C    D    E    F    G    H\n  ╔════╤════╤════╤════╤════╤════╤════╤════╗\n'
        for q in range(8):
            if q % 2 == 0:
                output += '%i ║ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '  ' if w % 2 == 0 else '░░' for w in range(8)] + [8 - q])
            else:
                output += '%i ║░%s░│ %s │░%s░│ %s │░%s░│ %s │░%s░│ %s ║ %i\n  ╟────┼────┼────┼────┼────┼────┼────┼────╢\n' % tuple([8 - q] + [find[map(q * 8 + w)] if map(q * 8 + w) else '░░' if w % 2 == 0 else '  ' for w in range(8)] + [8 - q])

        output += '\x1b[1A\x1b[2K' + '  ╚════╧════╧════╧════╧════╧════╧════╧════╝\n    A    B    C    D    E    F    G    H'
        return output

chess = Board()

next_states = [chess]
while True:
    current_states, next_states = next_states, []

    for state in current_states:
        for next_state in state.next_states():
            next_states.append(next_state)

    print(len(next_states))

The json files are too large to put here but you can assume they're correct. Each file has a dictionary with keys 2^0-2^63 each representing a possible position for the piece the file is named after. The values are the different positions they can go from there.

Body:
1. e2-e4 f7-f5
2. Bf1-b5

Pawn at d7 is pinned and can't move.


问:
Url rewrite issue not getting current session (getPrincipal()) for redirected url
I have rewrited url
from: http://www.xyz.com/Sample/showSamples-ASA21DS
to: http://www.xyz.com/Sample/showSamples.do?sampleId=ASA21DS

using urlRewrite.xml

```<code><urlrewrite>

<rule>
    <from>^/http://www.xyz.com/Sample/showSamples-ASA21DS</from>
    <to>http://www.xyz.com/Sample/showSamples.do?sampleId=ASA21DS</to>
</rule>
</urlrewrite>
</code>```

But, I dont get current session for this new url..
For this,

```<code>SecurityContextHolder.getContext().getAuthentication().getPrincipal()
</code>```

i m getting null

答: Check to make sure the new request is still going through the Spring Security filters.  This question is actually on the official FAQ page: http://static.springsource.org/spring-security/site/faq/faq.html#faq-no-filters-no-context</p>

Body:
I have rewrited url
from: http://www.xyz.com/Sample/showSamples-ASA21DS
to: http://www.xyz.com/Sample/showSamples.do?sampleId=ASA21DS

using urlRewrite.xml

<urlrewrite>

<rule>
    <from>^/http://www.xyz.com/Sample/showSamples-ASA21DS</from>
    <to>http://www.xyz.com/Sample/showSamples.do?sampleId=ASA21DS</to>
</rule>
</urlrewrite>

But, I dont get current session for this new url..
For this,

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

i m getting null


问:
How to simulate long running process in .NET API Controller Correctly
I am trying to create a unit test to simulate my API being called by many people at the same time.

I've got this code in my unit test:

            var tasks = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
                var id = i; // must assign to new variable inside for loop
                var t = Task.Run(async () =>
                {
                    response = await Client.GetAsync("/api/test2?id=" + id);
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);
```
<p>Then in my controller I am putting in a <code>Thread.Sleep</code>.<br />
But when I do this, the total time for all tests to complete is 10 x the sleep time.</p>
<p>I expected all the calls to be made and to have ended up at the <code>Thread.Sleep</code> call at more or less the same time.</p>
<p>But it seems the API calls are actually made one after the other.</p>
<p>The reason I am testing the parallel API call is because I want to test a deadlock issue with my data repository when using SQLite which has only happened when more than 1 user uses my website at the same time.</p>
<p>And I have never been able to simulate this and I thought I'd create a unit test, but the code I have now seems to not be executing the calls in parallel.</p>
<p>My plan with the Thread.Sleep calls was to put a couple in the Controller method to make sure all requests end up between certain code blocks at the same time.</p>
<p>Do I need to set a a max number of parallel requests on the Web Server or something or am I doing something obviously wrong?</p>
<p>Thanks in advance.</p>
<p><strong>Update 1:</strong>
I forgot to mention I get the same results with <code>await Task.Delay(1000);</code> and many similar alternatives.</p>
<p>Not sure if it's clear but this is all running within a unit test using NUnit.<br />
And the "Web Server" and Client is created like this:</p>
<pre class="lang-cs prettyprint-override"><code>            var builder = new WebHostBuilder().UseStartup<TStartup>();
            Server = new TestServer(builder);
            Client = Server.CreateClient();
</code>```

答: You can use Task.Delay(time in milliseconds). Thread.Sleep will not release a thread and it can't process other tasks while waiting to result.

Body:
I am trying to create a unit test to simulate my API being called by many people at the same time.

I've got this code in my unit test:

            var tasks = new List<Task>();
            for (int i = 0; i < 10; i++)
            {
                var id = i; // must assign to new variable inside for loop
                var t = Task.Run(async () =>
                {
                    response = await Client.GetAsync("/api/test2?id=" + id);
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                });
                tasks.Add(t);
            }

            await Task.WhenAll(tasks);

Then in my controller I am putting in a Thread.Sleep.

But when I do this, the total time for all tests to complete is 10 x the sleep time.

I expected all the calls to be made and to have ended up at the Thread.Sleep call at more or less the same time.

But it seems the API calls are actually made one after the other.

The reason I am testing the parallel API call is because I want to test a deadlock issue with my data repository when using SQLite which has only happened when more than 1 user uses my website at the same time.

And I have never been able to simulate this and I thought I'd create a unit test, but the code I have now seems to not be executing the calls in parallel.

My plan with the Thread.Sleep calls was to put a couple in the Controller method to make sure all requests end up between certain code blocks at the same time.

Do I need to set a a max number of parallel requests on the Web Server or something or am I doing something obviously wrong?

Thanks in advance.

Update 1:
I forgot to mention I get the same results with await Task.Delay(1000); and many similar alternatives.

Not sure if it's clear but this is all running within a unit test using NUnit.

And the "Web Server" and Client is created like this:

            var builder = new WebHostBuilder().UseStartup<TStartup>();
            Server = new TestServer(builder);
            Client = Server.CreateClient();


问:
Pass event listener from popup.js to background.js script
I’m working on a simple time tracker extension. When I started out I had all the js code in one popup.js file, but I found that when the extension pop-up was closed the timer stopped running. I came across the use of a background script to use in junction with the already created popup.js script of mine. What I’ve now done is that I have the evenListener logic from the HTML page in the popup.js, I then use the browser.runtime.sendMessage to send the data to the background.js script to handle the timer. Is this a correct setup or should I do it differently?

I can’t figure out how to pass the click event from the post to the background script, and then use the eventListener in the background script to start the timer.

Here is my public GitHub repo for the timetracker extension. https://github.com/krullmizter/timetracker

答:
Firstly, you should avoid using innerHTML because the add-on might get rejected if you try to upload it to the Firefox AMO website. Instead, use textContent.

As for your question, the background script can’t directly update the DOM of your popup. You could do this by sending messages from the background script to the popup script.

That said, one of the big benefits of using the Alarms API instead of Javascript timeouts/intervals is that your popup should be able to access the alarms that you created, even if they were made by the background script. So for your popup page to see what alarms you have running, it doesn’t need to ask the background script for anything.

For example, if you wanted to show the live timer of your script, you could load the list of alarms when your popup loads and then just use Javascript intervals on the popup page to keep the timer ticking in the UI and then register a listener on the popup page for when an alarm is fired, so that the popup can remove it from the UI.

Updating the popup UI using the background script is doable using messages, but in my experience it can get pretty complex.

As a side note, if you are sending a lot of messages between the popup and background script, sometimes it’s a good idea to use port-based messaging instead of just the regular runtime messaging APIs.

I’m not sure Alarms can fire every second, at least in Chrome when you release the addon, it’s capped at 1 per minute. That’s why alarms has minute-granularity: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms/create

Also, why does it need to run every second? Sounds like a bad design. Unless it’s for an UI element showing “seconds” :slight_smile:.

Also - alarms are global:

And lastly - background script is running all the time, so put there things that should run all the time. Popup runs when it’s opened, so all UI related things should be in the popup code.
See also: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension


问:
How to make Get-ChildItem not to follow links
I need Get-ChildItem to return all files/folders inside a path. But there are also symlinks going of to remote servers. The links are created by: mklink /D link \\remote-server\folder

If I run Get-ChildItem -recurse it follows the links to the remote servers and lists all files/folders from there. If I use -exclude it does not list the folder matching the excluded pattern but still goes down and lists all included files and folders.

What I actually need is Get-ChildItem -recurse to ignore links at all and not to follow them.

答:
As of Powershell 6.0, Get-ChildItem has a -FollowSymlink switch. If not provided, it doesn't follow them.

-FollowSymlink By default, the Get-ChildItem cmdlet displays symbolic links to directories found during recursion, but doesn't recurse into
them. Use the FollowSymlink parameter to search the directories that
target those symbolic links. The FollowSymlink is a dynamic parameter
and is supported only in the FileSystem provider.

This parameter was introduced in PowerShell 6.0.

Also, if you want to exclude symlinks entirely from the pipeline, they can be filtered out using the LinkType property, which won't be present on items that aren't symlinks.

```<code>Get-ChildItem $root -Recurse | Where-Object LinkType -eq $null
</code>```

Note the comment in the citation about the parameter only being supported by items from the FileSystem provider. If the remote path isn't of this variety, you can consider using New-PSDrive  to associate it with a FileSystem provider drive, e.g.:

```<code>New-PSDrive -Name "Public" -PSProvider "FileSystem" -Root "\\Server01\Public"

Write-Host "The provider for 'Public:' is $((Get-Item 'Public:').PSProvider)"
</code>```

Body:
As of Powershell 6.0, Get-ChildItem has a -FollowSymlink switch. If not provided, it doesn't follow them.

-FollowSymlink By default, the Get-ChildItem cmdlet displays symbolic links to directories found during recursion, but doesn't recurse into
them. Use the FollowSymlink parameter to search the directories that
target those symbolic links. The FollowSymlink is a dynamic parameter
and is supported only in the FileSystem provider.

This parameter was introduced in PowerShell 6.0.

Also, if you want to exclude symlinks entirely from the pipeline, they can be filtered out using the LinkType property, which won't be present on items that aren't symlinks.

Get-ChildItem $root -Recurse | Where-Object LinkType -eq $null

Note the comment in the citation about the parameter only being supported by items from the FileSystem provider. If the remote path isn't of this variety, you can consider using New-PSDrive  to associate it with a FileSystem provider drive, e.g.:

New-PSDrive -Name "Public" -PSProvider "FileSystem" -Root "\\Server01\Public"

Write-Host "The provider for 'Public:' is $((Get-Item 'Public:').PSProvider)"


问:
How to link two integer values in different functions in c while coding arays?
I'm currently working on a pretty basic generator function for c, but currently am getting a floating point error as a result of not linking my integers between two different functions? how would one link the two different integers to always have the same value?
The first integer(currentsize) is meant to change within its defining function. The second integer(nounsize) exists within a different function that is called after.
Here is my code:

```<code>char ** populate(char ** words, FILE *fptr, int *currentsize, int *maxsize)
{
    int i,j;
    for (int i= 0; i <= *maxsize; i++)
    {
        words[i] = malloc(sizeof(char) * 20);
    }
    while(fscanf(fptr,"%s",words[*currentsize])==1)
    {
        if(*currentsize>=*maxsize)
            words=doubleIt(words,maxsize);
    }
    return words;
}

char* generateSentence(char ** noun, int nounsize)
{
    char *sent = malloc(sizeof *sent * 100);
    strcpy(sent, noun[(rand()%nounsize)]);
    free(generateSentence);
}
</code>```

Thanks for any possible input or advice you can offer.

答:
you have to have a variable in the code that calling these functions

```<code> int froodle = 42;
 populate(words, fptr, &froodle, &maxsize);
 .....
 ....
 generateSentence(nountable, froodle);
</code>```

its not clear if you really need to pass &froodle to the first call, the code you show just needs froodle

Body:
I'm currently working on a pretty basic generator function for c, but currently am getting a floating point error as a result of not linking my integers between two different functions? how would one link the two different integers to always have the same value?
The first integer(currentsize) is meant to change within its defining function. The second integer(nounsize) exists within a different function that is called after.
Here is my code:

char ** populate(char ** words, FILE *fptr, int *currentsize, int *maxsize)
{
    int i,j;
    for (int i= 0; i <= *maxsize; i++)
    {
        words[i] = malloc(sizeof(char) * 20);
    }
    while(fscanf(fptr,"%s",words[*currentsize])==1)
    {
        if(*currentsize>=*maxsize)
            words=doubleIt(words,maxsize);
    }
    return words;
}

char* generateSentence(char ** noun, int nounsize)
{
    char *sent = malloc(sizeof *sent * 100);
    strcpy(sent, noun[(rand()%nounsize)]);
    free(generateSentence);
}

Thanks for any possible input or advice you can offer.

Body:
you have to have a variable in the code that calling these functions

 int froodle = 42;
 populate(words, fptr, &froodle, &maxsize);
 .....
 ....
 generateSentence(nountable, froodle);

its not clear if you really need to pass &froodle to the first call, the code you show just needs froodle


问:
How to see current context when debugging template errors?
I am getting a template error during rendering, which I think would be easy to fix if I could just see what's in the context that is passed into the template that is being rendered.  Django's debug error page provides a lot of information, but I'm not seeing my context anywhere.  Am I missing something?  Also, I am using Django-debug-toolbar, but that only seems to come up if the page successfully renders.  Not being able to see the contents of the context that is passed to the template makes debugging some types of template errors hard! What do I need to do to be able to see it in this scenario?   (Note that I'm not asking for a fix to my specific error, which is why I'm not providing more information about it).</p>

答: The easiest way to do this is with the Django Debug Toolbar. it will give you a popup tab on the right hand side of your screen that you can use to inspect various things about the current page's request. Things like SQL statements, versions, logging, and all the templates that were used to render the page, and the context available to each of them.</p>


问:
Create a ggplot barplot with differently coloured horizontal rectangles as background
I would like to create a bar plot with four bars – where a transparent background of 4 differently colored, horizontal areas represent whether the strength of the bars are considered "low", "medium", "high", or "very high".

```<code># Load ggplot2
library(ggplot2)

# Example data
data <- data.frame(
  name=c("A","B","C", "D") ,
  value=c(3, 12, 16, 22)
)

# Background data
backgound_area_color <- c(5, 10, 14, 20)
background_area_name <- c("low", "medium", "high", "very high")
background_data <- as.data.frame(backgound_area_color, background_area_name)

# My attempt:
ggplot(data, aes(x=name, y=value)) +
  geom_bar(stat = "identity") +
  geom_rect(data = background_data,
            aes(y = backgound_area_color))
</code>```

Thanks in advance

答:
You need an xmin, xmax, ymin and ymax aesthetic for geom_rect:

background_data <- data.frame(xmin = -Inf, xmax = Inf,
                              ymin = c(0, 5, 10, 14),
                              ymax = c(5, 10, 14, Inf),
                              fill = factor(background_area_name,
                                            background_area_name))

# My attempt:
ggplot(data, aes(x=name, y=value)) +
  geom_rect(data = background_data,
            aes(ymin = ymin, ymax = ymax, xmin = xmin, xmax = xmax, fill = fill),
            inherit.aes = FALSE, alpha = 0.5) +
  geom_bar(stat = "identity")
```

Body:
I would like to create a bar plot with four bars – where a transparent background of 4 differently colored, horizontal areas represent whether the strength of the bars are considered "low", "medium", "high", or "very high".

# Load ggplot2
library(ggplot2)

# Example data
data <- data.frame(
  name=c("A","B","C", "D") ,
  value=c(3, 12, 16, 22)
)

# Background data
backgound_area_color <- c(5, 10, 14, 20)
background_area_name <- c("low", "medium", "high", "very high")
background_data <- as.data.frame(backgound_area_color, background_area_name)

# My attempt:
ggplot(data, aes(x=name, y=value)) +
  geom_bar(stat = "identity") +
  geom_rect(data = background_data,
            aes(y = backgound_area_color))

Thanks in advance


问:
How to print odd numbers in python
Here is my code.  I can't get the odd numbers to print just the odd numbers and I don't know how to not print the []'s on the output.  can someone help?</p>
```<code>size = 5

def get_numbers(num):
    numbers = []
    user_input = input('Enter {} integers:\n'.format(num))

    i = 0
    for token in user_input.split():
        number = int(token)     # Convert string input into integer
        numbers.append(number)  # Add to numbers list

        print(i, number)
        i += 1

    return numbers

def print_all_numbers(numbers):
    # Print numbers
    print('Numbers:', numbers)

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', nums)

def print_negative_numbers(numbers):
    # Print all negative numbers
    for neg in numbers:
        if neg <= 0:
            print('Negative numbers:', nums)

nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
</code>```

答:
You can use filter(). In this case, filter() will take in a lambda function that checks whether each element is odd and returns a new list that only contains the elements that pass this check (i.e. only the elements which are odd).

def print_odd_numbers(numbers):
    odd_numbers = list(filter(lambda x: x % 2 == 1, numbers))
    for number in odd_numbers:
        print('Odd number:', number)

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print_odd_numbers(nums)
```

Title: How to print odd numbers in python

Body:
Here is my code.  I can't get the odd numbers to print just the odd numbers and I don't know how to not print the []'s on the output.  can someone help?

size = 5

def get_numbers(num):
    numbers = []
    user_input = input('Enter {} integers:\n'.format(num))

    i = 0
    for token in user_input.split():
        number = int(token)     # Convert string input into integer
        numbers.append(number)  # Add to numbers list

        print(i, number)
        i += 1

    return numbers

def print_all_numbers(numbers):
    # Print numbers
    print('Numbers:', numbers)

def print_odd_numbers(numbers):
    for number in numbers:
        if number % 2 == 1:
            print('Odd numbers:', nums)

def print_negative_numbers(numbers):
    # Print all negative numbers
    for neg in numbers:
        if neg <= 0:
            print('Negative numbers:', nums)

nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)


问:
Ansible Docker containers dynamic inventory on MacOS
I have started a Docker container using the following command:

```<code>docker run tomcat:latest
</code>```

Then I created a file named docker.yml with the following contents:

plugin: community.docker.docker_containers
docker_host: unix://var/run/docker.sock
```
<p>Finally I try to obtain a list of the currently running Docker containers using:</p>
```ansible-inventory -i docker.yml --list
```
<p>However instead of a list of running containers, I only get the following result:</p>
```[WARNING]:  * Failed to parse docker.yml with yaml plugin: Plugin configuration YAML file, not YAML inventory
[WARNING]:  * Failed to parse docker.yml with constructed plugin: Incorrect plugin name in file: community.docker.docker_containers
[WARNING]: Unable to parse docker.yml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
{
    "_meta": {
        "hostvars": {}
    },
    "all": {
        "children": [
            "ungrouped"
        ]
    }
}
```

Have I misunderstood the Ansible Docker containers dynamic inventory or am I doing something wrong?

答:
I suspect I had a case of system in disarray and this was the cure:

I retained my current Python installation located at ~/Library/Python/3.9/.

Attempted to uninstall Ansible using pip:
```<code>pip uninstall ansible
</code>```

Manually removed all things Ansible:
```<code>sudo rm -r /etc/ansible
sudo rm -r -/.ansible
sudo rm -r /usr/local/lib/python3.9/site-packages/ansible*
sudo rm /usr/local/bin/ansible*
</code>```

Performed a fresh installation of Ansible:
```<code>pip install ez_setup
pip install --user ansible
</code>```

Installed Ansible Docker collection prerequisite:
```<code>pip install docker
</code>```

Installed Ansible Docker collection:
```<code>ansible-galaxy collection install community.docker
</code>```

After the above, the Ansible Docker container dynamic inventory works as expected and without errors.

Body:
I have started a Docker container using the following command:

docker run tomcat:latest

Then I created a file named docker.yml with the following contents:

plugin: community.docker.docker_containers
docker_host: unix://var/run/docker.sock

Finally I try to obtain a list of the currently running Docker containers using:

ansible-inventory -i docker.yml --list

However instead of a list of running containers, I only get the following result:

[WARNING]:  * Failed to parse docker.yml with yaml plugin: Plugin configuration YAML file, not YAML inventory
[WARNING]:  * Failed to parse docker.yml with constructed plugin: Incorrect plugin name in file: community.docker.docker_containers
[WARNING]: Unable to parse docker.yml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
{
    "_meta": {
        "hostvars": {}
    },
    "all": {
        "children": [
            "ungrouped"
        ]
    }
}

Have I misunderstood the Ansible Docker containers dynamic inventory or am I doing something wrong?

Body:
I suspect I had a case of system in disarray and this was the cure:

I retained my current Python installation located at ~/Library/Python/3.9/.

Attempted to uninstall Ansible using pip:

pip uninstall ansible

Manually removed all things Ansible:

sudo rm -r /etc/ansible
sudo rm -r -/.ansible
sudo rm -r /usr/local/lib/python3.9/site-packages/ansible*
sudo rm /usr/local/bin/ansible*

Performed a fresh installation of Ansible:

pip install ez_setup
pip install --user ansible

Installed Ansible Docker collection prerequisite:

pip install docker

Installed Ansible Docker collection:

ansible-galaxy collection install community.docker

After the above, the Ansible Docker container dynamic inventory works as expected and without errors.


问:
Read zip file with multiple, different data type files inside using pandas from an URL
I'm trying to read a large (~850 mb) .csv file from an URL.

The thing is that the .csv file is within a .zip file that also contains a .pdf file, so when I try to read it in pandas:

```<code>df = pd.read_csv('link', encoding='latin1', sep=';')
</code>```

It doesn't work because it states:

ValueError: Multiple files found in ZIP file. Only one file per ZIP: ['LEIAME.pdf', 'perfil_eleitorado_2018.csv']

I'm working with a collaborative notebook, so the best solution would be just to open the .zip file directly from the link or to upload the .csv file somewhere that won't ask for permissions, log-ins, or anything like that to open it directly in the notebook.

Obs: This is just one of the large .csv databases I'm working with, there are others with similar sizes, or even slightly bigger.

答:
pd.read_csv() function allows the first argument to be a .zip file path or URL, but only one file per ZIP file is supported. The posted zip file has multiple files.

You can iterate over entries in a zip file and read CSV data as a buffered object.

import pandas as pd
import zipfile
from io import BytesIO

with zipfile.ZipFile("perfil_eleitorado_2018.zip", "r") as f:
    for name in f.namelist():
        if name.endswith('.csv'):
            with f.open(name) as zd:
                df = pd.read_csv(zd, encoding='latin1', sep=';')
            print(df)
            break
```
<p>If you want to interact with the URL directly w/o first downloading it then use can use the request library.</p>
<pre class="lang-python prettyprint-override"><code>import pandas as pd
import zipfile
from io import BytesIO
import requests

url = 'https://cdn.tse.jus.br/estatistica/sead/odsele/perfil_eleitorado/perfil_eleitorado_2018.zip'
r = requests.get(url)
buf1 = BytesIO(r.content)
with zipfile.ZipFile(buf1, "r") as f:
    for name in f.namelist():
        if name.endswith('.csv'):
            with f.open(name) as zd:
                df = pd.read_csv(zd, encoding='latin1', sep=';')
            print(df)
            break
</code>```

Output:

```<code>    DT_GERACAO HH_GERACAO ANO_ELEICAO ... QT_ELEITORES_DEFICIENCIA QT_ELEITORES_INC_NM_SOCIAL
0   12/04/2021   13:55:01        2018 ...                        1                          0
1   12/04/2021   13:55:01        2018 ...                        2                          0
2   12/04/2021   13:55:01        2018 ...                        4                          0
3   12/04/2021   13:55:01        2018 ...                        2                          0
4   12/04/2021   13:55:01        2018 ...                       25                          0
..         ...        ...         ... ...                      ...                        ...
</code>```

Body:
I'm trying to read a large (~850 mb) .csv file from an URL.

The thing is that the .csv file is within a .zip file that also contains a .pdf file, so when I try to read it in pandas:

df = pd.read_csv('link', encoding='latin1', sep=';')

It doesn't work because it states:

ValueError: Multiple files found in ZIP file. Only one file per ZIP: ['LEIAME.pdf', 'perfil_eleitorado_2018.csv']

I'm working with a collaborative notebook, so the best solution would be just to open the .zip file directly from the link or to upload the .csv file somewhere that won't ask for permissions, log-ins, or anything like that to open it directly in the notebook.

Obs: This is just one of the large .csv databases I'm working with, there are others with similar sizes, or even slightly bigger.

Body:
pd.read_csv() function allows the first argument to be a .zip file path or URL, but only one file per ZIP file is supported. The posted zip file has multiple files.

You can iterate over entries in a zip file and read CSV data as a buffered object.

import pandas as pd
import zipfile
from io import BytesIO

with zipfile.ZipFile("perfil_eleitorado_2018.zip", "r") as f:
    for name in f.namelist():
        if name.endswith('.csv'):
            with f.open(name) as zd:
                df = pd.read_csv(zd, encoding='latin1', sep=';')
            print(df)
            break

If you want to interact with the URL directly w/o first downloading it then use can use the request library.

import pandas as pd
import zipfile
from io import BytesIO
import requests

url = 'https://cdn.tse.jus.br/estatistica/sead/odsele/perfil_eleitorado/perfil_eleitorado_2018.zip'
r = requests.get(url)
buf1 = BytesIO(r.content)
with zipfile.ZipFile(buf1, "r") as f:
    for name in f.namelist():
        if name.endswith('.csv'):
            with f.open(name) as zd:
                df = pd.read_csv(zd, encoding='latin1', sep=';')
            print(df)
            break

Output:

    DT_GERACAO HH_GERACAO ANO_ELEICAO ... QT_ELEITORES_DEFICIENCIA QT_ELEITORES_INC_NM_SOCIAL
0   12/04/2021   13:55:01        2018 ...                        1                          0
1   12/04/2021   13:55:01        2018 ...                        2                          0
2   12/04/2021   13:55:01        2018 ...                        4                          0
3   12/04/2021   13:55:01        2018 ...                        2                          0
4   12/04/2021   13:55:01        2018 ...                       25                          0
..         ...        ...         ... ...                      ...                        ...


问:
Can you help me I want to print the value of factorial 4 but the following function is always giving NAN why?
My question is about recursive function why it is showing always NAN instead of showing the value of factorial 4.</p>
```<code>function factorial(i){
              if (i == 1) { return;}
              return i * factorial(--i);};
      console.log(factorial(4));
</code>```

答:
if (i == 1) { return;}  you should return a number here like return 1;

```<code>function factorial(i){
              if (i == 1) { return 1;}
              return i * factorial(--i);};
      console.log(factorial(4));
</code>```

small version of code:

```<code>const fact = (num) => num ==1 ? 1 : num * fact(--num);
</code>```

Body:
My question is about recursive function why it is showing always NAN instead of showing the value of factorial 4.

function factorial(i){
              if (i == 1) { return;}
              return i * factorial(--i);};
      console.log(factorial(4));

Body:
if (i == 1) { return;}  you should return a number here like return 1;

function factorial(i){
              if (i == 1) { return 1;}
              return i * factorial(--i);};
      console.log(factorial(4));

small version of code:

const fact = (num) => num ==1 ? 1 : num * fact(--num);


问:
Docker cannot resolve DNS on private network
Docker is a software tool primarily used by programmers as it is the mechanism programmers use to produce container images.

My machine is on a private network with private DNS servers, and a private zone for DNS resolution. I can resolve hosts on this zone from my host machine, but I cannot resolve them from containers running on my host machine.

Host:

```<code>root@host:~# cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.1.1

root@host:~# ping privatedomain.io
PING privatedomain.io (192.168.0.101) 56(84) bytes of data.
</code>```

Container:

```<code>root@container:~# cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN

nameserver 8.8.8.8
nameserver 8.8.4.4

root@container:~# ping privatedomain.io
ping: unknown host privatedomain.io
</code>```

It's fairly obvious that Google's public DNS servers won't resolve my private DNS requests. I know I can force it with docker --dns 192.168.0.1, or set DOCKER_OPTS="--dns 192.168.0.1" in /etc/default/docker, but my laptop frequently switches networks. It seems like there should be a systematic way of solving this problem.

答:
I have the same error message in my systemctl status docker.
I run a Nextcloud and a nextcloud nginx proxy container and used docker compose to install it. It worked for multiple months without big hickups, but on Friday it wasn't accessable. The server had shut down.
I restarted it, my icecast2 instance is working fine and was used this sunday for the service in our church. But the docker containers are gone. docker ps -a doesn't show any, I can't access the nextcloud via docker exec like I would do normally. And I have the error message:

```<code>No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: [nameserver 8.8.8.8 nameserver 8.8.4.4]"
Feb 06 19:04:58 ncxxxxxxxxx dockerd[21551]: time="2022-02-06T19:04:58.894366765Z" level=info msg="IPv6 enabled; Adding default IPv6 external servers: [nameserver 2001:4860:4860::8888 nameserver 2001:4860:4860::8844]
</code>```

My resolv.conf looks like this:

```<code>GNU nano 4.8
/etc/resolv.conf
nameserver 127.0.0.53
options edns0 trust-ad
search fritz.box
</code>```

Body:
Docker is a software tool primarily used by programmers as it is the mechanism programmers use to produce container images.

My machine is on a private network with private DNS servers, and a private zone for DNS resolution. I can resolve hosts on this zone from my host machine, but I cannot resolve them from containers running on my host machine.

Host:

root@host:~# cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.1.1

root@host:~# ping privatedomain.io
PING privatedomain.io (192.168.0.101) 56(84) bytes of data.

Container:

root@container:~# cat /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN

nameserver 8.8.8.8
nameserver 8.8.4.4

root@container:~# ping privatedomain.io
ping: unknown host privatedomain.io

It's fairly obvious that Google's public DNS servers won't resolve my private DNS requests. I know I can force it with docker --dns 192.168.0.1, or set DOCKER_OPTS="--dns 192.168.0.1" in /etc/default/docker, but my laptop frequently switches networks. It seems like there should be a systematic way of solving this problem.

Body:
I have the same error message in my systemctl status docker.
I run a Nextcloud and a nextcloud nginx proxy container and used docker compose to install it. It worked for multiple months without big hickups, but on Friday it wasn't accessable. The server had shut down.
I restarted it, my icecast2 instance is working fine and was used this sunday for the service in our church. But the docker containers are gone. docker ps -a doesn't show any, I can't access the nextcloud via docker exec like I would do normally. And I have the error message:

No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: [nameserver 8.8.8.8 nameserver 8.8.4.4]"
Feb 06 19:04:58 ncxxxxxxxxx dockerd[21551]: time="2022-02-06T19:04:58.894366765Z" level=info msg="IPv6 enabled; Adding default IPv6 external servers: [nameserver 2001:4860:4860::8888 nameserver 2001:4860:4860::8844]

My resolv.conf looks like this:

GNU nano 4.8
/etc/resolv.conf
nameserver 127.0.0.53
options edns0 trust-ad
search fritz.box


问:
Invalid Selector sent to instance - objectForKey:
I get an error when running my code.  The culprit is me accessing a string from a plist below:

```<code>    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);
</code>```

I have this in my cocos2d Init shown here:

```<code>-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super init])) {

        NSUserDefaults *sud = [NSUserDefaults standardUserDefaults];
        NSString *ctlLang = [sud valueForKey:@"ctlLang"];
        NSNumber *questionState = [sud valueForKey:@"questionState"];
        NSNumber *scoreState = [sud valueForKey:@"scoreState"];
        gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
        for (NSString *element in gameArray) {
            NSLog(@"\nQL gameArray value=%d\n", [element intValue]);
        }
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:ctlLang];
        dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

        NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
        NSLog(@"%@",sImageFile);
    }
}
</code>```

The printing of the string works fine in the init section of the scene.  The problem occurs in a method I define later.  For some reason it is not returning the string in the method shown here:

```<code>-(void) checkAnswer: (id) sender {

    CGSize size = [[CCDirector sharedDirector] winSize];
    CCMenuItemSprite *sAnswer = (CCMenuItemSprite *)sender;
    NSLog(@"Checking Answer Tag is ---> %d",sAnswer.tag);
    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);
    if ([question.answer integerValue] == sAnswer.tag) {
        //...
    }
}
</code>```

What am I missing here?  the program bombs at the NSLog statement.

答:
You assign the object returned by dictionaryWithContentsOfFile: to the dictionary ivar but you do not claim ownership of it by sending it a retain message to it:

```<code>dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];
</code>```

The method dictionaryWithContentsOfFile: returns an object you do not own. Probably, by the time checkAnswer: is executed the object has already been deallocated. You need to retain it:

```<code>dictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
</code>```

Or use alloc-initWithContentsOfFile: instead, which returns an object you own:

```<code>dictionary = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
</code>```

And the same goes for the gameplay ivar. You do not own the object returned by valueForKey: and you need to retain it. So this line:

```<code>gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
</code>```

should be:

```<code>gameArray = [[sud valueForKey:@"gameArray"] retain];
</code>```

Body:
I get an error when running my code.  The culprit is me accessing a string from a plist below:

    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);

I have this in my cocos2d Init shown here:

-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super init])) {

        NSUserDefaults *sud = [NSUserDefaults standardUserDefaults];
        NSString *ctlLang = [sud valueForKey:@"ctlLang"];
        NSNumber *questionState = [sud valueForKey:@"questionState"];
        NSNumber *scoreState = [sud valueForKey:@"scoreState"];
        gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
        for (NSString *element in gameArray) {
            NSLog(@"\nQL gameArray value=%d\n", [element intValue]);
        }
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:ctlLang];
        dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

        NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
        NSLog(@"%@",sImageFile);
    }
}

The printing of the string works fine in the init section of the scene.  The problem occurs in a method I define later.  For some reason it is not returning the string in the method shown here:

-(void) checkAnswer: (id) sender {

    CGSize size = [[CCDirector sharedDirector] winSize];
    CCMenuItemSprite *sAnswer = (CCMenuItemSprite *)sender;
    NSLog(@"Checking Answer Tag is ---> %d",sAnswer.tag);
    NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
    NSLog(@"%@",sImageFile);
    if ([question.answer integerValue] == sAnswer.tag) {
        //...
    }
}

What am I missing here?  the program bombs at the NSLog statement.

Body:
You assign the object returned by dictionaryWithContentsOfFile: to the dictionary ivar but you do not claim ownership of it by sending it a retain message to it:

dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

The method dictionaryWithContentsOfFile: returns an object you do not own. Probably, by the time checkAnswer: is executed the object has already been deallocated. You need to retain it:

dictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];

Or use alloc-initWithContentsOfFile: instead, which returns an object you own:

dictionary = [[NSDictionary alloc] initWithContentsOfFile:finalPath];

And the same goes for the gameplay ivar. You do not own the object returned by valueForKey: and you need to retain it. So this line:

gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];

should be:

gameArray = [[sud valueForKey:@"gameArray"] retain];