问:
How to trigger an event (together) in JavaScript?
i have created an EventListener for each button but i have button generation all and i need to call all events at once.I tried to put everything inside a function, but I don't know how to activate all events.
I would be very grateful for any help

答:
You can just call HTMLElement.click() on everyelement to simulate the click on every element. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

```<code>buttonAll.addEventListener('click', ()=> {
    nameButton.click();
    balanceButton.click();
    ageButton.click();
    documentButton.click();
    levelButton.click();
    buttonClear.click();
})
</code>```

if the list can grow then you might want to group the elements in an array to keep the function short

```<code>let buttonAllTargets = [
    nameButton,
    balanceButton,
    ageButton,
    documentButton,
    levelButton,
    buttonClear
];

buttonAllTargets.forEach(element => element.click());
buttonAll.addEventListener('click', ()=> {
    buttonAllTargets.forEach(element => element.click());
})
</code>```

Body:
You can just call HTMLElement.click() on everyelement to simulate the click on every element. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

buttonAll.addEventListener('click', ()=> {
    nameButton.click();
    balanceButton.click();
    ageButton.click();
    documentButton.click();
    levelButton.click();
    buttonClear.click();
})

if the list can grow then you might want to group the elements in an array to keep the function short

let buttonAllTargets = [
    nameButton,
    balanceButton,
    ageButton,
    documentButton,
    levelButton,
    buttonClear
];

buttonAllTargets.forEach(element => element.click());
buttonAll.addEventListener('click', ()=> {
    buttonAllTargets.forEach(element => element.click());
})


来源: stackexchange

问:
Javascript Function - Parameter match of Object in Array within an Object Loop
```<code>var dset2 = {
"DataFile": [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]}

var catValueArray = [];
var vertValueArray = [];
var indValueArray = [];
for (i = 0; i < dset2.DataFile.length; i++) {
    if (!catValueArray.includes(dset2.DataFile[i].Cat)) {
        catValueArray.push(dset2.DataFile[i].Cat);
    }
    if (!vertValueArray.includes(dset2.DataFile[i].Vert)) {
        vertValueArray.push(dset2.DataFile[i].Vert);
    }
    if (!indValueArray.includes(dset2.DataFile[i].Ind)) {
        indValueArray.push(dset2.DataFile[i].Ind);
    }
    console.log(catValueArray);
    console.log(vertValueArray);
    console.log(indValueArray);
}
</code>```

Results are

```<code>Array [ "D School", "T School", "S School" ];
Array [ "D Safety" ];
Array [ "A Ind", "B Ind" ];

</code>```

I would like to convert this into a reusable function.
IE:

```<code>var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].prop)) {
            array.push(dataset[i].prop);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');
</code>```

That doesn't work. However, if I move "Cat" inside the function, I can get a result.
IE:

```<code>var catValueArray = [];
var dsetSwitch = dset2.DataFile;
function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].Cat)) {
            array.push(dataset[i].Cat);
        }
    }
    console.log(array);
}
pullUniqueValues(dsetSwitch, catValueArray);
</code>```

The end result is to reuse on a a datasets that has over 10 keys that will be used as identifiers and the number of items ill need to access them is very large. Currently because I can not get the Object parameter passed into the function, I have been forced to hard code every instance where I need to access the key. IE: Anytime I need to access "Cat" key, from the Object in the Array DataFile from within the Object dset2, I have to explicerly write the loop with dset2.DataFile[i].Cat.

Additional attempts with no success passing the property parameter into the function.

```<code>var DataFile = [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]

var uniqueValues = [];
function giveUniqueValues1(prop){
uniqueValues = DataFile.map(item => item.prop)
  .filter((value, index, self) => self.indexOf(value) === index);
}
function giveUniqueValues2(prop){
uniqueValues = [...new Set(DataFile.map(item => item.prop))];
}

uniqueValues = DataFile.map(item => item.Cat)
  .filter((value, index, self) => self.indexOf(value) === index); // Successs
giveUniqueValues1(Cat); //Failed Error
giveUniqueValues1('Cat'); //Failed Undefined result for uniqueValues;

uniqueValues = [...new Set(DataFile.map(item => item.Cat))]; //Success
giveUniqueValues2('Cat'); //Fail No Values Returned
giveUniqueValues2(Cat); //Fail Error Out

</code>```

答:
I've made a function that does what you want it to do and only takes an array as an argument.

const array = [
    {
        ID: 1,
        Cat: 'D School',
        Vert: 'D Safety',
        Ind: 'A Ind',
    },
    {
        ID: 2,
        Cat: 'T School',
        Vert: 'D Safety',
        Ind: 'B Ind',
    },
    {
        ID: 3,
        Cat: 'S School',
        Vert: 'D Safety',
        Ind: 'B Ind',
    },
];

const returnUniqueArrays = (arr) => {
    // Create a map to keep track of our arrays
    const arrayMap = {};

    // Iterate for every object in the dataset
    arr.forEach((obj) => {
        for (const [key, value] of Object.entries(obj)) {
            // If an array with that key doesn't already exist, add it and push the value
            if (!arrayMap[key]) {
                arrayMap[key] = [value];
            } else {
                // If the existing array doesn't have the unique value, push it
                arrayMap[key] = [...new Set([...arrayMap[key], value])];
            }
        }
    });

    return Object.values(arrayMap);
};

console.log(returnUniqueArrays(array));```

ContentLicense: CC BY-SA 4.0

Body:
var dset2 = {
"DataFile": [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]}

var catValueArray = [];
var vertValueArray = [];
var indValueArray = [];
for (i = 0; i < dset2.DataFile.length; i++) {
    if (!catValueArray.includes(dset2.DataFile[i].Cat)) {
        catValueArray.push(dset2.DataFile[i].Cat);
    }
    if (!vertValueArray.includes(dset2.DataFile[i].Vert)) {
        vertValueArray.push(dset2.DataFile[i].Vert);
    }
    if (!indValueArray.includes(dset2.DataFile[i].Ind)) {
        indValueArray.push(dset2.DataFile[i].Ind);
    }
    console.log(catValueArray);
    console.log(vertValueArray);
    console.log(indValueArray);
}

Results are

Array [ "D School", "T School", "S School" ];
Array [ "D Safety" ];
Array [ "A Ind", "B Ind" ];

I would like to convert this into a reusable function.
IE:

var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].prop)) {
            array.push(dataset[i].prop);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');

That doesn't work. However, if I move "Cat" inside the function, I can get a result.
IE:

var catValueArray = [];
var dsetSwitch = dset2.DataFile;
function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].Cat)) {
            array.push(dataset[i].Cat);
        }
    }
    console.log(array);
}
pullUniqueValues(dsetSwitch, catValueArray);

The end result is to reuse on a a datasets that has over 10 keys that will be used as identifiers and the number of items ill need to access them is very large. Currently because I can not get the Object parameter passed into the function, I have been forced to hard code every instance where I need to access the key. IE: Anytime I need to access "Cat" key, from the Object in the Array DataFile from within the Object dset2, I have to explicerly write the loop with dset2.DataFile[i].Cat.

Additional attempts with no success passing the property parameter into the function.

var DataFile = [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]

var uniqueValues = [];
function giveUniqueValues1(prop){
uniqueValues = DataFile.map(item => item.prop)
  .filter((value, index, self) => self.indexOf(value) === index);
}
function giveUniqueValues2(prop){
uniqueValues = [...new Set(DataFile.map(item => item.prop))];
}

uniqueValues = DataFile.map(item => item.Cat)
  .filter((value, index, self) => self.indexOf(value) === index); // Successs
giveUniqueValues1(Cat); //Failed Error
giveUniqueValues1('Cat'); //Failed Undefined result for uniqueValues;

uniqueValues = [...new Set(DataFile.map(item => item.Cat))]; //Success
giveUniqueValues2('Cat'); //Fail No Values Returned
giveUniqueValues2(Cat); //Fail Error Out


问:
Cannot find module for a node js app running in a docker compose environment
I am sorry for my very newbie question, but I am having a terrible day figuring out this error, I have an Express app and I am trying to run it in docker compose.
I've used this Dockerfile:

```<code>FROM mhart/alpine-node
RUN mkdir -p /usr/src/app
RUN chmod -R 777 /usr/src/app
WORKDIR /usr/src/app
RUN npm install node-gyp -g
RUN npm install nodemon -g
ENV NODE_ENV development
EXPOSE 3000
</code>```

And this portion of my docker-compose file:

```<code>backend:
    mem_limit: 100m
    build:
      context: .
      dockerfile: dockerfiles/node/Dockerfile
    command: npm start
    depends_on:
      - mongo
      - elasticsearch
    volumes:
      - ./backend/:/usr/src/app
    ports:
      - 3000:3000
    links:
      - "mongo:mongo"
      - "elasticsearch:elasticsearch"
</code>```

When I do docker-compose up, I get this error:

```<code>backend_1        | npm info it worked if it ends with ok
backend_1        | npm info using npm@3.10.10
backend_1        | npm info using node@v6.9.5
backend_1        | npm info lifecycle service-designer@1.0.0~prestart: service-designer@1.0.0
backend_1        | npm info lifecycle service-designer@1.0.0~start: service-designer@1.0.0
backend_1        |
backend_1        | > service-designer@1.0.0 start /usr/src/app
backend_1        | > nodemon index.js
backend_1        |
backend_1        | [nodemon] 1.11.0
backend_1        | [nodemon] to restart at any time, enter `rs`
backend_1        | [nodemon] watching: *.*
backend_1        | [nodemon] starting `node index.js`
backend_1        | module.js:471
backend_1        |     throw err;
backend_1        |     ^
backend_1        |
backend_1        | Error: Cannot find module 'dotenv'
backend_1        |     at Function.Module._resolveFilename (module.js:469:15)
backend_1        |     at Function.Module._load (module.js:417:25)
backend_1        |     at Module.require (module.js:497:17)
backend_1        |     at require (internal/module.js:20:19)
backend_1        |     at Object.<anonymous> (/usr/src/app/index.js:1:63)
backend_1        |     at Module._compile (module.js:570:32)
backend_1        |     at Object.Module._extensions..js (module.js:579:10)
backend_1        |     at Module.load (module.js:487:32)
backend_1        |     at tryModuleLoad (module.js:446:12)
backend_1        |     at Function.Module._load (module.js:438:3)
backend_1        | [nodemon] app crashed - waiting for file changes before starting...
</code>```

If I do ls -al in the backend container, I get a full list of my backend app folder content, but it sounds like node_modules dependencies are not recognized.

答:
It happened to me because I had the file names in upper case.

what is recommended is
rename files to lowercase

delete the dist folder

run again

npm run start:dev
```
<p>to generate a new dist folder.</p>
<p>again run the</p>
<pre class="lang-py prettyprint-override"><code>docker build -t <name> .
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am sorry for my very newbie question, but I am having a terrible day figuring out this error, I have an Express app and I am trying to run it in docker compose.
I've used this Dockerfile:

FROM mhart/alpine-node
RUN mkdir -p /usr/src/app
RUN chmod -R 777 /usr/src/app
WORKDIR /usr/src/app
RUN npm install node-gyp -g
RUN npm install nodemon -g
ENV NODE_ENV development
EXPOSE 3000

And this portion of my docker-compose file:

backend:
    mem_limit: 100m
    build:
      context: .
      dockerfile: dockerfiles/node/Dockerfile
    command: npm start
    depends_on:
      - mongo
      - elasticsearch
    volumes:
      - ./backend/:/usr/src/app
    ports:
      - 3000:3000
    links:
      - "mongo:mongo"
      - "elasticsearch:elasticsearch"

When I do docker-compose up, I get this error:

backend_1        | npm info it worked if it ends with ok
backend_1        | npm info using npm@3.10.10
backend_1        | npm info using node@v6.9.5
backend_1        | npm info lifecycle service-designer@1.0.0~prestart: service-designer@1.0.0
backend_1        | npm info lifecycle service-designer@1.0.0~start: service-designer@1.0.0
backend_1        |
backend_1        | > service-designer@1.0.0 start /usr/src/app
backend_1        | > nodemon index.js
backend_1        |
backend_1        | [nodemon] 1.11.0
backend_1        | [nodemon] to restart at any time, enter `rs`
backend_1        | [nodemon] watching: *.*
backend_1        | [nodemon] starting `node index.js`
backend_1        | module.js:471
backend_1        |     throw err;
backend_1        |     ^
backend_1        |
backend_1        | Error: Cannot find module 'dotenv'
backend_1        |     at Function.Module._resolveFilename (module.js:469:15)
backend_1        |     at Function.Module._load (module.js:417:25)
backend_1        |     at Module.require (module.js:497:17)
backend_1        |     at require (internal/module.js:20:19)
backend_1        |     at Object.<anonymous> (/usr/src/app/index.js:1:63)
backend_1        |     at Module._compile (module.js:570:32)
backend_1        |     at Object.Module._extensions..js (module.js:579:10)
backend_1        |     at Module.load (module.js:487:32)
backend_1        |     at tryModuleLoad (module.js:446:12)
backend_1        |     at Function.Module._load (module.js:438:3)
backend_1        | [nodemon] app crashed - waiting for file changes before starting...

If I do ls -al in the backend container, I get a full list of my backend app folder content, but it sounds like node_modules dependencies are not recognized.

Body:
It happened to me because I had the file names in upper case.

what is recommended is
rename files to lowercase

delete the dist folder

run again

npm run start:dev

to generate a new dist folder.

again run the

docker build -t <name> .


问:
How to read connection string in .NET Core?
I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:

```<code>{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-

 WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
   }
 }
}
</code>```

On ASP.NET I used this:

```<code> var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
</code>```

Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?

答:
The method below will work fine if you want to get a connectionString from appsettings.json into a Model or ViewModel (not Controller). This is for ASP.NET Core 3 and above. Sometimes you may need to get a connectionString into a Model (for SQL queries) rather than dependency injection via the controller so this method below will get your connectionString from appsettings:</p>
```<code>public class NameOfYourModel
{
  static class getConnection
  {
    public static IConfigurationRoot Configuration;
    public static string GetConnectionString()
    {
      var builder = new ConfigurationBuilder()
      .SetBasePath(System.IO.Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json");
       Configuration = builder.Build();
       var connectionString =
    Configuration.GetConnectionString("connectionStringName");

       return connectionString;
     }
    }
    string connStr = getConnection.GetConnectionString().ToString(); //This
   //line now has your connectionString which you can use.

 //Continue the rest of your code here.
}
</code>```

Body:
I want to read just a connection string from a configuration file and for this add a file with the name "appsettings.json" to my project and add this content on it:

{
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-

 WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
    "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
    "Default": "Debug",
    "System": "Information",
    "Microsoft": "Information"
   }
 }
}

On ASP.NET I used this:

 var temp=ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

Now how can I read "DefaultConnection" in C# and store it on a string variable in .NET Core?

Body:
The method below will work fine if you want to get a connectionString from appsettings.json into a Model or ViewModel (not Controller). This is for ASP.NET Core 3 and above. Sometimes you may need to get a connectionString into a Model (for SQL queries) rather than dependency injection via the controller so this method below will get your connectionString from appsettings:

public class NameOfYourModel
{
  static class getConnection
  {
    public static IConfigurationRoot Configuration;
    public static string GetConnectionString()
    {
      var builder = new ConfigurationBuilder()
      .SetBasePath(System.IO.Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json");
       Configuration = builder.Build();
       var connectionString =
    Configuration.GetConnectionString("connectionStringName");

       return connectionString;
     }
    }
    string connStr = getConnection.GetConnectionString().ToString(); //This
   //line now has your connectionString which you can use.

 //Continue the rest of your code here.
}


答:
The following approach:

uses np.lexsort to order the array first by the second column ascending, then by the first column descending

uses np.maximum.accumulate to calculate the accumulated maxima

reverses the sorted order back to the original order to be able to compare

import numpy as np
arr = np.array([[405.95168576, 1033], [406.23572583, 1033], [407.49812423, 1028], [402.66145728, 1029], [404.11080846, 1032], [401.75897118, 1033], [402.29352509, 1029], [402.34504752, 1024], [402.69938672, 1027], [400.55298544, 1029], [401.41432112, 1027], [400.89318038, 1027], [401.07444532, 1029], [400.43212193, 1033], [400.38178995, 1027], [399.89895625, 1025], [399.88394127, 1031], [399.97766298, 1021], [399.68084993, 1027], [399.65810987, 1029], [399.40565484, 1020], [399.34339145, 1023], [399.39613518, 1019], [399.37733697, 1020], [399.38314402, 1020], [399.47479381, 1025], [399.44134998, 1025], [399.43511907, 1020], [399.40346787, 1020]])

# sort on arr[:,1] ascending then on arr[:,0] descending, return the indices
ind_sorted = np.lexsort((-arr[:, 0], arr[:, 1]))
# calculate the accumulated maxima of the sorted list
max_per_level_sorted = np.maximum.accumulate(arr[ind_sorted, 0])
# get the ordering that maps the sorted values back to the originals
reverse_sorted = np.argsort(ind_sorted)
# get the maxima in the order of the original array
max_per_level = max_per_level_sorted[reverse_sorted]
res = arr[:, 0] >= max_per_level
print(res.astype(int))  # res is a boolean array, show it as integers
```
<blockquote>
<p>[0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0]</p>
</blockquote>
<p>If you really want to, you can compress all this together:</p>
<pre class="lang-py prettyprint-override"><code>ind_sorted = np.lexsort((-arr[:, 0], arr[:, 1]))
res = arr[:, 0] >= np.maximum.accumulate(arr[ind_sorted, 0])[np.argsort(ind_sorted)]
print(res.astype(int))
</code>```

Here is a visualization:

import matplotlib.pyplot as plt

plt.scatter(arr[:, 1], arr[:, 0], color='dodgerblue')
plt.scatter(arr[res, 1], arr[res, 0], fc='none', ec='crimson', lw=2, s=100, marker='H')
```

Title: Filtering an np array using values from each row

Body:
I have an array with the shape (29,2):

arr = [[ 405.95168576 1033.        ]
 [ 406.23572583 1033.        ]
 [ 407.49812423 1028.        ]
 [ 402.66145728 1029.        ]
 [ 404.11080846 1032.        ]
 [ 401.75897118 1033.        ]
 [ 402.29352509 1029.        ]
 [ 402.34504752 1024.        ]
 [ 402.69938672 1027.        ]
 [ 400.55298544 1029.        ]
 [ 401.41432112 1027.        ]
 [ 400.89318038 1027.        ]
 [ 401.07444532 1029.        ]
 [ 400.43212193 1033.        ]
 [ 400.38178995 1027.        ]
 [ 399.89895625 1025.        ]
 [ 399.88394127 1031.        ]
 [ 399.97766298 1021.        ]
 [ 399.68084993 1027.        ]
 [ 399.65810987 1029.        ]
 [ 399.40565484 1020.        ]
 [ 399.34339145 1023.        ]
 [ 399.39613518 1019.        ]
 [ 399.37733697 1020.        ]
 [ 399.38314402 1020.        ]
 [ 399.47479381 1025.        ]
 [ 399.44134998 1025.        ]
 [ 399.43511907 1020.        ]
 [ 399.40346787 1020.        ]]

I would like to filter this array to find whether each row contains the maximum value for column arr[:,0], of all rows in which the value of arr[:,1] is equal to or lower than the one contained in that row.

At the moment, I have the following code, which produces the correct result:

import numpy as np

res = np.array([])

for i in range(arr.shape[0]):
    print(np.max(arr[:,0][arr[:,1] <= arr[i][1]]))
    if arr[i][0] >= np.max(arr[:,0][arr[:,1] <= arr[i][1]]):
        res = np.hstack((res, True))
    else:
        res = np.hstack((res, False))

print(res)

Is there a way to perform this operation in pure numpy, i.e. without using the loop?

Body:
The following approach:

uses np.lexsort to order the array first by the second column ascending, then by the first column descending

uses np.maximum.accumulate to calculate the accumulated maxima

reverses the sorted order back to the original order to be able to compare

import numpy as np
arr = np.array([[405.95168576, 1033], [406.23572583, 1033], [407.49812423, 1028], [402.66145728, 1029], [404.11080846, 1032], [401.75897118, 1033], [402.29352509, 1029], [402.34504752, 1024], [402.69938672, 1027], [400.55298544, 1029], [401.41432112, 1027], [400.89318038, 1027], [401.07444532, 1029], [400.43212193, 1033], [400.38178995, 1027], [399.89895625, 1025], [399.88394127, 1031], [399.97766298, 1021], [399.68084993, 1027], [399.65810987, 1029], [399.40565484, 1020], [399.34339145, 1023], [399.39613518, 1019], [399.37733697, 1020], [399.38314402, 1020], [399.47479381, 1025], [399.44134998, 1025], [399.43511907, 1020], [399.40346787, 1020]])

# sort on arr[:,1] ascending then on arr[:,0] descending, return the indices
ind_sorted = np.lexsort((-arr[:, 0], arr[:, 1]))
# calculate the accumulated maxima of the sorted list
max_per_level_sorted = np.maximum.accumulate(arr[ind_sorted, 0])
# get the ordering that maps the sorted values back to the originals
reverse_sorted = np.argsort(ind_sorted)
# get the maxima in the order of the original array
max_per_level = max_per_level_sorted[reverse_sorted]
res = arr[:, 0] >= max_per_level
print(res.astype(int))  # res is a boolean array, show it as integers

[0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0]

If you really want to, you can compress all this together:

ind_sorted = np.lexsort((-arr[:, 0], arr[:, 1]))
res = arr[:, 0] >= np.maximum.accumulate(arr[ind_sorted, 0])[np.argsort(ind_sorted)]
print(res.astype(int))

Here is a visualization:

import matplotlib.pyplot as plt

plt.scatter(arr[:, 1], arr[:, 0], color='dodgerblue')
plt.scatter(arr[res, 1], arr[res, 0], fc='none', ec='crimson', lw=2, s=100, marker='H')


问:
Could not authenticate via cookie Error: Unable to refresh user session. Please log in using the magic link flow to enable session persistence
I'm trying to log in with magic-sdk and am running into this error:

Could not authenticate via cookie Error: Unable to refresh user session. Please log in using the magic link flow to enable session persistence.

答:
Change your test keys to live keys

Magic no longer accepts test keys. So basically you have to use your live keys even when testing.


问:
Snakefile how to mix wildcards and variables
I want to make a rule which for a given number of threads translates files in one directory and format to another directory and format, in parallel.  Certain elements of the path are defined by variables and certain are wildcards. I want it to wildcard on phase and sample and ext but take stage, challenge and language from the Python variable environment.   I want the copy operation to take file to file. I don't want it to get the entire list of files as input.  I'm not using expand here because if I use expand then snakemake will pass the entire list of inputs as {input} and the entire list of outputs as {output} to the function, which is not what I want.  Here is the Snakefile:

```<code>from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

stage = "/media/catskills/interspeech22"
challenge = "openasr21"
language = "farsi"
sample_rate = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         "{stage}/{challenge}_{language}/{phase}/audio/{sample}.{ext}"
     output:
         "{stage}/{challenge}_{language}/{phase}/wav_{sample_rate}/{sample}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

When I run it I get this error:

```<code>$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'stage'
</code>```

Is there a way to do this in snakemake?

UPDATE: I found a partial solution here, which is to use f-strings and double curly quote the patterns.

```<code>from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/audio/{{sample}}.{{ext}}"
     output:
     f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/wav_{{SAMPLE_RATE}}/{{sample}}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

However the wildcard is not matching the subdirectory name.  I'm still getting an error, but it's a little different:

```<code>$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'phase'
</code>```

This leads to here:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.wav" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

However I'm still not done yet:

```<code>$ snakemake -c16
Building DAG of jobs...
WorkflowError:
Target rules may not contain wildcards. Please specify concrete files or a rule without wildcards at the command line, or have a rule without wildcards at the very top of your workflow (e.g. the typical "rule all" which just collects all results you want to generate in the end).
</code>```

I add rule all in an attempt to correct this issue:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

sph_results = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
               for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
        sph_results

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.sph" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

Finally it complains that the files to be constructed don't exist yet, before attempting to call this function which will construct them:

```<code>$ snakemake -c16
Building DAG of jobs...
MissingInputException in line 15 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Missing input files for rule all:
/media/catskills/interspeech22/openasr21_farsi/dev/wav_16000/MATERIAL_OP2-3S-BUILD_46645_20171106_064534_inLine.wav
/media/catskills/interspeech22/openasr21_farsi/eval/wav_16000/MATERIAL_OP2-3S_77793199_outLine.wav
</code>```

where, to fill out the example, the function copy_sph_to_wav is:

```<code>import os
import librosa
import soundfile as sf

def copy_sph_to_wav(src, dst, sr):
    cmd='/home/catskills/is22/sph2pipe_v2.5/sph2pipe'
    if src[-4:]=='.wav':
        audio,sr1=librosa.load(src, sr=sr)
    else:
        os.system(f"{cmd} -f wav {src} {dst}")
        audio,sr1=librosa.load(dst, sr=sr)

    sf.write(dst, audio, sr)
</code>```

UPDATE 2: Which leads us here, where we fix some issues with the sph_to_wav rule generating outputs which do not match our OUTPUTS file:

```<code>from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

OUTPUTS = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
           for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
         expand("{output}", output=OUTPUTS)

rule sph_to_wav:
     input:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/audio/{sample}.{ext}'
     output:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/wav_16000/{sample}.wav'
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)
</code>```

However we still get an error but a much more focused one, which is:

```<code>$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'stage'
</code>```0

There may be a clue here having to do with wildcard_constraints.

UPDATE 3:  This answer says that

Each wildcard in the input section shall have a corresponding wildcard
(with the same name) in the output section. That is how Snakemake
works: when the Snakemake tries to constract the DAG of jobs and finds
that it needs a certain file, it looks at the output section for each
rule and checks if this rule can produce the required file. This is
the way how Snakemake assigns certain values to the wildcard in the
output section. Every wildcard in other sections shall match one of
the wildcards in the output, and that is how the input gets concrete
filenames.

If that is true then I don't think there is a snakemake solution because I am trying to replace the .sph with .wav and I don't want to have to make a .sph.wav file.

答:
Try this:</p>
```<code>rule all:
    input:
        expand("{your_path}.extension", replacements)

rule make_output:
    input: "{input}_{num}.extension"
    output: "{output}_{num}.extension"
    shell:
        copy_sph_to_wav {input} > {output}

</code>```

Body:
I want to make a rule which for a given number of threads translates files in one directory and format to another directory and format, in parallel.  Certain elements of the path are defined by variables and certain are wildcards. I want it to wildcard on phase and sample and ext but take stage, challenge and language from the Python variable environment.   I want the copy operation to take file to file. I don't want it to get the entire list of files as input.  I'm not using expand here because if I use expand then snakemake will pass the entire list of inputs as {input} and the entire list of outputs as {output} to the function, which is not what I want.  Here is the Snakefile:

from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

stage = "/media/catskills/interspeech22"
challenge = "openasr21"
language = "farsi"
sample_rate = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         "{stage}/{challenge}_{language}/{phase}/audio/{sample}.{ext}"
     output:
         "{stage}/{challenge}_{language}/{phase}/wav_{sample_rate}/{sample}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

When I run it I get this error:

$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'stage'

Is there a way to do this in snakemake?

UPDATE: I found a partial solution here, which is to use f-strings and double curly quote the patterns.

from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/audio/{{sample}}.{{ext}}"
     output:
     f"{STAGE}/{CHALLENGE}_{LANGUAGE}/{{phase}}/wav_{{SAMPLE_RATE}}/{{sample}}.wav"
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

However the wildcard is not matching the subdirectory name.  I'm still getting an error, but it's a little different:

$ snakemake -c16
Building DAG of jobs...
WildcardError in line 11 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'phase'

This leads to here:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

# Resample WAV and SPH files to 16000 kHz WAV

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.wav" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

However I'm still not done yet:

$ snakemake -c16
Building DAG of jobs...
WorkflowError:
Target rules may not contain wildcards. Please specify concrete files or a rule without wildcards at the command line, or have a rule without wildcards at the very top of your workflow (e.g. the typical "rule all" which just collects all results you want to generate in the end).

I add rule all in an attempt to correct this issue:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

sph_results = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
               for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
        sph_results

rule sph_to_wav:
     input:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/audio/{sample}.{ext}" )
     output:
         str( Path(f"{STAGE}/{CHALLENGE}_{LANGUAGE}") / "{phase}/wav_{SAMPLE_RATE}/{sample}.sph" )
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

Finally it complains that the files to be constructed don't exist yet, before attempting to call this function which will construct them:

$ snakemake -c16
Building DAG of jobs...
MissingInputException in line 15 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Missing input files for rule all:
/media/catskills/interspeech22/openasr21_farsi/dev/wav_16000/MATERIAL_OP2-3S-BUILD_46645_20171106_064534_inLine.wav
/media/catskills/interspeech22/openasr21_farsi/eval/wav_16000/MATERIAL_OP2-3S_77793199_outLine.wav

where, to fill out the example, the function copy_sph_to_wav is:

import os
import librosa
import soundfile as sf

def copy_sph_to_wav(src, dst, sr):
    cmd='/home/catskills/is22/sph2pipe_v2.5/sph2pipe'
    if src[-4:]=='.wav':
        audio,sr1=librosa.load(src, sr=sr)
    else:
        os.system(f"{cmd} -f wav {src} {dst}")
        audio,sr1=librosa.load(dst, sr=sr)

    sf.write(dst, audio, sr)

UPDATE 2: Which leads us here, where we fix some issues with the sph_to_wav rule generating outputs which do not match our OUTPUTS file:

from pathlib import Path
from glob import glob
from copy_sph_to_wav import copy_sph_to_wav

STAGE = "/media/catskills/interspeech22"
CHALLENGE = "openasr21"
LANGUAGE = "farsi"
SAMPLE_RATE = 16000

OUTPUTS = [x.replace('.sph', '.wav').replace('/audio/', f'/wav_{SAMPLE_RATE}/')
           for x in glob(f"{STAGE}/{CHALLENGE}_{LANGUAGE}/*/audio/*")]

# Resample WAV and SPH files to 16000 kHz WAV

rule all:
     input:
         expand("{output}", output=OUTPUTS)

rule sph_to_wav:
     input:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/audio/{sample}.{ext}'
     output:
         '/media/catskills/interspeech22/openasr21_farsi/{phase}/wav_16000/{sample}.wav'
     run:
         copy_sph_to_wav({input}, {output}, sample_rate)

However we still get an error but a much more focused one, which is:

$ snakemake -c16 -p -n
Building DAG of jobs...
WildcardError in line 19 of /home/catskills/is22/interspeech22/scripts/Snakefile:
Wildcards in input files cannot be determined from output files:
'ext'

There may be a clue here having to do with wildcard_constraints.

UPDATE 3:  This answer says that

Each wildcard in the input section shall have a corresponding wildcard
(with the same name) in the output section. That is how Snakemake
works: when the Snakemake tries to constract the DAG of jobs and finds
that it needs a certain file, it looks at the output section for each
rule and checks if this rule can produce the required file. This is
the way how Snakemake assigns certain values to the wildcard in the
output section. Every wildcard in other sections shall match one of
the wildcards in the output, and that is how the input gets concrete
filenames.

If that is true then I don't think there is a snakemake solution because I am trying to replace the .sph with .wav and I don't want to have to make a .sph.wav file.

Body:
Try this:

rule all:
    input:
        expand("{your_path}.extension", replacements)

rule make_output:
    input: "{input}_{num}.extension"
    output: "{output}_{num}.extension"
    shell:
        copy_sph_to_wav {input} > {output}


问:
How to add condition in ARM Bicep template?
Let’s say, I want to deploy a separate resource only if param isProduction bool
is true.
Is that possible with Bicep?

I could not find this in the documentation.

答:
In addition to the answer already given, not only can the whole resource be deployed based on a condition, but also individual properties of a resource can be changed for a specific environment using conditional ternary operator. The following is an example for Azure Front Door, where only in the production environment the Premium Tier is used:</p>
```<code>resource profile 'Microsoft.Cdn/profiles@2020-09-01' = {
  name: 'azureFrontDoor'
  location: 'global'
  sku: {
    name: isProduction ? 'Premium_AzureFrontDoor' : 'Standard_AzureFrontDoor'
  }
  tags: tags
}
</code>```

Body:
In addition to the answer already given, not only can the whole resource be deployed based on a condition, but also individual properties of a resource can be changed for a specific environment using conditional ternary operator. The following is an example for Azure Front Door, where only in the production environment the Premium Tier is used:

resource profile 'Microsoft.Cdn/profiles@2020-09-01' = {
  name: 'azureFrontDoor'
  location: 'global'
  sku: {
    name: isProduction ? 'Premium_AzureFrontDoor' : 'Standard_AzureFrontDoor'
  }
  tags: tags
}


问:
Partial parsing and recovery of Menhir
There is a very small calculator in Sedlex and Menhir. Now, I would like to make the calculator to be able to parse expressions like 1+. So I modified parser.mly to

```<code>... ...
main:
    expr EOL                { $1 }
;
expr [@recovery (E_int 0)]:
    INT                     { E_int $1 }
  | BOOL                    { E_bool $1 }
... ...
</code>```

But evaluating 1+ still returned an error Fatal error: exception Parser.MenhirBasics.Error.

Could anyone help?

答:
Augmented summary of my comments:

[@recovery ...] is a construct specific to Merlin

As of now (13/02/2022) it is still possible to define your own error recovery by using the special error token like this:

main:
    expr EOL                { $1 }
;
expr [@recovery (E_int 0)]:
    INT                     { E_int $1 }
  | BOOL                    { E_bool $1 }
  | error                   { E_int 0 }
```

From menhir's manual:

If the error token is used to survive an error and continue parsing, then the legacy strategy should be selected.

--strategy strategy.   This switch selects an error-handling strategy, to be used by the code back-end, the table back-end, and the reference interpreter. The available strategies are legacy and simplified.

From OCaml weekly news:

Grammars that make more complex use of the error token, and therefore
need the legacy strategy, cannot be compiled by the new code back-end.
As a workaround, it is possible to switch to the table back-end (using
--table --strategy legacy) or to the ancient code back-end (using
--code-ancient). In the long run, we recommend abandoning the use of
the error token. Support for the error token may be removed
entirely at some point in the future.

This way of doing will most likely not work in a near future but it does for now and it appeared to be the simplest way of doing what OP asked.

Title: Partial parsing and recovery of Menhir

Body:
There is a very small calculator in Sedlex and Menhir. Now, I would like to make the calculator to be able to parse expressions like 1+. So I modified parser.mly to

... ...
main:
    expr EOL                { $1 }
;
expr [@recovery (E_int 0)]:
    INT                     { E_int $1 }
  | BOOL                    { E_bool $1 }
... ...

But evaluating 1+ still returned an error Fatal error: exception Parser.MenhirBasics.Error.

Could anyone help?

Body:
Augmented summary of my comments:

[@recovery ...] is a construct specific to Merlin

As of now (13/02/2022) it is still possible to define your own error recovery by using the special error token like this:

main:
    expr EOL                { $1 }
;
expr [@recovery (E_int 0)]:
    INT                     { E_int $1 }
  | BOOL                    { E_bool $1 }
  | error                   { E_int 0 }

From menhir's manual:

If the error token is used to survive an error and continue parsing, then the legacy strategy should be selected.

--strategy strategy.   This switch selects an error-handling strategy, to be used by the code back-end, the table back-end, and the reference interpreter. The available strategies are legacy and simplified.

From OCaml weekly news:

Grammars that make more complex use of the error token, and therefore
need the legacy strategy, cannot be compiled by the new code back-end.
As a workaround, it is possible to switch to the table back-end (using
--table --strategy legacy) or to the ancient code back-end (using
--code-ancient). In the long run, we recommend abandoning the use of
the error token. Support for the error token may be removed
entirely at some point in the future.

This way of doing will most likely not work in a near future but it does for now and it appeared to be the simplest way of doing what OP asked.


问:
Merge PDF files from post custom fields(ACF) into one PDF file and respond back the created PDF file, Wordpress(AJAX Request)
I am using Advanced Custom Fields plugin(free version) for attaching 3 different pdf files to a single post.

After displaying a list of posts on a template, with a button click I am making an AJAX Request to get the files of all displayed posts.

Since every post has 3 PDF files, I want to merge all these files of all posts to a single PDF file and download that single file.

What I did so far :

AJAX Request on button click:

```<code>    function merklisteDownload() {
        window.event.preventDefault()
        var m = JSON.parse(window.sessionStorage.getItem('merkliste_items')) || []
        var ids = []
        if (m.length > 0) {
            m.forEach(element => {
                ids.push(element.id)
            });
        }
        $.ajax({
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            dataType: "json",
            data: {
                action: 'get_post_files',
                ids: ids
            },
            success: function(response) {
                console.log(response.data)
            },
            error: function(error) {
                console.log(error)
            }
        });
    }
</code>```

And admin-ajax.php code:

```<code>    function get_post_files(){
    $data = [];
    foreach ($_POST['ids'] as $post_id) {
        array_push($data, [
            'id'                        => $post_id,
            'title'                     => get_the_title($post_id),
            'category'                  => get_the_category($post_id)[0]->name,
            'front_image'               => get_field('front_image', $post_id)['sizes']['large'] == true ? get_field('front_image', $post_id)['sizes']['large'] : null,
            'back_image'                => get_field('back_image', $post_id)['sizes']['large'] == true ? get_field('back_image', $post_id)['sizes']['large'] : null,
            'technische_daten'          => get_field('technische_daten', $post_id)['url'], //file
            'lichttechnische_parameter' => get_field('lichttechnische_parameter', $post_id)['url'], //file
            'reach_zertifikat'          => get_field('reach-zertifikat', $post_id)['url'],  //file
        ]);
    }
    wp_send_json_success($data);
    wp_die();
}

add_action('wp_ajax_get_post_files', 'get_post_files');
add_action('wp_ajax_nopriv_get_post_files', 'get_post_files');
</code>```

Everything is working till now, I am able to get the file URLs of each post, but I dont know how to merge these files into one and return the file as AJAX Response, then download that file.

Any help?

Best regards.

答:
Here is an option that may point you in the right direction to merge the files: https://orangeable.com/php/pdf-merge

It would probably look something like this:

```<code>function get_post_files(){
    $data = [];
    foreach ($_POST['ids'] as $post_id) {
        array_push($data, [
            'id'                        => $post_id,
            'title'                     => get_the_title($post_id),
            'category'                  => get_the_category($post_id)[0]->name,
            'front_image'               => get_field('front_image', $post_id)['sizes']['large'] == true ? get_field('front_image', $post_id)['sizes']['large'] : null,
            'back_image'                => get_field('back_image', $post_id)['sizes']['large'] == true ? get_field('back_image', $post_id)['sizes']['large'] : null,
            'technische_daten'          => get_field('technische_daten', $post_id)['url'], //file
            'lichttechnische_parameter' => get_field('lichttechnische_parameter', $post_id)['url'], //file
            'reach_zertifikat'          => get_field('reach-zertifikat', $post_id)['url'],  //file
        ]);
        $temp = array(
            $data['technische_daten'],
            $data['lichttechnische_parameter'],
            $data['reach_zertifikat']
        );
        file_put_contents(getcwd() . "\\pdf\\merged-".$post_id.".pdf", "");
        $command = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=" . getcwd() . "\\pdf\\merged-".$post_id.".pdf "; // needs space at end
        foreach($temp as $file) {
            $command .= getcwd() . "\\pdf\\" . $file . " ";
        }
        $command .= "2&>1";
        $data['merged_file'] = shell_exec($command);
    }
    wp_send_json_success($data);
    wp_die();
}

add_action('wp_ajax_get_post_files', 'get_post_files');
add_action('wp_ajax_nopriv_get_post_files', 'get_post_files');
</code>```

Body:
I am using Advanced Custom Fields plugin(free version) for attaching 3 different pdf files to a single post.

After displaying a list of posts on a template, with a button click I am making an AJAX Request to get the files of all displayed posts.

Since every post has 3 PDF files, I want to merge all these files of all posts to a single PDF file and download that single file.

What I did so far :

AJAX Request on button click:

    function merklisteDownload() {
        window.event.preventDefault()
        var m = JSON.parse(window.sessionStorage.getItem('merkliste_items')) || []
        var ids = []
        if (m.length > 0) {
            m.forEach(element => {
                ids.push(element.id)
            });
        }
        $.ajax({
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            dataType: "json",
            data: {
                action: 'get_post_files',
                ids: ids
            },
            success: function(response) {
                console.log(response.data)
            },
            error: function(error) {
                console.log(error)
            }
        });
    }

And admin-ajax.php code:

    function get_post_files(){
    $data = [];
    foreach ($_POST['ids'] as $post_id) {
        array_push($data, [
            'id'                        => $post_id,
            'title'                     => get_the_title($post_id),
            'category'                  => get_the_category($post_id)[0]->name,
            'front_image'               => get_field('front_image', $post_id)['sizes']['large'] == true ? get_field('front_image', $post_id)['sizes']['large'] : null,
            'back_image'                => get_field('back_image', $post_id)['sizes']['large'] == true ? get_field('back_image', $post_id)['sizes']['large'] : null,
            'technische_daten'          => get_field('technische_daten', $post_id)['url'], //file
            'lichttechnische_parameter' => get_field('lichttechnische_parameter', $post_id)['url'], //file
            'reach_zertifikat'          => get_field('reach-zertifikat', $post_id)['url'],  //file
        ]);
    }
    wp_send_json_success($data);
    wp_die();
}

add_action('wp_ajax_get_post_files', 'get_post_files');
add_action('wp_ajax_nopriv_get_post_files', 'get_post_files');

Everything is working till now, I am able to get the file URLs of each post, but I dont know how to merge these files into one and return the file as AJAX Response, then download that file.

Any help?

Best regards.

Body:
Here is an option that may point you in the right direction to merge the files: https://orangeable.com/php/pdf-merge

It would probably look something like this:

function get_post_files(){
    $data = [];
    foreach ($_POST['ids'] as $post_id) {
        array_push($data, [
            'id'                        => $post_id,
            'title'                     => get_the_title($post_id),
            'category'                  => get_the_category($post_id)[0]->name,
            'front_image'               => get_field('front_image', $post_id)['sizes']['large'] == true ? get_field('front_image', $post_id)['sizes']['large'] : null,
            'back_image'                => get_field('back_image', $post_id)['sizes']['large'] == true ? get_field('back_image', $post_id)['sizes']['large'] : null,
            'technische_daten'          => get_field('technische_daten', $post_id)['url'], //file
            'lichttechnische_parameter' => get_field('lichttechnische_parameter', $post_id)['url'], //file
            'reach_zertifikat'          => get_field('reach-zertifikat', $post_id)['url'],  //file
        ]);
        $temp = array(
            $data['technische_daten'],
            $data['lichttechnische_parameter'],
            $data['reach_zertifikat']
        );
        file_put_contents(getcwd() . "\\pdf\\merged-".$post_id.".pdf", "");
        $command = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=" . getcwd() . "\\pdf\\merged-".$post_id.".pdf "; // needs space at end
        foreach($temp as $file) {
            $command .= getcwd() . "\\pdf\\" . $file . " ";
        }
        $command .= "2&>1";
        $data['merged_file'] = shell_exec($command);
    }
    wp_send_json_success($data);
    wp_die();
}

add_action('wp_ajax_get_post_files', 'get_post_files');
add_action('wp_ajax_nopriv_get_post_files', 'get_post_files');


问:
how to download files via rselenium
I'm trying to download files via Rselium and it has been 4 days without any success. All I want to do is get Rselium to click on the download link and save it to a local file on disk.

I am using Docker on a windows 10 machine.

In this page https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html

I want to download the List of eligible securities

Based on feed back from @Nad pat below, I have now updated my code. I am still not able to download the files to the specified directory!

Updated code

```<code>library(tidyverse)
library(lubridate)
library(XML)
library(readxl)
library(janitor)

library(RSelenium)

fprof <- makeFirefoxProfile(list(

    browser.download.manager.showWhenStarting = FALSE,

    browser.download.dir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),
    # browser.download.dir = "c:/users/joe/downloads",
    # browser.download.useDownloadDir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),

    rowser.helperApps.neverAsk.openFile = "text/csv",

    browser.helperApps.neverAsk.saveToDisk = "text/plain,application/octet-stream,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    # browser.helperApps.neverAsk.saveToDisk="text/csv",

    browser.download.folderList = 2L
                                 )
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = TRUE)
remDr$navigate(link_to_chart)
remDr$screenshot(display = TRUE) #This will take a screenshot and display it in the RStudio viewer

#download file - 2 options
remDr$findElement(using ="class", "anchor-xls")$clickElement()
remDr$findElement(using ="xpath", '//*[@id="content"]/section/div[2]/table/tbody/tr[1]/th/a')$clickElement()

remDr$closeWindow()
</code>```

Old Code

This is the best code I could come-up with:

```<code>library(tidyverse)
library(lubridate)

library(XML)
library(readxl)
library(janitor)
library(platus)

library(RSelenium)

firefor_exemptions <- c("application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "application/vnd.openxmlformats-officedocument.presentationml.slide",
  "application/vnd.openxmlformats-officedocument.presentationml.slideshw",
  "application/vnd.openxmlformats-officedocument.presentationml.template",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
  "application/vnd.openxmformats-officedocument.wordprocessingml.document",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
  "application/x-msbinder",
  "application/vnd.ms-officetheme",
  "application/onenote",
  "audio/vnd.ms-playready.media.pya",
  "vdeo/vnd.ms-playready.media.pyv",
  "application/vnd.ms-powerpoint",
  "application/vnd.ms-powerpoint.addin.macroenabled.12",
  "application/vnd.ms-powerpoint.slide.macroenabled.12",
  "application/vnd.ms-powerpoint.presentation.macroenabled.12",
  "appliation/vnd.ms-powerpoint.slideshow.macroenabled.12",
  "application/vnd.ms-project",
  "application/x-mspublisher",
  "application/x-msschedule",
  "application/x-silverlight-app"
)

fprof <- makeFirefoxProfile(list(browser.helperApps.neverAsk.saveToDisk = firefor_exemptions,
                                 browser.download.dir = str_replace_all("c:/users/john_doe/downloads", "/", "\\\\\\\\"))
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = FALSE)
remDr$navigate(link_to_chart)

#I'm not sure what I should be selecting
remDr$findElement("class", "js-no-cache anchor-to-file anchor-xls")$clickElement()

remDr$findElement("link", "List of eligible securities")$clickElement()

remDr$closeWindow()
</code>```

Any ideas on how to make this work?

答:
Why use Selenium? You can download the file with download.file if you find out its url:

```<code>url <- "https://www.rba.gov.au/mkt-operations/xls/eligible-securities.xls"
url <- paste0(url, "?v=", gsub(" |:", "-", as.character(Sys.time())))
download.file(url, "securities.xls")
</code>```

This saves the file to disk.

Title: how to download files via rselenium

Body:
I'm trying to download files via Rselium and it has been 4 days without any success. All I want to do is get Rselium to click on the download link and save it to a local file on disk.

I am using Docker on a windows 10 machine.

In this page https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html

I want to download the List of eligible securities

Based on feed back from @Nad pat below, I have now updated my code. I am still not able to download the files to the specified directory!

Updated code

library(tidyverse)
library(lubridate)
library(XML)
library(readxl)
library(janitor)

library(RSelenium)

fprof <- makeFirefoxProfile(list(

    browser.download.manager.showWhenStarting = FALSE,

    browser.download.dir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),
    # browser.download.dir = "c:/users/joe/downloads",
    # browser.download.useDownloadDir = str_replace_all("c:/users/joe/downloads/", "/", "\\\\\\\\"),

    rowser.helperApps.neverAsk.openFile = "text/csv",

    browser.helperApps.neverAsk.saveToDisk = "text/plain,application/octet-stream,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    # browser.helperApps.neverAsk.saveToDisk="text/csv",

    browser.download.folderList = 2L
                                 )
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = TRUE)
remDr$navigate(link_to_chart)
remDr$screenshot(display = TRUE) #This will take a screenshot and display it in the RStudio viewer

#download file - 2 options
remDr$findElement(using ="class", "anchor-xls")$clickElement()
remDr$findElement(using ="xpath", '//*[@id="content"]/section/div[2]/table/tbody/tr[1]/th/a')$clickElement()

remDr$closeWindow()

Old Code

This is the best code I could come-up with:

library(tidyverse)
library(lubridate)

library(XML)
library(readxl)
library(janitor)
library(platus)

library(RSelenium)

firefor_exemptions <- c("application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "application/vnd.openxmlformats-officedocument.presentationml.slide",
  "application/vnd.openxmlformats-officedocument.presentationml.slideshw",
  "application/vnd.openxmlformats-officedocument.presentationml.template",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
  "application/vnd.openxmformats-officedocument.wordprocessingml.document",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
  "application/x-msbinder",
  "application/vnd.ms-officetheme",
  "application/onenote",
  "audio/vnd.ms-playready.media.pya",
  "vdeo/vnd.ms-playready.media.pyv",
  "application/vnd.ms-powerpoint",
  "application/vnd.ms-powerpoint.addin.macroenabled.12",
  "application/vnd.ms-powerpoint.slide.macroenabled.12",
  "application/vnd.ms-powerpoint.presentation.macroenabled.12",
  "appliation/vnd.ms-powerpoint.slideshow.macroenabled.12",
  "application/vnd.ms-project",
  "application/x-mspublisher",
  "application/x-msschedule",
  "application/x-silverlight-app"
)

fprof <- makeFirefoxProfile(list(browser.helperApps.neverAsk.saveToDisk = firefor_exemptions,
                                 browser.download.dir = str_replace_all("c:/users/john_doe/downloads", "/", "\\\\\\\\"))
)

link_to_chart <- "https://www.rba.gov.au/mkt-operations/resources/tech-notes/eligible-securities.html"

remDr <- remoteDriver(remoteServerAddr = "localhost",
                      port = 4445L, browserName = "firefox",
                      extraCapabilities = fprof)

remDr$open(silent = FALSE)
remDr$navigate(link_to_chart)

#I'm not sure what I should be selecting
remDr$findElement("class", "js-no-cache anchor-to-file anchor-xls")$clickElement()

remDr$findElement("link", "List of eligible securities")$clickElement()

remDr$closeWindow()

Any ideas on how to make this work?

Body:
Why use Selenium? You can download the file with download.file if you find out its url:

url <- "https://www.rba.gov.au/mkt-operations/xls/eligible-securities.xls"
url <- paste0(url, "?v=", gsub(" |:", "-", as.character(Sys.time())))
download.file(url, "securities.xls")

This saves the file to disk.


问:
Stop job from running between a period of time
I searched about that, but didn't find any resources. I have a java batch running every midnight and it takes 20minutes to finish it's execution, and I have a CI/CD pipeline using github actions, and I want to stop github actions job from running if someone tries to push a commit in this date interval: [midnight, midnight + 20min], so it will not brake the batch. Is this possible in github actions ?</p>

答:
Yes - actually nowadays it's much easier than before, as GitHub added native support for concurrency. It's even better than locking a  fixed time-window - it's based on workflow actual execution time.

Here are the docs:
https://docs.github.com/en/actions/using-jobs/using-concurrency

Basically you just add this to top level of your workflow:

```<code>concurrency:
  group: ${{ github.workflow }}
</code>```

And it will queue up all workflows that will appear and execute them one after another.

If you would like to stop every other workflows from running not just the one, you can do:

```<code>concurrency: repository_lock
</code>```

This will make all workflows queueing up - but that maybe a bit too much I think - it depends on what you need - but it's really flexbile solution.

The only alternative that was available before and it's still usable is cancelling other workflow runs if new one appears:
https://github.com/styfle/cancel-workflow-action/

But I think it's not what you need.

Body:
Yes - actually nowadays it's much easier than before, as GitHub added native support for concurrency. It's even better than locking a  fixed time-window - it's based on workflow actual execution time.

Here are the docs:
https://docs.github.com/en/actions/using-jobs/using-concurrency

Basically you just add this to top level of your workflow:

concurrency:
  group: ${{ github.workflow }}

And it will queue up all workflows that will appear and execute them one after another.

If you would like to stop every other workflows from running not just the one, you can do:

concurrency: repository_lock

This will make all workflows queueing up - but that maybe a bit too much I think - it depends on what you need - but it's really flexbile solution.

The only alternative that was available before and it's still usable is cancelling other workflow runs if new one appears:
https://github.com/styfle/cancel-workflow-action/

But I think it's not what you need.


问:
Passing additional parameters while creating s3 bucket
Is there a way to pass additional parameters to the AWS API when creating aws_s3_bucket resource, namengly CreateBucketConfiguration/LocationConstraint ?

答:
You can't do this directly, but you can obtain the same effect through provider alias set to a given region:</p>
```<code>provider "aws" {
   alias  = "west"
   region = "us-west-2"
}

resource "aws_s3_bucket" "mybucket" {
   provider = aws.west
   #...
}
</code>```

Body:
You can't do this directly, but you can obtain the same effect through provider alias set to a given region:

provider "aws" {
   alias  = "west"
   region = "us-west-2"
}

resource "aws_s3_bucket" "mybucket" {
   provider = aws.west
   #...
}


问:
how to make a TextView strech across the screen, filling it up?
```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/pleaseChooseText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:textAlignment="center"
        android:text="Please Choose your Mood"
        android:textColor="@color/black"
        android:textStyle="bold"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I want to make this text fill up screen width but not the screen height, would this work here or programatically, how do I do that?

答:
I'm pretty sure what you're looking for is the AutoResizing Text
Based on my previous experiences, it won't really work until you have the layout_width declared to match_parent and the layout_height declared to a hardcoded number.
For example:

```<code>    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        />
</code>```

There are two many missing attributes missing, but the base thing is the auto-resizing text attributes.

Body:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/pleaseChooseText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:textAlignment="center"
        android:text="Please Choose your Mood"
        android:textColor="@color/black"
        android:textStyle="bold"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

I want to make this text fill up screen width but not the screen height, would this work here or programatically, how do I do that?

Body:
I'm pretty sure what you're looking for is the AutoResizing Text
Based on my previous experiences, it won't really work until you have the layout_width declared to match_parent and the layout_height declared to a hardcoded number.
For example:

    <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="12sp"
        app:autoSizeStepGranularity="2sp"
        app:autoSizeTextType="uniform"
        />

There are two many missing attributes missing, but the base thing is the auto-resizing text attributes.


问:
In React, how can I make a single api call, set the result to a state variable, and display it?
I am programming a react application where I need to make a single async api call, save the result to a state variable and display the result. I am using an axios instance where the response of the api call is a nested object. For example:

```<code>{
    kanji:
        {character: "", stroke:""},
    quote: "string"
}
</code>```

So far I have the following code where I am able to console.log the homeData object successfully. However I get the error:  'TypeError: homeData is undefined'.

```<code>const Home = () =>{

    const [homeData, setHomeData] = useState({})

    const getHomeData = async()=>{
        instance.get("/data")
        .then(res =>{
            setHomeData(res.data)
        })
        .catch(error =>{
            console.log(error)
        })
    }

    useEffect(()=>{
        getHomeData()
    }, [])

    console.log(homeData)

    return(
        <>
          <p>{homeData}<p>
        </>
    )
}

</code>```

This seems like a promise issue but I am not sure how to fix it. Thank you for your help in advance.

答:
This is not a promise issue, it has to due with the order in which the lifecycle methods run. useEffect runs after the component renders. This means when the component first renders, the homeData is an empty object. homeData will be present in the second render. The following code first checks if homeData exists, then if it exists, it displays the kanji character. Note also, you cant just display a raw object into the dom so you will have to access the homeData by property for it to display</p>
```<code>const Home = () =>{

    const [homeData, setHomeData] = useState({})

    const getHomeData = async()=>{
        instance.get("/data")
        .then(res =>{
            setHomeData(res.data)
        })
        .catch(error =>{
            console.log(error)
        })
    }

    useEffect(()=>{
        getHomeData()
    }, [])

    console.log(homeData)

    return(
        <>
          <p>{homeData && homeData.kanji.character}<p>
        </>
    )
}
</code>```

Body:
I am programming a react application where I need to make a single async api call, save the result to a state variable and display the result. I am using an axios instance where the response of the api call is a nested object. For example:

{
    kanji:
        {character: "", stroke:""},
    quote: "string"
}

So far I have the following code where I am able to console.log the homeData object successfully. However I get the error:  'TypeError: homeData is undefined'.

const Home = () =>{

    const [homeData, setHomeData] = useState({})

    const getHomeData = async()=>{
        instance.get("/data")
        .then(res =>{
            setHomeData(res.data)
        })
        .catch(error =>{
            console.log(error)
        })
    }

    useEffect(()=>{
        getHomeData()
    }, [])

    console.log(homeData)

    return(
        <>

{homeData}

        </>
    )
}

This seems like a promise issue but I am not sure how to fix it. Thank you for your help in advance.

Body:
This is not a promise issue, it has to due with the order in which the lifecycle methods run. useEffect runs after the component renders. This means when the component first renders, the homeData is an empty object. homeData will be present in the second render. The following code first checks if homeData exists, then if it exists, it displays the kanji character. Note also, you cant just display a raw object into the dom so you will have to access the homeData by property for it to display

const Home = () =>{

    const [homeData, setHomeData] = useState({})

    const getHomeData = async()=>{
        instance.get("/data")
        .then(res =>{
            setHomeData(res.data)
        })
        .catch(error =>{
            console.log(error)
        })
    }

    useEffect(()=>{
        getHomeData()
    }, [])

    console.log(homeData)

    return(
        <>
          <p>{homeData && homeData.kanji.character}<p>
        </>
    )
}


问:
Rails has_many :through with conditions and building associations
I'm having problems building an association that is a has_many :through with conditions.  I have this model:

```<code>class Contact < AR
  has_many :group_contacts
  has_many :groups, :through => :group_contacts, :conditions => {:groups => {:published => true}}
end
</code>```

problem happens when I try to instantiate a group from a contact.  With the above syntax, I get an error:

```<code>contact.groups.build
=> ActiveRecord::UnknownAttributeError: unknown attribute: groups
</code>```

But when I use the following syntax it works:

```<code>has_many :groups, :through => :group_contacts, :conditions => ['groups.published = ?', true]

contact.groups.build
=> #<Group id: nil, name: nil, description: nil, created_at: nil, updated_at: nil, published: true>
</code>```

I see a reference to the exact problem in this question.  It is said a ticket would be filed for this bug (back in pre- rails 3 versions).  I can't find anything however on rails 3.0.x.

I'm using 3.0.8.  Has anyone else found this issue?

Further Notes:

I've also found that when I'm building groups, it actually ignores my conditions on the association when building.  The only reason my above build had published => true is because it's the default in the db.

This seems like a regression, can anyone else verify this?

答:
```<code>has_many :groups, :through => :group_contacts, :conditions => {:published => true}
</code>```

or

```<code>has_many :groups, :through => :group_contacts, :conditions => {"groups.published" => true}
</code>```

Body:
I'm having problems building an association that is a has_many :through with conditions.  I have this model:

class Contact < AR
  has_many :group_contacts
  has_many :groups, :through => :group_contacts, :conditions => {:groups => {:published => true}}
end

problem happens when I try to instantiate a group from a contact.  With the above syntax, I get an error:

contact.groups.build
=> ActiveRecord::UnknownAttributeError: unknown attribute: groups

But when I use the following syntax it works:

has_many :groups, :through => :group_contacts, :conditions => ['groups.published = ?', true]

contact.groups.build
=> #<Group id: nil, name: nil, description: nil, created_at: nil, updated_at: nil, published: true>

I see a reference to the exact problem in this question.  It is said a ticket would be filed for this bug (back in pre- rails 3 versions).  I can't find anything however on rails 3.0.x.

I'm using 3.0.8.  Has anyone else found this issue?

Further Notes:

I've also found that when I'm building groups, it actually ignores my conditions on the association when building.  The only reason my above build had published => true is because it's the default in the db.

This seems like a regression, can anyone else verify this?

Body:
has_many :groups, :through => :group_contacts, :conditions => {:published => true}

or

has_many :groups, :through => :group_contacts, :conditions => {"groups.published" => true}


问:
Either round or truncate pandas column values to 2 decimals, based on floor/ceil conditions
I have a data frame that I need to convert specifically to two decimal place resolution based on the following logic:

if x (in terms of the value with more than two decimals places) > math.floor(x) + 0.5

...then round this value to two decimals.

if x (in terms of the value with more than two decimals places) < math.ceil(x) - 0.5

...then truncate this value to two decimals.

The main hang-up I am having is just actually seeing these newly rounded/truncated values replace the originals in the data frame.

Sample dataframe:

```<code>import math
import pandas as pd

test_df = pd.DataFrame({'weights': ['25.2524%', '25.7578%', '35.5012%', '13.5000%',
    "50.8782%", "10.2830%", "5.5050%", "30.5555%", "20.7550%"]})

# .. which creates:

   | weights |
|0 | 25.2524%|
|1 | 25.7578%|
|2 | 35.5012%|
|3 | 13.5000%|
|4 | 50.8782%|
|5 | 10.2830%|
|6 |  5.5050%|
|7 | 30.5555%|
|8 | 20.7550%|
</code>```

Define truncate function, and also the function that will configure decimal resolution:

```<code>def truncate_decimals(target_allocation, two_decimal_places) -> float:
    decimal_exponent = 10.0 ** two_decimal_places
    return math.trunc(decimal_exponent * target_allocation) / decimal_exponent

def decimals(df):
    df["weights"] = df["weights"].str.rstrip("%").astype("float")
    decimal_precision = 2
    for x in df["weights"]:
        if x > math.floor(x) + 0.5:
            x = round(x, decimal_precision)
            print("This value is being rounded", x)
            df.loc[(df.weights == x), ('weights')] = x
        elif x < math.ceil(x) - 0.5:
            y = truncate_decimals(x, decimal_precision)
            print("This value is being truncated", y)
            df.loc[(df.weights == x), ('weights')] = y
        else:
            pass
            print("This value does not meet one of the above conditions", round(x, decimal_precision))

    return df

decimals(test_df)
</code>```

Expected output:

```<code>This value is being truncated 25.25
This value is being rounded 25.76
This value is being rounded 35.5
This value does not meet one of the above conditions 13.5
This value is being rounded 50.88
This value is being truncated 10.28
This value is being rounded 5.5
This value is being rounded 30.56
This value is being rounded 20.75

   | weights|
|0 | 25.25  |
|1 | 25.76  |
|2 | 35.5   |
|3 | 13.5   |
|4 | 50.88  |
|5 | 10.28  |
|6 |  5.5   |
|7 | 30.56  |
|8 | 20.75  |
</code>```

Current output:

```<code>The current value is being truncated 25.25

   | weights |
|0 | 25.2524%|
|1 | 25.7578%|
|2 | 35.5012%|
|3 | 13.5000%|
|4 | 50.8782%|
|5 | 10.2830%|
|6 |  5.5050%|
|7 | 30.5555%|
|8 | 20.7550%|
</code>```

答:
Another approach could be to define a function that applies the above rule for a generic number and then apply it to each weight in the column.

Something like this

```<code>import math
import pandas as pd

test_df = pd.DataFrame({'weights': ['25.2524%', '25.7578%', '35.5012%', '13.5000%',
    "50.8782%", "10.2830%", "5.5050%", "30.5555%", "20.7550%"]})

def truncate_decimals(target_allocation, two_decimal_places) -> float:
    decimal_exponent = 10.0 ** two_decimal_places
    return math.trunc(decimal_exponent * target_allocation) / decimal_exponent

def rule(number, decimal_precision=2):
    number = float(number.rstrip("%"))

    if number > math.floor(number) + 0.5:
        number = round(number, decimal_precision)
        print("This value is being rounded", number)

    elif number < math.ceil(number) - 0.5:
        number = truncate_decimals(number, decimal_precision)
        print("This value is being truncated", number)

    else:
        print("This value does not meet one of the above conditions", round(number, decimal_precision))

    return number

test_df['rounded'] = test_df.weights.apply(rule)
</code>```

Body:
I have a data frame that I need to convert specifically to two decimal place resolution based on the following logic:

if x (in terms of the value with more than two decimals places) > math.floor(x) + 0.5

...then round this value to two decimals.

if x (in terms of the value with more than two decimals places) < math.ceil(x) - 0.5

...then truncate this value to two decimals.

The main hang-up I am having is just actually seeing these newly rounded/truncated values replace the originals in the data frame.

Sample dataframe:

import math
import pandas as pd

test_df = pd.DataFrame({'weights': ['25.2524%', '25.7578%', '35.5012%', '13.5000%',
    "50.8782%", "10.2830%", "5.5050%", "30.5555%", "20.7550%"]})

# .. which creates:

   | weights |
|0 | 25.2524%|
|1 | 25.7578%|
|2 | 35.5012%|
|3 | 13.5000%|
|4 | 50.8782%|
|5 | 10.2830%|
|6 |  5.5050%|
|7 | 30.5555%|
|8 | 20.7550%|

Define truncate function, and also the function that will configure decimal resolution:

def truncate_decimals(target_allocation, two_decimal_places) -> float:
    decimal_exponent = 10.0 ** two_decimal_places
    return math.trunc(decimal_exponent * target_allocation) / decimal_exponent

def decimals(df):
    df["weights"] = df["weights"].str.rstrip("%").astype("float")
    decimal_precision = 2
    for x in df["weights"]:
        if x > math.floor(x) + 0.5:
            x = round(x, decimal_precision)
            print("This value is being rounded", x)
            df.loc[(df.weights == x), ('weights')] = x
        elif x < math.ceil(x) - 0.5:
            y = truncate_decimals(x, decimal_precision)
            print("This value is being truncated", y)
            df.loc[(df.weights == x), ('weights')] = y
        else:
            pass
            print("This value does not meet one of the above conditions", round(x, decimal_precision))

    return df

decimals(test_df)

Expected output:

This value is being truncated 25.25
This value is being rounded 25.76
This value is being rounded 35.5
This value does not meet one of the above conditions 13.5
This value is being rounded 50.88
This value is being truncated 10.28
This value is being rounded 5.5
This value is being rounded 30.56
This value is being rounded 20.75

   | weights|
|0 | 25.25  |
|1 | 25.76  |
|2 | 35.5   |
|3 | 13.5   |
|4 | 50.88  |
|5 | 10.28  |
|6 |  5.5   |
|7 | 30.56  |
|8 | 20.75  |

Current output:

The current value is being truncated 25.25

   | weights |
|0 | 25.2524%|
|1 | 25.7578%|
|2 | 35.5012%|
|3 | 13.5000%|
|4 | 50.8782%|
|5 | 10.2830%|
|6 |  5.5050%|
|7 | 30.5555%|
|8 | 20.7550%|

Body:
Another approach could be to define a function that applies the above rule for a generic number and then apply it to each weight in the column.

Something like this

import math
import pandas as pd

test_df = pd.DataFrame({'weights': ['25.2524%', '25.7578%', '35.5012%', '13.5000%',
    "50.8782%", "10.2830%", "5.5050%", "30.5555%", "20.7550%"]})

def truncate_decimals(target_allocation, two_decimal_places) -> float:
    decimal_exponent = 10.0 ** two_decimal_places
    return math.trunc(decimal_exponent * target_allocation) / decimal_exponent

def rule(number, decimal_precision=2):
    number = float(number.rstrip("%"))

    if number > math.floor(number) + 0.5:
        number = round(number, decimal_precision)
        print("This value is being rounded", number)

    elif number < math.ceil(number) - 0.5:
        number = truncate_decimals(number, decimal_precision)
        print("This value is being truncated", number)

    else:
        print("This value does not meet one of the above conditions", round(number, decimal_precision))

    return number

test_df['rounded'] = test_df.weights.apply(rule)


问:
beautifulsoup get last tag from snippet, if tag exists
Here's html snippet 1:

```<code><td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a> <span style="color:#666;font-size:10px;">B</span>  <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
</code>```

Here's html snippet 2:

```<code><td class="firstleft lineupopt-name" style=""><a href="/link/link_url2?id=221" title="Hillary Clinton" target="_blank">Clinton, Hillary</a>  <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
</code>```

Here's my relevant code:

```<code>all = cols[1].find_all('span')
for ele in all:
    if (ele is not None):
        ttt = cols[1].span.text
    else:
        ttt = 'none'
</code>```

Issue: my code works in both instances, but for html snippet 2, it grabs content from the first span tag. In both instances, if the tag exists, I'd like to grab content from only the last span tag. How can this be done?

答: I test it in conda env with bs4 v4.9.1, and now nth-last-of-type(1) is OK.

Body:
Here's html snippet 1:

Trump, Donald B  TTT

Here's html snippet 2:

Clinton, Hillary  TTT

Here's my relevant code:

all = cols[1].find_all('span')
for ele in all:
    if (ele is not None):
        ttt = cols[1].span.text
    else:
        ttt = 'none'

Issue: my code works in both instances, but for html snippet 2, it grabs content from the first span tag. In both instances, if the tag exists, I'd like to grab content from only the last span tag. How can this be done?


问:
Align shapes flush/stacked/touching
I'm trying to get a selection of shapes in order from right to left. I found a routine by John Wilson on vbaexpress on which I based my code.

The sorting works perfectly when I select item by item by clicking on the shapes but it doesn't respect the "visible order" of shapes if I select them by "lassoing" with my mouse.

In case of dragging my mouse over the shapes to select them, the routine should respect the visible order of shapes.

Thanks in advance.

```<code>  Sub AlignFlush()
  Dim oshpR As ShapeRange
  Dim oshp As Shape
  Dim L As Long
  Dim rayPOS() As Single

  Set oshpR = ActiveWindow.Selection.ShapeRange

  ReDim rayPOS(1 To oshpR.Count)
  'add to array
  For L = 1 To oshpR.Count
     rayPOS(L) = oshpR(L).Left
  Next L
  'sort
  Call sortray(rayPOS)

  'apply
  For L = 1 To oshpR.Count
      If L = 1 Then
          Set oshp = Windows(1).Selection.ShapeRange(1)
          PosTop = oshp.Top
          PosNext = oshp.Left + oshp.Width
      Else
          Set oshp = Windows(1).Selection.ShapeRange(L)
          oshp.Top = PosTop
          oshp.Left = PosNext
          PosNext = oshp.Left + oshp.Width
      End If
  Next L
  End Sub

   Sub sortray(ArrayIn As Variant)
  Dim b_Cont As Boolean
  Dim lngCount As Long
  Dim vSwap As Long
  Do
     b_Cont = False
     For lngCount = LBound(ArrayIn) To UBound(ArrayIn) - 1
        If ArrayIn(lngCount) > ArrayIn(lngCount + 1) Then
           vSwap = ArrayIn(lngCount)
           ArrayIn(lngCount) = ArrayIn(lngCount + 1)
           ArrayIn(lngCount + 1) = vSwap
           b_Cont = True
        End If
     Next lngCount
  Loop Until Not b_Cont
</code>```

End Sub

答:
Some comments on your existing code:

Array counts always start at 0 unless you use the Option Base statement to set it to a different number.

When you use ReDim, most of the time, you want to use the Preserve keyword, or the ReDim obliterates the existing array contents. But in this case, we know the array size ahead of time, so Preserve is not necessary.

You call sortray, but didn't include it in your listing. I've added a sorting routine.

But then you make no use of the sorted array in the section where you position the shapes.

Working macro (based on your description of what you mean by "visible order" being the left-to-right sequence):

Since you use the left position of the leftmost shape to apply to the others, here's a simpler way to do that:

```<code>Sub AlignFlushLeftWithLeftmostShape()
    Dim ShpCount As Long
    Dim oshpR As ShapeRange
    Dim L As Long
    Dim rayPOS() As Single

    Set oshpR = ActiveWindow.Selection.ShapeRange

    ShpCount = oshpR.Count

    ReDim rayPOS(ShpCount - 1)

    For L = 0 To ShpCount - 1
       rayPOS(L) = oshpR(L + 1).Left
    Next L

    Call BubbleSort(rayPOS)

    For x = 1 To ShpCount
        oshpR(x).Left = rayPOS(0)
    Next x
End Sub

Sub BubbleSort(arr)
    Dim lTemp As Long
    Dim i As Long
    Dim j As Long
    Dim lngMin As Long
    Dim lngMax As Long
    lngMin = LBound(arr)
    lngMax = UBound(arr)
    For i = lngMin To lngMax - 1
        For j = i + 1 To lngMax
            If arr(i) > arr(j) Then
                lTemp = arr(i)
                arr(i) = arr(j)
                arr(j) = lTemp
            End If
        Next j
    Next i
End Sub

</code>```

Title: Align shapes flush/stacked/touching

Body:
I'm trying to get a selection of shapes in order from right to left. I found a routine by John Wilson on vbaexpress on which I based my code.

The sorting works perfectly when I select item by item by clicking on the shapes but it doesn't respect the "visible order" of shapes if I select them by "lassoing" with my mouse.

In case of dragging my mouse over the shapes to select them, the routine should respect the visible order of shapes.

Thanks in advance.

  Sub AlignFlush()
  Dim oshpR As ShapeRange
  Dim oshp As Shape
  Dim L As Long
  Dim rayPOS() As Single

  Set oshpR = ActiveWindow.Selection.ShapeRange

  ReDim rayPOS(1 To oshpR.Count)
  'add to array
  For L = 1 To oshpR.Count
     rayPOS(L) = oshpR(L).Left
  Next L
  'sort
  Call sortray(rayPOS)

  'apply
  For L = 1 To oshpR.Count
      If L = 1 Then
          Set oshp = Windows(1).Selection.ShapeRange(1)
          PosTop = oshp.Top
          PosNext = oshp.Left + oshp.Width
      Else
          Set oshp = Windows(1).Selection.ShapeRange(L)
          oshp.Top = PosTop
          oshp.Left = PosNext
          PosNext = oshp.Left + oshp.Width
      End If
  Next L
  End Sub

   Sub sortray(ArrayIn As Variant)
  Dim b_Cont As Boolean
  Dim lngCount As Long
  Dim vSwap As Long
  Do
     b_Cont = False
     For lngCount = LBound(ArrayIn) To UBound(ArrayIn) - 1
        If ArrayIn(lngCount) > ArrayIn(lngCount + 1) Then
           vSwap = ArrayIn(lngCount)
           ArrayIn(lngCount) = ArrayIn(lngCount + 1)
           ArrayIn(lngCount + 1) = vSwap
           b_Cont = True
        End If
     Next lngCount
  Loop Until Not b_Cont

End Sub

Body:
Some comments on your existing code:

Array counts always start at 0 unless you use the Option Base statement to set it to a different number.

When you use ReDim, most of the time, you want to use the Preserve keyword, or the ReDim obliterates the existing array contents. But in this case, we know the array size ahead of time, so Preserve is not necessary.

You call sortray, but didn't include it in your listing. I've added a sorting routine.

But then you make no use of the sorted array in the section where you position the shapes.

Working macro (based on your description of what you mean by "visible order" being the left-to-right sequence):

Since you use the left position of the leftmost shape to apply to the others, here's a simpler way to do that:

Sub AlignFlushLeftWithLeftmostShape()
    Dim ShpCount As Long
    Dim oshpR As ShapeRange
    Dim L As Long
    Dim rayPOS() As Single

    Set oshpR = ActiveWindow.Selection.ShapeRange

    ShpCount = oshpR.Count

    ReDim rayPOS(ShpCount - 1)

    For L = 0 To ShpCount - 1
       rayPOS(L) = oshpR(L + 1).Left
    Next L

    Call BubbleSort(rayPOS)

    For x = 1 To ShpCount
        oshpR(x).Left = rayPOS(0)
    Next x
End Sub

Sub BubbleSort(arr)
    Dim lTemp As Long
    Dim i As Long
    Dim j As Long
    Dim lngMin As Long
    Dim lngMax As Long
    lngMin = LBound(arr)
    lngMax = UBound(arr)
    For i = lngMin To lngMax - 1
        For j = i + 1 To lngMax
            If arr(i) > arr(j) Then
                lTemp = arr(i)
                arr(i) = arr(j)
                arr(j) = lTemp
            End If
        Next j
    Next i
End Sub


问:
Spring Boot REST WebService + JPA : pageable and filter
I'm fairly new to these technos and I need a pitch to understand a good way to do things.
I've got an Employee entity, and I want to list them by making a GET query to an endpoint.I have to return a Page of Employees, after having applied filters on field(s). Currently, the Pageable on the GET query works, but not my filter.

Here is my REST endpoint :

```<code>@RequestMapping(value = "/employees",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(readOnly = true)
public ResponseEntity<List<EmployeeDTO>> getAllEmployees(Pageable pageable, String filters) throws URISyntaxException, JSONException {

        JSONObject sfilters = null;
        try {
            sfilters = new JSONObject(filters.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // I wish this on could works, but still have to update it if we add fields to our Employee entity
        Page<Employee> page = employeeRepository.findAllByCompanyIdAndFirstnameLikeAndLastnameLike(
            userService.getUserWithAuthorities().getCompany().getId(),
            sfilters.get("firstname").toString(),
            sfilters.get("lastname").toString(),
            pageable);

        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/employees");
        ResponseEntity<List<EmployeeDTO>> result = new ResponseEntity<>(page.getContent().stream()
            .map(employeeMapper::employeeToEmployeeDTO)
            .collect(Collectors.toCollection(LinkedList::new)), headers, HttpStatus.OK);

        return result;
}
</code>```

NB : I have to filter on more fields than that but I want to keep example as clear as possible.

My repository method :

```<code>Page<Employee> findAllByCompanyIdAndFirstnameLikeAndLastnameLike(Long idCompany, String firstname, String lastname, Pageable pageable);
</code>```

Client side, it works well, I send good params for pageable and for my filter to be converted into JSONObject. But now I need suggestions on how can I properly generate dynamics filters on my query. My JPA repository method doesnt work.

I tried to use predicates, but it does not help as the methods fail when I give it a Predicate arg. This method seems to be good to check, items by items, if one or more match your pred but not sure they are made for retrieve set of items with a dynamic query.

EDIT : I created an EmployeeSpecification class implementing Specification but I want to return a list/array of Predicates not only one. The default method to override thus return a single Predicate. How can I manage to get multiple predicate from this entity ?

Thanks for any hint, helps, past experiences to share.

答:
You can just add a new method in your repository which extends the JpaRepository and write the fields by which you want to filter:</p>
```<code>public Page<SomeClass> findByNameContaining(String searchString, Pageable pageable);
</code>```

Body:
I'm fairly new to these technos and I need a pitch to understand a good way to do things.
I've got an Employee entity, and I want to list them by making a GET query to an endpoint.I have to return a Page of Employees, after having applied filters on field(s). Currently, the Pageable on the GET query works, but not my filter.

Here is my REST endpoint :

@RequestMapping(value = "/employees",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(readOnly = true)
public ResponseEntity<List<EmployeeDTO>> getAllEmployees(Pageable pageable, String filters) throws URISyntaxException, JSONException {

        JSONObject sfilters = null;
        try {
            sfilters = new JSONObject(filters.trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // I wish this on could works, but still have to update it if we add fields to our Employee entity
        Page<Employee> page = employeeRepository.findAllByCompanyIdAndFirstnameLikeAndLastnameLike(
            userService.getUserWithAuthorities().getCompany().getId(),
            sfilters.get("firstname").toString(),
            sfilters.get("lastname").toString(),
            pageable);

        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/employees");
        ResponseEntity<List<EmployeeDTO>> result = new ResponseEntity<>(page.getContent().stream()
            .map(employeeMapper::employeeToEmployeeDTO)
            .collect(Collectors.toCollection(LinkedList::new)), headers, HttpStatus.OK);

        return result;
}

NB : I have to filter on more fields than that but I want to keep example as clear as possible.

My repository method :

Page<Employee> findAllByCompanyIdAndFirstnameLikeAndLastnameLike(Long idCompany, String firstname, String lastname, Pageable pageable);

Client side, it works well, I send good params for pageable and for my filter to be converted into JSONObject. But now I need suggestions on how can I properly generate dynamics filters on my query. My JPA repository method doesnt work.

I tried to use predicates, but it does not help as the methods fail when I give it a Predicate arg. This method seems to be good to check, items by items, if one or more match your pred but not sure they are made for retrieve set of items with a dynamic query.

EDIT : I created an EmployeeSpecification class implementing Specification but I want to return a list/array of Predicates not only one. The default method to override thus return a single Predicate. How can I manage to get multiple predicate from this entity ?

Thanks for any hint, helps, past experiences to share.

Body:
You can just add a new method in your repository which extends the JpaRepository and write the fields by which you want to filter:

public Page<SomeClass> findByNameContaining(String searchString, Pageable pageable);