问:
How to efficiently check whether a vector of numbers is in an interval defined by a data frame
I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1  in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

```<code>set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}
</code>```

Thanks!

答:
You could use approx with method = "constant" and specifying which limits to use by setting the f argument:

```<code>## dummy data
n1 <- runif(10, 0, 100)
df.int <- data.frame(
   upper = seq(1, 100, by = 1),
   value = runif(100, 0, 100)
)

approx(x = df.int$upper,
       y = df.int$value,
       xout = n1,
       method = "constant",
       f = 1,
       rule = 2             ## extrapolation behavior outside domain
)
</code>```

Body:
I have the following problem: I have one vector n1 which contains certain values (as an example I randomized the values in the code). I have a data frame df.int which contains one column of upper limits for intervals and one column of certain values (randomized it again, in reality the values are modes of something else). I want to check for each entry of n1  in which interval of the data frame it is and then overwrite the value of n1 with the value of the second column of the respective interval.

In general, my code should work but as n1 and the intervals are quite long, my script runs too long. So I want to ask how I could adjust my code such that it works more efficiently.

Here is the code:

set.seed(123)
seq.vec <- c(seq(400,800000,by=200))
n1 <- sample(100:800000, 2000, replace=TRUE)
df.int <- data.frame(matrix( nrow=length(seq.vec), ncol=2))
df.names <- c("Upper.Limit", "Value")
colnames(df.int) <- df.names
df.int$Upper.Limit <- seq.vec
df.int$Value <- sample(100:800000, length(seq.vec), replace=TRUE)
j <- 1
m <- 1
for (k in seq_len(n1)){
  for (i in seq_len(df.int$Upper.Limit)){
    if (j==1) {
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j],df.int$Value[j],n1[m])
    } else{
      n1[m] <- ifelse(n1<=df.int$Upper.Limit[j] & n1>df.int$Upper.Limit[j-1]
                            ,df.int$Value[j],n1[m])
    }
    j <- j+1
  }
  m <- m+1
}

Thanks!

Body:
You could use approx with method = "constant" and specifying which limits to use by setting the f argument:

## dummy data
n1 <- runif(10, 0, 100)
df.int <- data.frame(
   upper = seq(1, 100, by = 1),
   value = runif(100, 0, 100)
)

approx(x = df.int$upper,
       y = df.int$value,
       xout = n1,
       method = "constant",
       f = 1,
       rule = 2             ## extrapolation behavior outside domain
)


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Converting array of lists to array of dictionary

Body:
I have data as follows

{"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

I want to convert above data as follows

[{"value": 1288.1639933233453},
{"value": 1255.1777295971826},
{"value": 1250.1075681742996},
{"value": 1283.9962801780075},
{"value": 1297.4411412000093}]

Body:
using lambda

a={"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

res = list(map(lambda x:{'value':x[0]},a['array']))


问:
What programming language would be most beneficial to have the most proficiency with?
I still have a lot to learn in terms of programming and currently only know a decent amount of C++.  I'm aware that different languages have different uses, but I was just wondering if there was perhaps one that stood out as a superior language or a language that would be applicable to more tasks?

Thanks

答:
Java is really big in today's world, since almost everything on the internet uses it. You'll find Java will be a major part of a lot of different apps.

In the work world however, I believe C# is the most common language that companies are using. Almost all of the job notifications my computer science advisor sends out are asking for people experienced with C#. My boyfriend is currently working at a company that writes programs for casinos, and they use C#.

C++ is still a pretty major language though. It's what my job mainly uses.

ContentLicense: CC BY-SA 3.0


答:
Works with GitHub Webhook IPs in a loop

```<code>- name: get request to github
  uri:
    url: "https://api.github.com/meta"
    method: GET
    return_content: yes
    status_code: 200
    headers:
      Content-Type: "application/json"
      #X-Auth-Token: "0010101010"
    body_format: json
  register: json_response

- name:  GitHub webhook IPs
  debug:
    msg: "{{ item }}"
  with_items: "{{ (json_response.content | from_json).hooks }}"

</code>```

Title: Ansible parse json and read result into different variables

Body:
I've set up a task which queries the github api meta endpoint and returns the following

{
  "verifiable_password_authentication": true,
  "github_services_sha": "f9e3a6b98d76d9964a6613d581164039b8d54d89",
  "hooks": [
    "192.30.252.0/22",
    "185.199.108.0/22",
    "140.82.112.0/20"
  ],
  "git": [
    "192.30.252.0/22",
    "185.199.108.0/22",
    "140.82.112.0/20",
    "13.229.188.59/32",
    "13.250.177.223/32",
    "18.194.104.89/32",
    "18.195.85.27/32",
    "35.159.8.160/32",
    "52.74.223.119/32"
  ],
  "pages": [
    "192.30.252.153/32",
    "192.30.252.154/32",
    "185.199.108.153/32",
    "185.199.109.153/32",
    "185.199.110.153/32",
    "185.199.111.153/32"
  ],
  "importer": [
    "54.87.5.173",
    "54.166.52.62",
    "23.20.92.3"
  ]
}

What I need to do is get the 3 hook IPs and read them each into their own variable.

I've tried a couple of solutions i've found around but nothing is seeming to work for me.

I've got as far as drilling down into the json so i'm being returned only the 3 IPs, but how do I get them out and into variables individually?

Body:
Works with GitHub Webhook IPs in a loop

- name: get request to github
  uri:
    url: "https://api.github.com/meta"
    method: GET
    return_content: yes
    status_code: 200
    headers:
      Content-Type: "application/json"
      #X-Auth-Token: "0010101010"
    body_format: json
  register: json_response

- name:  GitHub webhook IPs
  debug:
    msg: "{{ item }}"
  with_items: "{{ (json_response.content | from_json).hooks }}"


问:
pandas.read_csv y-axis contains whole data rows and sklearn.linear model ValueError
I am very new to Python. I inserted a csv-file which contains data about used cars (price, yearOfRegistration, powerPS, Kilometer, model, fuelType) and used a scatter-plot to visualize my data. The x-axis should be the Kilometers and the y-axis the price. After running my code the label of the x-axis looks okay (labels are 20000, 40000, 60000, etc.) whereas the label of the y-axis does not. The label of the y-axis contains whole data rows and one line looks like this: 4500,1999,150,125000,3er,benzin,"BMW...".

I have tried to relabel the y-axis but I think that the problem exists in the csv data?

That is my code:

```<code>import pandas as pd

df = pd.read_csv("./autos_prepared.csv")
#print(df)

print(df.head())

print(df["price"])

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

import matplotlib.pyplot as plt

plt.scatter(df["kilometer"], df["price"])
plt.show()
</code>```

I expected a plot with the x-axis I described above and labels on the y-axis from 0, 10000, 20000, 30000, 40000. Instead I have got the results I described above.

Additionally I would like to add that I have got the

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

after trying to run this code:

```<code>from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(df[["kilometer"]], df[["price"]])
#
print("Intercept: " + str(model.intercept_))
print("Coef: " + str(model.coef_))
</code>```

Is there anyone who could help me? That would be great!

答: I think there indeed was an error in the data. Problem is solved now. I do not know exactly what was wrong but it works now.</p>

Body:
I am very new to Python. I inserted a csv-file which contains data about used cars (price, yearOfRegistration, powerPS, Kilometer, model, fuelType) and used a scatter-plot to visualize my data. The x-axis should be the Kilometers and the y-axis the price. After running my code the label of the x-axis looks okay (labels are 20000, 40000, 60000, etc.) whereas the label of the y-axis does not. The label of the y-axis contains whole data rows and one line looks like this: 4500,1999,150,125000,3er,benzin,"BMW...".

I have tried to relabel the y-axis but I think that the problem exists in the csv data?

That is my code:

import pandas as pd

df = pd.read_csv("./autos_prepared.csv")
#print(df)

print(df.head())

print(df["price"])

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

import matplotlib.pyplot as plt

plt.scatter(df["kilometer"], df["price"])
plt.show()

I expected a plot with the x-axis I described above and labels on the y-axis from 0, 10000, 20000, 30000, 40000. Instead I have got the results I described above.

Additionally I would like to add that I have got the

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

after trying to run this code:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(df[["kilometer"]], df[["price"]])
#
print("Intercept: " + str(model.intercept_))
print("Coef: " + str(model.coef_))

Is there anyone who could help me? That would be great!


问:
How to find next 2 or 4 null keys in dictionary with starting index
I have Dictionary<ushort, ushort> and let's say I have KeyValuePair from json file with index 43001 and value. If the value is float I have to convert the float to 2 ushort values and store them in the dictionary where the higher order bytes will be at 43001 and the lower order bytes will be stored at 43002. If it's double I have to store it as 4 ushorts. This is fine, I know how to do it. If I have another float value with the same starting index of 43001 I have to store it starting with 43003. If 43001 is already present, how can I find next 2 available index (or 4 for double)  after 43001 till 65535.

I know I can do something like

```<code>for (ushort i = 43001; i < 65535; i += 2)
{
   if (!dict.ContainsKey(i) && !dict.ConainsKey(i + 1))
   {
       return //whatever;
   }
}
</code>```

and the same for double, but I think there is more elegant and better way.

答:
Off the top of my head, something like</p>

```<code>var start = 43001;
var end = 65535;
var range = end - start;
var step = 2;
var nextSlot = Enumerable.Range(0, range / step)
    .Select(i => (ushort)(start + i * step))
    .First(i =>
        Enumerable.Range(0, step)
            .Select(ii => (ushort)(ii + i))
            .All(iii => !dict.ContainsKey(iii)));
</code>```

Body:
I have Dictionary<ushort, ushort> and let's say I have KeyValuePair from json file with index 43001 and value. If the value is float I have to convert the float to 2 ushort values and store them in the dictionary where the higher order bytes will be at 43001 and the lower order bytes will be stored at 43002. If it's double I have to store it as 4 ushorts. This is fine, I know how to do it. If I have another float value with the same starting index of 43001 I have to store it starting with 43003. If 43001 is already present, how can I find next 2 available index (or 4 for double)  after 43001 till 65535.

I know I can do something like

for (ushort i = 43001; i < 65535; i += 2)
{
   if (!dict.ContainsKey(i) && !dict.ConainsKey(i + 1))
   {
       return //whatever;
   }
}

and the same for double, but I think there is more elegant and better way.

Body:
Off the top of my head, something like

var start = 43001;
var end = 65535;
var range = end - start;
var step = 2;
var nextSlot = Enumerable.Range(0, range / step)
    .Select(i => (ushort)(start + i * step))
    .First(i =>
        Enumerable.Range(0, step)
            .Select(ii => (ushort)(ii + i))
            .All(iii => !dict.ContainsKey(iii)));


问:
deselecting checkbox is removing whole row from the front-end angular 4
i have this Panel array coming from backend which has another array Tests. i have mapped them on my custom accordion with checkboxes. the problem i am facing is i should be able to select/deselect Tests without removing it from the from front-end like it Disappears when i deselect. how can i solve this issue?

you can see from that image

https://i.stack.imgur.com/qJUFy.png

here is my html file

```<code><ngb-panel *ngFor="let panel of panels" id="{{panel.Id}}" [title]="panel.Name">
    <label class="custom-control custom-checkbox">
        <input type="checkbox" class="custom-control-input" [name]="panel.Id + '-' + panel.Moniker" [ngModel]="checkAllTestsSelected(panel)" (ngModelChange)="onPanelCheckboxUpdate($event, panel)" [id]="panel.Id + '-' + panel.Moniker">
        <span class="custom-control-indicator"></span>
    </label>

    </ng-template>
    <ng-template ngbPanelContent>
        <div class="individual-panel" *ngFor="let test of panel.Tests">
            <span class="text-dimmed">{{test.Name}}</span>
            <span *ngIf="panel.Name.includes('ENA') || panel.Name.includes('Celiac')">
                <label class="custom-control custom-checkbox">
                    <input type="checkbox" class="custom-control-input" [name]="test.Id + '-' + test.Code"
                    [ngModel]="testSelectionSession.SelectedPanelIds.indexOf(panel.Id) > -1 || testSelectionSession.SelectedPanelIds.indexOf(test.AssociatedPanel?.Id) > -1"
                    (ngModelChange)="onTestCheckboxUpdate($event, test, panel)"
                    [id]="test.Id + '-' + test.Code">
                    <span class="custom-control-indicator"></span>
                </label>
            </span>
        </div>
</code>```

ts file

```<code>checkAllTestsSelected(panel: TestOrderPanel) {
    // get all individual test panels
    let individualTestPanelIds = panel.Tests.reduce((acc, test) => {
        if (test.AssociatedPanel) {
            acc.push(test.AssociatedPanel.Id);
        }
        return acc;
    }, []);

    // check if all individual test panels are selected

    let allIndividualTestsSelected = individualTestPanelIds.reduce(
        (acc: boolean, panelId: number) =>
        acc && this.panelIds.indexOf(panelId) > -1,
        individualTestPanelIds.length > 0 &&
        panel.Tests.length === individualTestPanelIds.length
    );

    // if selected, remove all individual test panels and add the panel group
    if (panel.Tests.length > 0 && allIndividualTestsSelected) {
        this.panelIds = this.panelIds.filter(
            panelId => individualTestPanelIds.indexOf(panelId) === -1
        );
        this.selectedPanels = this.selectedPanels.filter(
            selectedPanel => individualTestPanelIds.indexOf(selectedPanel.Id) === -1
        );
        this.panelIds.push(panel.Id);
        this.selectedPanels.push(panel);
        this.updateSession();
    }
    return this.panelIds.indexOf(panel.Id) > -1;
}

onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
    let testPanelIds = panel.Tests.reduce((acc, test) => {
        if (test.AssociatedPanel) {
            acc.push(test.AssociatedPanel.Id);
        }

        return acc;
    }, []);

    // Wipe any duplicates
    this.panelIds = this.panelIds.filter(
        panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
    );
    this.selectedPanels = this.selectedPanels.filter(
        selectedPanel =>
        panel.Id !== selectedPanel.Id &&
        testPanelIds.indexOf(selectedPanel.Id) === -1
    );

    if ($event) {
        this.panelIds.push(panel.Id);
        this.selectedPanels.push(panel);
    }
    this.updateSession();
}

onTestCheckboxUpdate($event: boolean,
    test: TestOrderPanelTest,
    panel: TestOrderPanel,
    index) {

    let testPanelIds = panel.Tests.reduce((acc, test) => {
        if (test.AssociatedPanel) {
            acc.push(test.AssociatedPanel.Id);
        }

        return acc;
    }, []);
    let associatedTestPanels =
        this.testSelectionSession.IndividualTestPanelsForAll.filter(
            testPanel => testPanelIds.indexOf(testPanel.Id) > -1
        );
    // If the panel is selected and a test within the panel is deselected,
    // remove the panel and back all of the individual tests
    if (this.panelIds.indexOf(panel.Id) > -1 && !$event) {
        this.selectedPanels = this.selectedPanels.filter(
            e => e.Tests.splice(index, 1)
        );
    }

    let clickedTestPanel = associatedTestPanels.find(
        testPanel => (test.AssociatedPanel ? test.AssociatedPanel.Id : -1) ===
        testPanel.Id
    );

    if (clickedTestPanel) {
        // Wipe any duplicates
        this.panelIds = this.panelIds.filter(
            panelId => clickedTestPanel.Id !== panelId
        );
        this.selectedPanels = this.selectedPanels.filter(
            panel => clickedTestPanel.Id !== panel.Id
        );

        // Add individual panel if checkbox selected
        if ($event) {
            this.panelIds = this.panelIds.concat(clickedTestPanel.Id);
            this.selectedPanels = this.selectedPanels.concat(clickedTestPanel);
        }
    }
    this.updateSession();
}
</code>```

this.panelIds includes IDs of panels and this.selectedPanels includes whole panel array which is selected.

i have created a stackblitz too

my code is doing something like that stackblitz.com/edit/angular-bsszc9

and here is example of how my page will look like
stackblitz

how can i solve this problem?
thanks

答:
Delete

```<code>if (this.panelIds.indexOf(panel.Id) > -1 && !$event) {
    this.selectedPanels = this.selectedPanels.filter(
        e => e.Tests.splice(index, 1)
    );
}
</code>```

This part doesn't do anything but removing checkboxes and panels for no logical reason in a very random way (removing the checkbox with the same index from each panel and if there isn't any remove the whole panel)

Please read: Array.prototype.splice and Array.prototype.filter to understand how is this happening.

Body:
i have this Panel array coming from backend which has another array Tests. i have mapped them on my custom accordion with checkboxes. the problem i am facing is i should be able to select/deselect Tests without removing it from the from front-end like it Disappears when i deselect. how can i solve this issue?

you can see from that image

https://i.stack.imgur.com/qJUFy.png

here is my html file

<ngb-panel *ngFor="let panel of panels" id="{{panel.Id}}" [title]="panel.Name">

        <input type="checkbox" class="custom-control-input" [name]="panel.Id + '-' + panel.Moniker" [ngModel]="checkAllTestsSelected(panel)" (ngModelChange)="onPanelCheckboxUpdate($event, panel)" [id]="panel.Id + '-' + panel.Moniker">

    </ng-template>
    <ng-template ngbPanelContent>

            {{test.Name}}

                    <input type="checkbox" class="custom-control-input" [name]="test.Id + '-' + test.Code"
                    [ngModel]="testSelectionSession.SelectedPanelIds.indexOf(panel.Id) > -1 || testSelectionSession.SelectedPanelIds.indexOf(test.AssociatedPanel?.Id) > -1"
                    (ngModelChange)="onTestCheckboxUpdate($event, test, panel)"
                    [id]="test.Id + '-' + test.Code">

ts file

checkAllTestsSelected(panel: TestOrderPanel) {
    // get all individual test panels
    let individualTestPanelIds = panel.Tests.reduce((acc, test) => {
        if (test.AssociatedPanel) {
            acc.push(test.AssociatedPanel.Id);
        }
        return acc;
    }, []);

    // check if all individual test panels are selected

    let allIndividualTestsSelected = individualTestPanelIds.reduce(
        (acc: boolean, panelId: number) =>
        acc && this.panelIds.indexOf(panelId) > -1,
        individualTestPanelIds.length > 0 &&
        panel.Tests.length === individualTestPanelIds.length
    );

    // if selected, remove all individual test panels and add the panel group
    if (panel.Tests.length > 0 && allIndividualTestsSelected) {
        this.panelIds = this.panelIds.filter(
            panelId => individualTestPanelIds.indexOf(panelId) === -1
        );
        this.selectedPanels = this.selectedPanels.filter(
            selectedPanel => individualTestPanelIds.indexOf(selectedPanel.Id) === -1
        );
        this.panelIds.push(panel.Id);
        this.selectedPanels.push(panel);
        this.updateSession();
    }
    return this.panelIds.indexOf(panel.Id) > -1;
}

onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
    let testPanelIds = panel.Tests.reduce((acc, test) => {
        if (test.AssociatedPanel) {
            acc.push(test.AssociatedPanel.Id);
        }

        return acc;
    }, []);

    // Wipe any duplicates
    this.panelIds = this.panelIds.filter(
        panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
    );
    this.selectedPanels = this.selectedPanels.filter(
        selectedPanel =>
        panel.Id !== selectedPanel.Id &&
        testPanelIds.indexOf(selectedPanel.Id) === -1
    );

    if ($event) {
        this.panelIds.push(panel.Id);
        this.selectedPanels.push(panel);
    }
    this.updateSession();
}

onTestCheckboxUpdate($event: boolean,
    test: TestOrderPanelTest,
    panel: TestOrderPanel,
    index) {

    let testPanelIds = panel.Tests.reduce((acc, test) => {
        if (test.AssociatedPanel) {
            acc.push(test.AssociatedPanel.Id);
        }

        return acc;
    }, []);
    let associatedTestPanels =
        this.testSelectionSession.IndividualTestPanelsForAll.filter(
            testPanel => testPanelIds.indexOf(testPanel.Id) > -1
        );
    // If the panel is selected and a test within the panel is deselected,
    // remove the panel and back all of the individual tests
    if (this.panelIds.indexOf(panel.Id) > -1 && !$event) {
        this.selectedPanels = this.selectedPanels.filter(
            e => e.Tests.splice(index, 1)
        );
    }

    let clickedTestPanel = associatedTestPanels.find(
        testPanel => (test.AssociatedPanel ? test.AssociatedPanel.Id : -1) ===
        testPanel.Id
    );

    if (clickedTestPanel) {
        // Wipe any duplicates
        this.panelIds = this.panelIds.filter(
            panelId => clickedTestPanel.Id !== panelId
        );
        this.selectedPanels = this.selectedPanels.filter(
            panel => clickedTestPanel.Id !== panel.Id
        );

        // Add individual panel if checkbox selected
        if ($event) {
            this.panelIds = this.panelIds.concat(clickedTestPanel.Id);
            this.selectedPanels = this.selectedPanels.concat(clickedTestPanel);
        }
    }
    this.updateSession();
}

this.panelIds includes IDs of panels and this.selectedPanels includes whole panel array which is selected.

i have created a stackblitz too

my code is doing something like that stackblitz.com/edit/angular-bsszc9

and here is example of how my page will look like
stackblitz

how can i solve this problem?
thanks

Body:
Delete

if (this.panelIds.indexOf(panel.Id) > -1 && !$event) {
    this.selectedPanels = this.selectedPanels.filter(
        e => e.Tests.splice(index, 1)
    );
}

This part doesn't do anything but removing checkboxes and panels for no logical reason in a very random way (removing the checkbox with the same index from each panel and if there isn't any remove the whole panel)

Please read: Array.prototype.splice and Array.prototype.filter to understand how is this happening.


问:
Transform Rotate Menu Item Circular Menu
I have modified a circular menu that I found on this pen
But I am having trouble rotating the menu items around the main circle. By default of this pen, the button's bottom part is perpendicular to it's relative position, but since I changed them with font icons, they look upside down or crooked.

I'm a CSS noob, so I need some help please, been at this for hours!

I've tried a couple of things like:

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}
```
<p>or something like</p>
<pre class="lang-css prettyprint-override"><code>menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
}
</code>```

None of them seems to be working. Currently my component looks like this:

Here is my full CSS and HTML...

menu {
  box-sizing: border-box;
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--<menu>
    <li><i className="fas fa-bell"></i></li>
    <li><i className="fas fa-cog"></i></li>
    <li><i className="fas fa-terminal"></i></li>
</menu>-->

<menu>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</menu></code>```

答:
menu {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 30px;
  height: 70px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}
li a {
  transform :rotate(180deg);
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><menu>
  <li><a>1</a></li>
    <li><a>2</a></li>
    <li><a>3</a></li>
</menu></code>```

wrap your list content in a block element or inline element like i did! and rotate this element 180deg!

Body:
I have modified a circular menu that I found on this pen
But I am having trouble rotating the menu items around the main circle. By default of this pen, the button's bottom part is perpendicular to it's relative position, but since I changed them with font icons, they look upside down or crooked.

I'm a CSS noob, so I need some help please, been at this for hours!

I've tried a couple of things like:

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

or something like

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
}

None of them seems to be working. Currently my component looks like this:

Here is my full CSS and HTML...

menu {
  box-sizing: border-box;
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}

<menu>

1

2

3

</menu>

Body:
menu {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 30px;
  height: 70px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}
li a {
  transform :rotate(180deg);
  display:block;
}

<menu>
  <li><a>1</a></li>
    <li><a>2</a></li>
    <li><a>3</a></li>
</menu>

wrap your list content in a block element or inline element like i did! and rotate this element 180deg!


问:
How do I access an element in a list item within a key of a dict?
I currently have a JSON file which outputs a wide range of weather data. I can refine the information I want to a certain degree but need to refine it one step further but am unable to.

I have tried selecting it based on location e.g [1] and I have also tried to access the data based on keys e.g.  ['weather'] but I can only refine it so much before Python throws an error.

```<code>{'coord': {'lon': -1.98, 'lat': 50.72}, 'weather': [{'id': 803, 'main':
'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base':
'stations', 'main': {'temp': 293.6, 'pressure': 1022, 'humidity': 64,
'temp_min': 292.15, 'temp_max': 294.82}, 'visibility': 10000, 'wind':
{'speed': 5.1, 'deg': 230}, 'clouds': {'all': 75}, 'dt': 1559214671,
'sys': {'type': 1, 'id': 1401, 'message': 0.0072, 'country': 'GB',
'sunrise': 1559188945, 'sunset': 1559246925}, 'timezone': 3600, 'id':
2640101, 'name': 'Poole', 'cod': 200}
</code>```

The above code is the JSON file that I have to work with, I want to refine and extract for example the 'main' value in 'weather' so I would like to extract the string 'Clouds' but I have tried things like dict['weather]['main'] but it simply throws up an error.

Looking for some advice :D

答:
The value for weather is a list, so you'd need dict['weather'][0]['main'].

Also, I recommend not calling a particular dictionary dict, because it hides the built-in dict function.

Body:
I currently have a JSON file which outputs a wide range of weather data. I can refine the information I want to a certain degree but need to refine it one step further but am unable to.

I have tried selecting it based on location e.g [1] and I have also tried to access the data based on keys e.g.  ['weather'] but I can only refine it so much before Python throws an error.

{'coord': {'lon': -1.98, 'lat': 50.72}, 'weather': [{'id': 803, 'main':
'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base':
'stations', 'main': {'temp': 293.6, 'pressure': 1022, 'humidity': 64,
'temp_min': 292.15, 'temp_max': 294.82}, 'visibility': 10000, 'wind':
{'speed': 5.1, 'deg': 230}, 'clouds': {'all': 75}, 'dt': 1559214671,
'sys': {'type': 1, 'id': 1401, 'message': 0.0072, 'country': 'GB',
'sunrise': 1559188945, 'sunset': 1559246925}, 'timezone': 3600, 'id':
2640101, 'name': 'Poole', 'cod': 200}

The above code is the JSON file that I have to work with, I want to refine and extract for example the 'main' value in 'weather' so I would like to extract the string 'Clouds' but I have tried things like dict['weather]['main'] but it simply throws up an error.

Looking for some advice :D


问:
Changing behavior of EditTextPreference when clicked
I'm trying to change the behavior of a EditTextPreference for my needs.
It hold a path i set using an intent.
My problem is it also open his own Fragment to modify his text.
I end up with 2 consecutives windows: the ACTION_OPEN_DOCUMENT_TREE which i wanted and the default windows to write a simple string in a box.

Here the SettingFragment.java:

```<code>@Override
public  void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.root_preferences, rootKey);

    Preference editTextPreference = getPreferenceManager().findPreference("path");
    if (editTextPreference != null) {
        editTextPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference arg0) {
                Intent secondActivity = new Intent(ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(secondActivity, RQS_OPEN_DOCUMENT_TREE);

                return true;
            }
        });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE) {
        Uri treeUri = data.getData();
        System.out.println(treeUri.toString());
        String path = FileUtil.getFullPathFromTreeUri(treeUri, getContext());

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        sharedPreferences.edit().putString("path",path).apply();
    }
}
</code>```

Here the associated xml:

```<code><androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory>
    <EditTextPreference
        app:key="path"
        app:title="@string/path_title"
        app:useSimpleSummaryProvider="true"
    />
</PreferenceCategory>
</code>```

I tried changing EditTextPreference for Preference but the value woulnd't show anymore. I've found out that useSimpleSummaryProvider could only be applied to ListPreference and EditTextPreference.
I also tried to disable it but it would no longer fire onPreferenceClick().
Is there a way to only execute onPreferenceClick rather than the default fragment or a better way to handle this?

答:
I managed to get around the problem, sort of, using Preference instead of EditTextPreference. So now it only open up ACTION_OPEN_DOCUMENT_TREE.
Then i used this code to set the summary i need:</p>

```<code>Preference editPreference = getPreferenceManager().findPreference("path");
editPreference.setSummary(sharedPreferences.getString("path", "Le chemin n'est pas défini"));
</code>```

Body:
I'm trying to change the behavior of a EditTextPreference for my needs.
It hold a path i set using an intent.
My problem is it also open his own Fragment to modify his text.
I end up with 2 consecutives windows: the ACTION_OPEN_DOCUMENT_TREE which i wanted and the default windows to write a simple string in a box.

Here the SettingFragment.java:

@Override
public  void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
    setPreferencesFromResource(R.xml.root_preferences, rootKey);

    Preference editTextPreference = getPreferenceManager().findPreference("path");
    if (editTextPreference != null) {
        editTextPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference arg0) {
                Intent secondActivity = new Intent(ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(secondActivity, RQS_OPEN_DOCUMENT_TREE);

                return true;
            }
        });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE) {
        Uri treeUri = data.getData();
        System.out.println(treeUri.toString());
        String path = FileUtil.getFullPathFromTreeUri(treeUri, getContext());

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        sharedPreferences.edit().putString("path",path).apply();
    }
}

Here the associated xml:

<androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory>
    <EditTextPreference
        app:key="path"
        app:title="@string/path_title"
        app:useSimpleSummaryProvider="true"
    />
</PreferenceCategory>

I tried changing EditTextPreference for Preference but the value woulnd't show anymore. I've found out that useSimpleSummaryProvider could only be applied to ListPreference and EditTextPreference.
I also tried to disable it but it would no longer fire onPreferenceClick().
Is there a way to only execute onPreferenceClick rather than the default fragment or a better way to handle this?

Body:
I managed to get around the problem, sort of, using Preference instead of EditTextPreference. So now it only open up ACTION_OPEN_DOCUMENT_TREE.
Then i used this code to set the summary i need:

Preference editPreference = getPreferenceManager().findPreference("path");
editPreference.setSummary(sharedPreferences.getString("path", "Le chemin n'est pas défini"));


问:
Import file loop based on name variable
I apologise if this is atrociously easy but I have absolutely zero experience with VBA and I'm sort of jumping hurdles as I go along. I've figured out how to import a file from text and convert it as I need using the record macro function.
I'm now looking to loop this process, based on a file name variable.
The file's I'm looking to import would use the naming convention AB1, AB2, AB3, etc, or something equally as arbitrary, once the file is imported, and converted into the formatting code, it would repeat the process on a new page. </p>

<p>I've tried various coding frameworks from many websites but I can never successfully integrate it into my code already. </p>

```<code>Sub LoadFromFile()
Dim fileName As String, folder As String

folder = "FILEPATH
fileName = ActiveCell.Value

ActiveCell.Offset(1, 0).Range("A1").Select

With ActiveSheet.QueryTables _
    .Add(Connection:="TEXT;" & folder & fileName,
Destination:=ActiveCell)
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 850
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
Cells.Select
With Selection.Font
    .Name = "Lucida Console"
    .Size = 8
    .Strikethrough = False
    .Superscript = False
    .Subscript = False
    .OutlineFont = False
    .Shadow = False
    .Underline = xlUnderlineStyleNone
    .ThemeColor = xlThemeColorLight1
    .TintAndShade = 0
    .ThemeFont = xlThemeFontNone

End With
Application.PrintCommunication = False
With ActiveSheet.PageSetup
  .Orientation = xlLandscape
       .LeftHeader = ""
    .CenterHeader = ""
    .RightHeader = ""
    .LeftFooter = ""
    .CenterFooter = ""
    .RightFooter = ""
    .LeftMargin = Application.InchesToPoints(0.25)
    .RightMargin = Application.InchesToPoints(0.25)
    .TopMargin = Application.InchesToPoints(0.75)
    .BottomMargin = Application.InchesToPoints(0.75)
    .HeaderMargin = Application.InchesToPoints(0.3)
    .FooterMargin = Application.InchesToPoints(0.3)
End With
Application.PrintCommunication = True

End Sub
</code>```

答:
if the files are all in the same folder u can use a function like this, to get the name off all file in the folder

```<code>Function listfiles(ByVal sPath As String)

    Dim vaArray     As Variant
    Dim i           As Integer
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    Set oFiles = oFolder.Files

    If oFiles.Count = 0 Then Exit Function

    ReDim vaArray(1 To oFiles.Count)
    i = 1
    For Each oFile In oFiles
        vaArray(i) = oFile.Name
        i = i + 1
    Next

    listfiles = vaArray

End Function
</code>```

and then u can do a "For Each " to get each file and run your code inside it.

good luck

Title: Import file loop based on name variable

Body:
I apologise if this is atrociously easy but I have absolutely zero experience with VBA and I'm sort of jumping hurdles as I go along. I've figured out how to import a file from text and convert it as I need using the record macro function.
I'm now looking to loop this process, based on a file name variable.
The file's I'm looking to import would use the naming convention AB1, AB2, AB3, etc, or something equally as arbitrary, once the file is imported, and converted into the formatting code, it would repeat the process on a new page.

I've tried various coding frameworks from many websites but I can never successfully integrate it into my code already.

Sub LoadFromFile()
Dim fileName As String, folder As String

folder = "FILEPATH
fileName = ActiveCell.Value

ActiveCell.Offset(1, 0).Range("A1").Select

With ActiveSheet.QueryTables _
    .Add(Connection:="TEXT;" & folder & fileName,
Destination:=ActiveCell)
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 850
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
Cells.Select
With Selection.Font
    .Name = "Lucida Console"
    .Size = 8
    .Strikethrough = False
    .Superscript = False
    .Subscript = False
    .OutlineFont = False
    .Shadow = False
    .Underline = xlUnderlineStyleNone
    .ThemeColor = xlThemeColorLight1
    .TintAndShade = 0
    .ThemeFont = xlThemeFontNone

End With
Application.PrintCommunication = False
With ActiveSheet.PageSetup
  .Orientation = xlLandscape
       .LeftHeader = ""
    .CenterHeader = ""
    .RightHeader = ""
    .LeftFooter = ""
    .CenterFooter = ""
    .RightFooter = ""
    .LeftMargin = Application.InchesToPoints(0.25)
    .RightMargin = Application.InchesToPoints(0.25)
    .TopMargin = Application.InchesToPoints(0.75)
    .BottomMargin = Application.InchesToPoints(0.75)
    .HeaderMargin = Application.InchesToPoints(0.3)
    .FooterMargin = Application.InchesToPoints(0.3)
End With
Application.PrintCommunication = True

End Sub

Body:
if the files are all in the same folder u can use a function like this, to get the name off all file in the folder

Function listfiles(ByVal sPath As String)

    Dim vaArray     As Variant
    Dim i           As Integer
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    Set oFiles = oFolder.Files

    If oFiles.Count = 0 Then Exit Function

    ReDim vaArray(1 To oFiles.Count)
    i = 1
    For Each oFile In oFiles
        vaArray(i) = oFile.Name
        i = i + 1
    Next

    listfiles = vaArray

End Function

and then u can do a "For Each " to get each file and run your code inside it.

good luck


问:
Why the compiler is reading first the internal term and then going out?
lets assume I've done return something1(something2(something3)); then the PC is first doing the internal term and then going to the next term which is something2 and then going to the next term which is something1, my question why he's going in that way and not going opposite, like this : doing first something1, then something2 , then something3?</p>

答:
Actually, it works just fine.
Let's take your own example, you want to execute function1(function2(function3())),

Now, if you break it down,
The program first goes to execute function1(), but function1() requires the value of function2(), so it jumps to execute function2(), and now function2() requires the value of function3(), so the function3() gets executed.

It just seems that the program is executing in opposite order but actually it is working in a regular way.


问:
The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel
I have a problem with my edit page. When I submit I get this error:

The POST method is not supported for this route. Supported methods: GET, HEAD.

I have no clue where it comes from as I am pretty new to Laravel.

routes(web.php):

```<code>Route::group(['middleware' => 'auth'], function () {
Route::get('/', 'ProjectController@index');

Route::get('/projects/{id}', 'ProjectController@show');
Route::post('/create','ProjectController@store');
Route::get('/create', 'ProjectController@create');
Route::get('/projects/{id}/delete', 'ProjectController@destroy');
Route::put('/edit','ProjectController@update');
Route::get('/projects/{id}/edit', 'ProjectController@edit');

});
</code>```

Controller:

```<code> public function edit($id)
    {
        return view('project.edit',[

            'project' => Project::find($id)
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $project = Project::find($request->id);
        $project->project_name = $request->input('project_name');
        $project->client = $request->input('client');
        $project->description = $request->input('description');
        $project->time_span = $request->input('time_span');
        $project->text_report = $request->input('text_report');
        $project->created_by = $request->input('created_by');

        $project->save();

        return  redirect('/')->with('success', 'Project aangepast');
    }
</code>```

答:
Hi you dont have to write all the routes just follow the conventions  https://laravel.com/docs/5.8/controllers
check : Actions Handled By Resource Controller section

Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method. When posting a data from n laravel you have to use,

```<code><form action="/foo/bar" method="POST">
@method('PUT')
</form>
</code>```

Body:
I have a problem with my edit page. When I submit I get this error:

The POST method is not supported for this route. Supported methods: GET, HEAD.

I have no clue where it comes from as I am pretty new to Laravel.

routes(web.php):

Route::group(['middleware' => 'auth'], function () {
Route::get('/', 'ProjectController@index');

Route::get('/projects/{id}', 'ProjectController@show');
Route::post('/create','ProjectController@store');
Route::get('/create', 'ProjectController@create');
Route::get('/projects/{id}/delete', 'ProjectController@destroy');
Route::put('/edit','ProjectController@update');
Route::get('/projects/{id}/edit', 'ProjectController@edit');

});

Controller:

 public function edit($id)
    {
        return view('project.edit',[

            'project' => Project::find($id)
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $project = Project::find($request->id);
        $project->project_name = $request->input('project_name');
        $project->client = $request->input('client');
        $project->description = $request->input('description');
        $project->time_span = $request->input('time_span');
        $project->text_report = $request->input('text_report');
        $project->created_by = $request->input('created_by');

        $project->save();

        return  redirect('/')->with('success', 'Project aangepast');
    }

Body:
Hi you dont have to write all the routes just follow the conventions  https://laravel.com/docs/5.8/controllers
check : Actions Handled By Resource Controller section

Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method. When posting a data from n laravel you have to use,

<form action="/foo/bar" method="POST">
@method('PUT')
</form>


问:
PHP urldecode() function wont work for email validation
Im trying to decode the email, since its been encoded in the url, but the urldecode() function wont decode it.

I'v also tried rawurldecode(), then tried first encoding it myself and then decoding it, but its still encoded like %40 instead of an @ sign.

Here is the code:

```<code>$isValid = ! User::emailExists(urldecode($_GET['email']));
</code>```

Im getting something like this:

http://localhost/account/validate-email?email=some_email%40gmail.com

答:
I made a simple test:

```<code><?php
$email = "some_email%40example.com";
var_dump($email);
var_dump(urldecode($email));
var_dump(rawurldecode($email));
</code>```

The (expected) output is:

string(24) "some_email%40example.com"

string(22) "some_email@example.com"

string(22) "some_email@example.com"

So decoding works as expected.

Could it be that you are looking at a single example where what you think is a %40 actually is something else, like a sequence that contains a unicode character that only looks like those you expect but actually is different?

Body:
Im trying to decode the email, since its been encoded in the url, but the urldecode() function wont decode it.

I'v also tried rawurldecode(), then tried first encoding it myself and then decoding it, but its still encoded like %40 instead of an @ sign.

Here is the code:

$isValid = ! User::emailExists(urldecode($_GET['email']));

Im getting something like this:

http://localhost/account/validate-email?email=some_email%40gmail.com

Body:
I made a simple test:

<?php
$email = "some_email%40example.com";
var_dump($email);
var_dump(urldecode($email));
var_dump(rawurldecode($email));

The (expected) output is:

string(24) "some_email%40example.com"

string(22) "some_email@example.com"

string(22) "some_email@example.com"

So decoding works as expected.

Could it be that you are looking at a single example where what you think is a %40 actually is something else, like a sequence that contains a unicode character that only looks like those you expect but actually is different?


问:
Removing the duplicates from an array of objects
Duplicate values are being storing into an array of object

Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array

But with the below piece of code duplicate values are being stored into an array teamSocketsList

```<code>var  TeamUser = {
    userId : userID,
    socketId : socket.id
}

var i = $.inArray( userID, teamSocketsList );
if(i == -1){
    teamSocketsList.push(TeamUser);
}else{
        teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
        return value != userID;
    });
}
</code>```

Actual Result:

```<code>[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
</code>```

Expected Result:

```<code>[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
</code>```

Edit:

Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value

The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.

Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.

答:
use reduce along with Object.values. create an object whose keys are userId. If the key does not exist, create the key and then use Object.values to get the required ouput.

const input = [
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
];

const output = Object.values(input.reduce((accu, {userId, socketId}) => {
    if(!accu[userId]) accu[userId] = {userId, socketId};
    return accu;
}, {}));

console.log(output);```

Body:
Duplicate values are being storing into an array of object

Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array

But with the below piece of code duplicate values are being stored into an array teamSocketsList

var  TeamUser = {
    userId : userID,
    socketId : socket.id
}

var i = $.inArray( userID, teamSocketsList );
if(i == -1){
    teamSocketsList.push(TeamUser);
}else{
        teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
        return value != userID;
    });
}

Actual Result:

[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]

Expected Result:

[
    {"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
    {"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]

Edit:

Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value

The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.

Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.


问:
Does Java read a single byte in big endian bit order?
So we can talk about the endianness of both the bit and byte order.
When I read the next byte from FileInputStream, for example, I practically get an 8-bit signed integer, but I have no idea what is the bit order with which Java calculates the byte's integer value. Which comes first, the most significant or the least significant bit?

(sign bit, 2^6 ..... 2^0)
Or...
(2^0, ..... 2^6, sign bit)

答:
Endianness only really applies when a unit is broken down into other units. So if you were transmitting a byte over a bit stream, you could observe whether the least significant bit was transmitted first or last.  And at that point we could say that the stream was little-endian or big-endian.

But within a byte-addressable machine, i.e., where the byte is the smallest unit of storage, there is no "endianness" within the byte.  No bit of the byte is "before" any other bit of the byte.

Note that another term for endianness is "byte order". The order of bytes within larger entities.

It is true we like to number bits (0 to 7, for an 8-bit byte) so we can talk about them, but this really does not define endianness, even though the numbering is often chosen to match the byte order of the machine; this is convention.

With respect to FileInputStream - according to its documentation, that transfers bytes: no part of the byte is sent before any other part, at least not as far as FileInputStream is concerned.  If the byte has to be sent bitwise over some interconnect (say, a SATA cable), then the decision about which bit goes first is a matter for the hardware.  The higher layer code is dealing in bytes (or even blocks).


问:
what is the issue with encryption in c++ and decryption in php
Here, I have c++ program which encodes the string and I have to decrypt in php. I have verified that the key and the iv are same in both programs, still getting false in openssl_decrypt() command.

```<code>    int main(int argc, char** args)
    {
        unsigned char *salt = (unsigned char*)"12345678";
        unsigned char *data = (unsigned char*)"123456789123450";
        unsigned int count        = 5;
        int dlen                  = strlen((char*)data);
        unsigned int ksize        = 16;
        unsigned int vsize        = 12;
        unsigned char *key        = new unsigned char[ksize];
        unsigned char *iv         = new unsigned char[vsize];

        int ret = EVP_BytesToKey( EVP_aes_128_gcm() , EVP_sha1(), salt, data, dlen, count, key, iv);

        const EVP_CIPHER*     m_cipher = EVP_aes_128_gcm();
        EVP_CIPHER_CTX* m_encode;
        EVP_CIPHER_CTX* m_decode;
        if (!(m_encode = EVP_CIPHER_CTX_new()))
           cout << "ERROR :: In encode Initiallization"<< endl;

        EVP_EncryptInit_ex(m_encode, m_cipher, NULL, key, iv);

        if (!(m_decode = EVP_CIPHER_CTX_new()))
            cout << "ERROR :: In decode Initiallization"<< endl;
        EVP_DecryptInit_ex(m_decode, m_cipher, NULL, key, iv);
        unsigned char* plain = (unsigned char*)"My Name IS  DON !!!";
        int len  = strlen((char*)plain);
        unsigned char* encData = new unsigned char[len];

        int c_len = len;
        int f_len = 0;
        EVP_EncryptInit_ex(m_encode, NULL, NULL, NULL, NULL);
        EVP_EncryptUpdate(m_encode, encData, &c_len, plain, len);
        EVP_EncryptFinal_ex(m_encode, encData + c_len, &f_len);

        len = c_len + f_len;

        cout << string( encData, encData + len)<< endl;
    }
</code>```

And the following is decryption code in php. "./abc_enc.txt" contains encryption string of c++ code. As I mentioned above I am getting same key and iv for both programs but openssl_decrypt function returns false. Can someone figure out what is the mistake?

```<code>    <?
    function EVP_BytesToKey($salt, $password) {
        $ivlen = 12;
        $keylen = 16;
        $iterations = 5;
        $hash = "";
        $hdata = "";
        while(strlen($hash)<$ivlen+$keylen)
        {
            $hdata .= $password.$salt;
            $md_buf = openssl_digest($hdata, 'sha1');
            for ($i = 1; $i < $iterations; $i++) {
                $md_buf = openssl_digest ( hex2bin($md_buf),'sha1');
            }
            $hdata = hex2bin($md_buf);
            $hash.= $hdata;
         }
         return $hash;
    }
    function decrypt($ivHashCiphertext, $password) {
         $method = "aes-128-gcm";
         $salt = "12345678";
         $iterations = 5;
         $ivlen = openssl_cipher_iv_length($method);
         $ciphertext = $ivHashCiphertext;
         $genKeyData = EVP_BytesToKey($salt, $password);
         $keylen = 16;
         $key = substr($genKeyData,0,$keylen);
         $iv  = substr($genKeyData,$keylen,$ivlen);
         //var_dump($key);
         //var_dump($iv);
         $ret = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
         var_dump($ret);
         return $ret;
    }
    $file = './abc_enc.txt';
    $fileData = (file_get_contents($file));
    $encrypted = $fileData;
    $decrypted = decrypt($encrypted, '123456789123450');
    ?>
</code>```

答:
In short

I'm neither an openSSL nor a PHP specialist.  But at first sight, it appears that you might experience problems because you read and write binary data using files in text mode.

More infos about the potential problem

The encrypted data resulting from your C++ code is binary data. Your code does not show how you write the file. But unless you explicitly request the file to be in binary mode, you will get a file in text mode.

This might cause multiple issues when writing the data, since text mode allows for OS-dependent transformations to happen.  Typical examples are characters with value 0x0A (new lines), skipping trailing 0x20 (space character), adding a 0x0A at the end of the file if there isn't and similar undesired transformation.

Your PHP code might open the file in an incompatible default mode,  which might add further transformation if it's text mode, or avoid reverting transformations if it's binary.

This means that in the end, the string you try to decode might not be the original encrypted string !

How to solve it ?

First inspect with a binary editor the content of the file to see if it matches the expectations.  Or check the expected length of the encrypted source data,  the length of the file, and the length of the loaded content.  If they all match, my answer is not relevant.

If it is relevant, or if you intend sooner or later to allow cross platform exchanges (e.g. windows client communicating with a linux server), then you could:

either add the necessary statements to use binary mode on both sides.

or add a Base64 encoding to transform binary into a robust ascii string on the writing side, and retransforming Base64 into binary on the reading side (openssl provides for base64 encoding and PHP has everything needed as well)

Body:
Here, I have c++ program which encodes the string and I have to decrypt in php. I have verified that the key and the iv are same in both programs, still getting false in openssl_decrypt() command.

    int main(int argc, char** args)
    {
        unsigned char *salt = (unsigned char*)"12345678";
        unsigned char *data = (unsigned char*)"123456789123450";
        unsigned int count        = 5;
        int dlen                  = strlen((char*)data);
        unsigned int ksize        = 16;
        unsigned int vsize        = 12;
        unsigned char *key        = new unsigned char[ksize];
        unsigned char *iv         = new unsigned char[vsize];

        int ret = EVP_BytesToKey( EVP_aes_128_gcm() , EVP_sha1(), salt, data, dlen, count, key, iv);

        const EVP_CIPHER*     m_cipher = EVP_aes_128_gcm();
        EVP_CIPHER_CTX* m_encode;
        EVP_CIPHER_CTX* m_decode;
        if (!(m_encode = EVP_CIPHER_CTX_new()))
           cout << "ERROR :: In encode Initiallization"<< endl;

        EVP_EncryptInit_ex(m_encode, m_cipher, NULL, key, iv);

        if (!(m_decode = EVP_CIPHER_CTX_new()))
            cout << "ERROR :: In decode Initiallization"<< endl;
        EVP_DecryptInit_ex(m_decode, m_cipher, NULL, key, iv);
        unsigned char* plain = (unsigned char*)"My Name IS  DON !!!";
        int len  = strlen((char*)plain);
        unsigned char* encData = new unsigned char[len];

        int c_len = len;
        int f_len = 0;
        EVP_EncryptInit_ex(m_encode, NULL, NULL, NULL, NULL);
        EVP_EncryptUpdate(m_encode, encData, &c_len, plain, len);
        EVP_EncryptFinal_ex(m_encode, encData + c_len, &f_len);

        len = c_len + f_len;

        cout << string( encData, encData + len)<< endl;
    }

And the following is decryption code in php. "./abc_enc.txt" contains encryption string of c++ code. As I mentioned above I am getting same key and iv for both programs but openssl_decrypt function returns false. Can someone figure out what is the mistake?

    <?
    function EVP_BytesToKey($salt, $password) {
        $ivlen = 12;
        $keylen = 16;
        $iterations = 5;
        $hash = "";
        $hdata = "";
        while(strlen($hash)<$ivlen+$keylen)
        {
            $hdata .= $password.$salt;
            $md_buf = openssl_digest($hdata, 'sha1');
            for ($i = 1; $i < $iterations; $i++) {
                $md_buf = openssl_digest ( hex2bin($md_buf),'sha1');
            }
            $hdata = hex2bin($md_buf);
            $hash.= $hdata;
         }
         return $hash;
    }
    function decrypt($ivHashCiphertext, $password) {
         $method = "aes-128-gcm";
         $salt = "12345678";
         $iterations = 5;
         $ivlen = openssl_cipher_iv_length($method);
         $ciphertext = $ivHashCiphertext;
         $genKeyData = EVP_BytesToKey($salt, $password);
         $keylen = 16;
         $key = substr($genKeyData,0,$keylen);
         $iv  = substr($genKeyData,$keylen,$ivlen);
         //var_dump($key);
         //var_dump($iv);
         $ret = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
         var_dump($ret);
         return $ret;
    }
    $file = './abc_enc.txt';
    $fileData = (file_get_contents($file));
    $encrypted = $fileData;
    $decrypted = decrypt($encrypted, '123456789123450');
    ?>


问:
How to publish specific files using Publish Build Artifact Task
I am Building C# Application using Visual Studio Build In Azure Pipeline.

My solution Contains multiple project (ManagerWeb & WebAPI).

I want to Publish Two Separate Artifact ManagerWeb & WebAPI respectively.

All the required File's are present in Build.ArtifactStagingDirectory.

How I can specify a pattern using which I can get Two Separate Artifact ?
Example All the File name with WebAPI in 1st Artifact & ManagerWeb in another.

The File name from ArtifactStaging Directory are as Below

```<code>Something.Manager.WebAPI.deploy.cmd
Something.Manager.WebAPI.deploy-readme.txt
Something.Manager.WebAPI.SetParameters.xml
Something.Manager.WebAPI.SourceManifest.xml
Something.Manager.WebAPI.zip

Something.ManagerWeb.deploy.cmd
Something.ManagerWeb.deploy-readme.txt
Something.ManagerWeb.SetParameters.xml
Something.ManagerWeb.SourceManifest.xml
Something.ManagerWeb.zip
</code>```

Any Help will be appreciable.

Thanks in Advance.

答:
Add a PowerShell task to create two folders and move the files to there:

```<code>cd $(Build.ArtifactStagingDirectory)
$files = dir
mkdir WebAPI
mkdir ManagerWeb
ForEach($file in $files)
{
   if($file.FullName.Contains("WebAPI"))
   {
       mv $file.FullName -Destination WebAPI
   }
   else
   {
       mv $file.FullName -Destination ManagerWeb
   }
}
</code>```

Then in the "Path to publish" field add the folders:

For WebApi artifacts:

```<code>$(Build.ArtifactStagingDirectory)/WebAPI
</code>```

And for ManagerWeb artifacts:

```<code>$(Build.ArtifactStagingDirectory)/ManagerWeb
</code>```

Body:
I am Building C# Application using Visual Studio Build In Azure Pipeline.

My solution Contains multiple project (ManagerWeb & WebAPI).

I want to Publish Two Separate Artifact ManagerWeb & WebAPI respectively.

All the required File's are present in Build.ArtifactStagingDirectory.

How I can specify a pattern using which I can get Two Separate Artifact ?
Example All the File name with WebAPI in 1st Artifact & ManagerWeb in another.

The File name from ArtifactStaging Directory are as Below

Something.Manager.WebAPI.deploy.cmd
Something.Manager.WebAPI.deploy-readme.txt
Something.Manager.WebAPI.SetParameters.xml
Something.Manager.WebAPI.SourceManifest.xml
Something.Manager.WebAPI.zip

Something.ManagerWeb.deploy.cmd
Something.ManagerWeb.deploy-readme.txt
Something.ManagerWeb.SetParameters.xml
Something.ManagerWeb.SourceManifest.xml
Something.ManagerWeb.zip

Any Help will be appreciable.

Thanks in Advance.

Body:
Add a PowerShell task to create two folders and move the files to there:

cd $(Build.ArtifactStagingDirectory)
$files = dir
mkdir WebAPI
mkdir ManagerWeb
ForEach($file in $files)
{
   if($file.FullName.Contains("WebAPI"))
   {
       mv $file.FullName -Destination WebAPI
   }
   else
   {
       mv $file.FullName -Destination ManagerWeb
   }
}

Then in the "Path to publish" field add the folders:

For WebApi artifacts:

$(Build.ArtifactStagingDirectory)/WebAPI

And for ManagerWeb artifacts:

$(Build.ArtifactStagingDirectory)/ManagerWeb


问:
How can parse JSon with special characters?
This my text in database:

```<code>"推奨切削条件 "
</code>```

in PHP, i using Json_encode:
Result:

```<code>{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]};
</code>```

In javascript :

```<code>var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';//getData();
strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
var jsonData = JSON.parse(strData)
</code>```

Error:

```<code>Uncaught SyntaxError: Unexpected token  in JSON at position 56
    at JSON.parse (<anonymous>)
</code>```

How can parse JSon with special characters?

Thanks all.

答:
You can try out as,

var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';

strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");

// Your code
// var jsonData = JSON.parse(strData);

var jsonData = JSON.parse(JSON.stringify(strData));

console.log(JSON.parse(JSON.stringify(jsonData)));```

Body:
This my text in database:

"推奨切削条件 "

in PHP, i using Json_encode:
Result:

{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]};

In javascript :

var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';//getData();
strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
var jsonData = JSON.parse(strData)

Error:

Uncaught SyntaxError: Unexpected token  in JSON at position 56
    at JSON.parse (<anonymous>)

How can parse JSon with special characters?

Thanks all.


问:
Is there a way to paste display_errors code in another file than php.ini
Hi I was trying to comment on this for advice

Wordpress - The Jetpack server could not communicate with your site’s XML-RPC URL

But It was suggested I ask a new question.
So here goes:

Is there any way to paste the code you suggested in the .htaccess file?
Or in another php file?

Because I can't find the php.ini file anywhere, tried to look everywhere.
(Yes, I searched in SO and google and youtube for answers, and tried it all)

So is there any way to edit the error_reporting somewehere else?

This is what I want to do to help with the connection between jetpack and website as delboy1978uk suggests.

set error_reporting to -1, turn display_errors off, and set a custom error_log. Then in the terminal, type tail -f /path/to/error_log

Thanks in advance for any advice you could give.
Reshma

答:
So I'm posting this answer also, because this was the last step in recovering the jetpack dashboard and settings page.

I've tried to access my wp-admin via Chrome browser.
And that seemed to do the trick so to speak.
I was using Internet Explorer before.

But in Chrome, Jetpack works just fine!!

I have my dashboard and settings page back up in the websites back-end
Yesss!!!
I have no explanation as to why jetpack suddenly wasn't working properly in IE anymore.
But I'm so happy that all is well now with my jetpack plugin.

I hope these two answers offer solutions for others who are experiencing the same issue.
(because it was a nightmare for me)

Kind regards, Reshma


问:
Is there a JavaScript (or jQuery) shortcut for "function(){return false;}"?
To prevent actions from happening, I frequently type

```<code>function(){return false;}
</code>```

Is there a shortcut?

答:
You can cancel an event default action by using the preventDefault method:</p>

```<code>$("form").bind("submit", function(event){
  event.preventDefault();
});
</code>```

OwnerDisplayName: Steven Noble

Body:
To prevent actions from happening, I frequently type

function(){return false;}

Is there a shortcut?

Body:
You can cancel an event default action by using the preventDefault method:

$("form").bind("submit", function(event){
  event.preventDefault();
});

OwnerDisplayName: CMS

ContentLicense: CC BY-SA 2.5


问:
Get span Id's of selected text using getSelected()
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

So a simple example of a paragraph is below.

```<code><span id="p-58" class="softWord" onClick="setTranscriptPosition(-58);return false"> that </span>
<span id="p177" class="softWord" onClick="setTranscriptPosition(177);return false"> quake </span>
<span id="p857" class="softWord" onClick="setTranscriptPosition(857);return false"> briefly </span>
<span id="p1697" class="softWord" onClick="setTranscriptPosition(1697);return false"> triggering </span>
<span id="p2267" class="softWord" onClick="setTranscriptPosition(2267);return false"> another </span>
<span id="p2697" class="softWord" onClick="setTranscriptPosition(2697);return false"> tsunami </span>
</code>```

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

```<code>function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }
</code>```

How would i get the id's of those spans though?

答:
If you don't mind using a library, my Rangy library makes this pretty simple. The following will work in all major browsers (including IE 6):

jsFiddle: http://jsfiddle.net/VC3hk/24/

Code:

```<code>function getSelectedSpanIds() {
    var sel = rangy.getSelection(), ids = [];
    for (var r = 0, range, spans; r < sel.rangeCount; ++r) {
        range = sel.getRangeAt(r);
        if (range.startContainer == range.endContainer && range.startContainer.nodeType == 3) {
            range = range.cloneRange();
            range.selectNode(range.startContainer.parentNode);
        }
        spans = range.getNodes([1], function(node) {
              return node.nodeName.toLowerCase() == "span";
        });
        for (var i = 0, len = spans.length; i < len; ++i) {
            ids.push(spans[i].id);
        }
    }
    return ids;
}

document.onkeyup = document.onmouseup = function() {
    alert(getSelectedSpanIds());
};
</code>```

Body:
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

So a simple example of a paragraph is below.

 that
 quake
 briefly
 triggering
 another
 tsunami

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }

How would i get the id's of those spans though?

Body:
If you don't mind using a library, my Rangy library makes this pretty simple. The following will work in all major browsers (including IE 6):

jsFiddle: http://jsfiddle.net/VC3hk/24/

Code:

function getSelectedSpanIds() {
    var sel = rangy.getSelection(), ids = [];
    for (var r = 0, range, spans; r < sel.rangeCount; ++r) {
        range = sel.getRangeAt(r);
        if (range.startContainer == range.endContainer && range.startContainer.nodeType == 3) {
            range = range.cloneRange();
            range.selectNode(range.startContainer.parentNode);
        }
        spans = range.getNodes([1], function(node) {
              return node.nodeName.toLowerCase() == "span";
        });
        for (var i = 0, len = spans.length; i < len; ++i) {
            ids.push(spans[i].id);
        }
    }
    return ids;
}

document.onkeyup = document.onmouseup = function() {
    alert(getSelectedSpanIds());
};


问:
Index when using OR in query
What is the best way to create index when I have a query like this?

```<code>... WHERE (user_1 = '$user_id' OR user_2 = '$user_id') ...
</code>```

I know that only one index can be used in a query so I can't create two indexes, one for user_1 and one for user_2.

Also could solution for this type of query be used for this query?

```<code>WHERE ((user_1 = '$user_id' AND user_2 = '$friend_id') OR (user_1 = '$friend_id' AND user_2 = '$user_id'))
</code>```

答:
The two cases are different.

At the first case both columns needs to be searched for the same value. If you have a two column index (u1,u2) then it may be used at the column u1 as it cannot be used at column u2. If you have two indexes separate for u1 and u2 probably both of them will be used. The choice comes from statistics based on how many rows are expected to be returned. If returned rows expected few an index seek will be selected, if the appropriate index is available. If the number is high a scan is preferable, either table or index.

At the second case again both columns need to be checked again, but within each search there are two sub-searches where the second sub-search will be upon the results of the first one, due to the AND condition. Here it matters more and two indexes u1 and u2 will help as any field chosen to be searched first will have an index. The choice to use an index is like i describe above.

In either case however every OR will force 1 more search or set of searches. So the proposed solution of breaking using union does not hinder more as the table will be searched x times no matter 1 select with OR(s) or x selects with union and no matter index selection and type of search (seek or scan). As a result, since each select at the union get its own execution plan part, it is more likely that (single column) indexes will be used and finally get all row result sets from all parts around the OR(s). If you do not want to copy a large select statement to many unions you may get the primary key values and then select those or use a view to be sure the majority of the statement is in one place.

Finally, if you exclude the union option, there is a way to trick the optimizer to use a single index. Create a double index u1,u2 (or u2,u1 - whatever column has higher cardinality goes first) and modify your statement so all OR parts use all columns:

```<code>... WHERE (user_1 = '$user_id' OR user_2 = '$user_id') ...
</code>```

will be converted to:

```<code>... WHERE ((user_1 = '$user_id' and user_2=user_2) OR (user_1=user_1 and user_2 = '$user_id')) ...
</code>```

This way a double index (u1,u2) will be used at all times. Please not that this will work if columns are nullable and bypassing this with isnull or coalesce may cause index not to be selected. It will work with ansi nulls off however.

Title: Index when using OR in query

Body:
What is the best way to create index when I have a query like this?

... WHERE (user_1 = '$user_id' OR user_2 = '$user_id') ...

I know that only one index can be used in a query so I can't create two indexes, one for user_1 and one for user_2.

Also could solution for this type of query be used for this query?

WHERE ((user_1 = '$user_id' AND user_2 = '$friend_id') OR (user_1 = '$friend_id' AND user_2 = '$user_id'))

Body:
The two cases are different.

At the first case both columns needs to be searched for the same value. If you have a two column index (u1,u2) then it may be used at the column u1 as it cannot be used at column u2. If you have two indexes separate for u1 and u2 probably both of them will be used. The choice comes from statistics based on how many rows are expected to be returned. If returned rows expected few an index seek will be selected, if the appropriate index is available. If the number is high a scan is preferable, either table or index.

At the second case again both columns need to be checked again, but within each search there are two sub-searches where the second sub-search will be upon the results of the first one, due to the AND condition. Here it matters more and two indexes u1 and u2 will help as any field chosen to be searched first will have an index. The choice to use an index is like i describe above.

In either case however every OR will force 1 more search or set of searches. So the proposed solution of breaking using union does not hinder more as the table will be searched x times no matter 1 select with OR(s) or x selects with union and no matter index selection and type of search (seek or scan). As a result, since each select at the union get its own execution plan part, it is more likely that (single column) indexes will be used and finally get all row result sets from all parts around the OR(s). If you do not want to copy a large select statement to many unions you may get the primary key values and then select those or use a view to be sure the majority of the statement is in one place.

Finally, if you exclude the union option, there is a way to trick the optimizer to use a single index. Create a double index u1,u2 (or u2,u1 - whatever column has higher cardinality goes first) and modify your statement so all OR parts use all columns:

... WHERE (user_1 = '$user_id' OR user_2 = '$user_id') ...

will be converted to:

... WHERE ((user_1 = '$user_id' and user_2=user_2) OR (user_1=user_1 and user_2 = '$user_id')) ...

This way a double index (u1,u2) will be used at all times. Please not that this will work if columns are nullable and bypassing this with isnull or coalesce may cause index not to be selected. It will work with ansi nulls off however.


答:
please replace the \b to ""   strData=strData.replace("\b","");

```<code><script>
    var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';
   strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
   strData=strData.replace("\b","");
   document.write(strData);
   var jsonData = JSON.parse(strData)
   document.write(jsonData);
</code>```

Title: How can parse JSon with special characters?

Body:
please replace the \b to ""   strData=strData.replace("\b","");

<script>
    var strData ='{"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}';
   strData=strData.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
   strData=strData.replace("\b","");
   document.write(strData);
   var jsonData = JSON.parse(strData)
   document.write(jsonData);


问:
Fastest way for generating fake files with given filesize
I'm looking for fastest way to generate fake files for stress test where is a possibility to pass file size. Currently I'm using simple

with open("{}".format(i), 'wb') as f: f.write(os.urandom(FILE_SIZE))

but for my case, creating each file takes too long. It seems to me that the Faker library does not have the method to generate fake files

EDIT: The code below is just a part of whole script so any CMD/OS commands are not a solution for my problem.

答:
Wouldn't it be better to use OS commands for that?

```<code>dd if=/dev/urandom of=/tmp/x bs=1M count=1
</code>```

You could start that using subprocess module:

```<code>subprocess.check_call("dd if=/dev/urandom of=/tmp/y bs=1M count=1".split(" "))
</code>```

Body:
Wouldn't it be better to use OS commands for that?

dd if=/dev/urandom of=/tmp/x bs=1M count=1

You could start that using subprocess module:

subprocess.check_call("dd if=/dev/urandom of=/tmp/y bs=1M count=1".split(" "))


问:
Need help with hashMap with expiry time constraints
I need a thread-safe Map with a time limited expiry policy. I tried looking for an existing library, but could not find one. Jboss cache is going to be a heavy alternative for my requirement. I have a first cut draft in place. Please have a look at the code posted on pastebin

I need constructive comments and enhancement suggestions. Thanks in advance.

答: i'm sure ehcache would have something that would work.  maybe a bit "lighter" than jboss cache.</p>


问:
In JavaScript, how do I check that only one "@" is present in an input?
I am trying to make an email validator and I want to make a command to check that the user input (the email the user enters) contains ONLY ONE OF "@" and ".". Example: name@@.com would be invalid</p>

```<code>function validateEmail(){
let enterEmail = prompt("Enter your email to see if it is valid");
let removeSpace = (enterEmail.trim());
let s = removeSpace.indexOf('@');
let lastS = removeSpace.lastIndexOf('.');
if (s > 1 && lastS > 1) {
    Output("emailOutput", "The Email you have entered is valid");
    }
else {
    Output("emailOutput", "The Email you have entered is invalid");
}
}
</code>```

答:
```<code>let s = "mail@@@.com"
s.match(/@/g).length
</code>```

Length here will be the number of occurrences in the string

Body:
I am trying to make an email validator and I want to make a command to check that the user input (the email the user enters) contains ONLY ONE OF "@" and ".". Example: name@@.com would be invalid

function validateEmail(){
let enterEmail = prompt("Enter your email to see if it is valid");
let removeSpace = (enterEmail.trim());
let s = removeSpace.indexOf('@');
let lastS = removeSpace.lastIndexOf('.');
if (s > 1 && lastS > 1) {
    Output("emailOutput", "The Email you have entered is valid");
    }
else {
    Output("emailOutput", "The Email you have entered is invalid");
}
}

Body:
let s = "mail@@@.com"
s.match(/@/g).length

Length here will be the number of occurrences in the string


问:
How selectRow of PickerView can affect on Button enabled?
I have UIPickerView and button. I want if I choose raw number 0 then button is not enabled and vice versa. I have this construction in my code:

```<code>    import UIKit

    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    ...
    @IBOutlet weak var buttonOutlet: UIButton!
    @IBOutlet weak var firstPicker: UIPickerView!
    @IBOutlet weak var secondPicker: UIPickerView!

    let firstData = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
    let secondData = ["00", "10", "20", "30", "40", "50"]

    @IBOutlet weak var firstLabel: UILabel!
    @IBOutlet weak var secondLabel: UILabel!

    var first: Int!
    var second: Int!

    var firstRaw = 1
    var secondRaw = 0
            ...
        override func viewDidLoad() {
            super.viewDidLoad()

            self.firstPicker.delegate = self
            self.firstPicker.dataSource = self
            self.secondPicker.delegate = self
            self.secondPicker.dataSource = self

            firstPicker.selectRow(firstRaw, inComponent: 0, animated: true)
            secondPicker.selectRow(firstRaw, inComponent: 0, animated: true)
            if (self.firstRaw == 0) && (self.secondRaw == 0) {
                self.buttonOutlet.isEnabled = false
            } else {
                self.buttonOutlet.isEnabled = true
            }
        ...
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if pickerView == firstPicker {
                ...
            } else {
                ...
    }
</code>```

Why this construction doesn't work?

答:
To detect when a value is selected you must implement the UIPickerViewDelegate, also implement didSelectRow method of picker view. I'm assuming that you already populate your picker view data.

```<code>class ViewController : UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var buttonOutlet: UIButton!
    @IBOutlet weak var firstPicker: UIPickerView!
    var firstRaw = 1
        ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.firstPicker.delegate = self
        ...
    }
    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
        if self.firstRaw == 0 {
            self.buttonOutlet.isEnabled = false
        } else {
            self.buttonOutlet.isEnabled = true
        }
    }
}
</code>```

Body:
I have UIPickerView and button. I want if I choose raw number 0 then button is not enabled and vice versa. I have this construction in my code:

    import UIKit

    class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    ...
    @IBOutlet weak var buttonOutlet: UIButton!
    @IBOutlet weak var firstPicker: UIPickerView!
    @IBOutlet weak var secondPicker: UIPickerView!

    let firstData = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10"]
    let secondData = ["00", "10", "20", "30", "40", "50"]

    @IBOutlet weak var firstLabel: UILabel!
    @IBOutlet weak var secondLabel: UILabel!

    var first: Int!
    var second: Int!

    var firstRaw = 1
    var secondRaw = 0
            ...
        override func viewDidLoad() {
            super.viewDidLoad()

            self.firstPicker.delegate = self
            self.firstPicker.dataSource = self
            self.secondPicker.delegate = self
            self.secondPicker.dataSource = self

            firstPicker.selectRow(firstRaw, inComponent: 0, animated: true)
            secondPicker.selectRow(firstRaw, inComponent: 0, animated: true)
            if (self.firstRaw == 0) && (self.secondRaw == 0) {
                self.buttonOutlet.isEnabled = false
            } else {
                self.buttonOutlet.isEnabled = true
            }
        ...
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            if pickerView == firstPicker {
                ...
            } else {
                ...
    }

Why this construction doesn't work?

Body:
To detect when a value is selected you must implement the UIPickerViewDelegate, also implement didSelectRow method of picker view. I'm assuming that you already populate your picker view data.

class ViewController : UIViewController, UIPickerViewDelegate {

    @IBOutlet weak var buttonOutlet: UIButton!
    @IBOutlet weak var firstPicker: UIPickerView!
    var firstRaw = 1
        ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.firstPicker.delegate = self
        ...
    }
    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
        if self.firstRaw == 0 {
            self.buttonOutlet.isEnabled = false
        } else {
            self.buttonOutlet.isEnabled = true
        }
    }
}