问:
How to position user typed-in content in search bar input?
I am working on a search bar for my site. It is positioned correctly on the site, it's styled and everything works just fine, I added a placeholder and positioned/styled it inside the search bar as I liked it to fit the rest of my site. If I click inside the search bar and write anything, the written letters appear in the default position of the placeholder (middle of the search bar), but I want them to be positioned differently (more to the left and lower), like the placeholder.
The placeholder looks good but the
typed-in text doesn't.

The HTML looks like this:

```<code><input id="searchbar" type="text" placeholder="Suche..." />
</code>```

The search bar is styled as following:

```<code>#searchbar {
  grid-area: search;
  font-size: max(var(--ändern), 20px);
  font-family: var(--schriftart);
  background-color: var(--hintergrundfarbe);
  color: var(--schriftfarbe);
  border: solid 1px;
  border-radius: 0.75vw;
  border-color: var(--hintergrundfarbe);
  text-align: center;
  width: 15vw;
  height: max(2.5vw, calc(150px / 4));
  margin-left: 1.25vw;
  margin-top: 0.5vw;
  box-sizing: border-box;
}
input:focus {
  outline: none;
}
</code>```

The placeholder is styled as following:

```<code>#searchbar::placeholder {
  color: var(--schriftfarbe);
  filter: opacity(0.5);
  position: absolute;
  left: 20px;
  top: auto;
  bottom: auto;
}
</code>```

I tried to use

```<code>#searchbar:focus {
  position: relative;
  left: 20px;
  top: auto;
  bottom: auto;
}
</code>```

but it shifts the whole search bar, not only the the typed-in content.
I also tried

```<code>text-indent: 40px;
</code>```

but doesn't seem to change anything either. I would be happy for anyone trying to help me :)

答:
Try the below code.

:root {
--hintergrundfarbe: rgb(182, 97, 22);
--schriftfarbe: rgb(255, 234, 0);
--schriftfarbe-hover: rgb(231, 181, 3);
--schriftfarbe-active: white;
--schriftart: Javanese Text;
--überschriftart: Matura MT Script Capitals;
--ändern: 1.25vw; }

#searchbar {
  grid-area: search;
  font-size: max(var(--ändern), 20px);
  font-family: var(--schriftart);
  background-color: var(--hintergrundfarbe);
  color: var(--schriftfarbe);
  border: solid 1px;
  border-radius: 0.75vw;
  border-color: var(--hintergrundfarbe);
  width: 15vw;
  height: max(2.5vw, calc(150px / 4));
  margin-left: 1.25vw;
  margin-top: 0.5vw;
  box-sizing: border-box;
  padding-left:20px;
  padding-top:10px;
}

input:focus {
  outline: none;
}

#searchbar::placeholder {
  color: var(--schriftfarbe);
  filter: opacity(0.5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="searchbar" type="text" placeholder="Suche..." /></code>```

Body:
I am working on a search bar for my site. It is positioned correctly on the site, it's styled and everything works just fine, I added a placeholder and positioned/styled it inside the search bar as I liked it to fit the rest of my site. If I click inside the search bar and write anything, the written letters appear in the default position of the placeholder (middle of the search bar), but I want them to be positioned differently (more to the left and lower), like the placeholder.
The placeholder looks good but the
typed-in text doesn't.

The HTML looks like this:

<input id="searchbar" type="text" placeholder="Suche..." />

The search bar is styled as following:

#searchbar {
  grid-area: search;
  font-size: max(var(--ändern), 20px);
  font-family: var(--schriftart);
  background-color: var(--hintergrundfarbe);
  color: var(--schriftfarbe);
  border: solid 1px;
  border-radius: 0.75vw;
  border-color: var(--hintergrundfarbe);
  text-align: center;
  width: 15vw;
  height: max(2.5vw, calc(150px / 4));
  margin-left: 1.25vw;
  margin-top: 0.5vw;
  box-sizing: border-box;
}
input:focus {
  outline: none;
}

The placeholder is styled as following:

#searchbar::placeholder {
  color: var(--schriftfarbe);
  filter: opacity(0.5);
  position: absolute;
  left: 20px;
  top: auto;
  bottom: auto;
}

I tried to use

#searchbar:focus {
  position: relative;
  left: 20px;
  top: auto;
  bottom: auto;
}

but it shifts the whole search bar, not only the the typed-in content.
I also tried

text-indent: 40px;

but doesn't seem to change anything either. I would be happy for anyone trying to help me :)

Body:
Try the below code.

:root {
--hintergrundfarbe: rgb(182, 97, 22);
--schriftfarbe: rgb(255, 234, 0);
--schriftfarbe-hover: rgb(231, 181, 3);
--schriftfarbe-active: white;
--schriftart: Javanese Text;
--überschriftart: Matura MT Script Capitals;
--ändern: 1.25vw; }

#searchbar {
  grid-area: search;
  font-size: max(var(--ändern), 20px);
  font-family: var(--schriftart);
  background-color: var(--hintergrundfarbe);
  color: var(--schriftfarbe);
  border: solid 1px;
  border-radius: 0.75vw;
  border-color: var(--hintergrundfarbe);
  width: 15vw;
  height: max(2.5vw, calc(150px / 4));
  margin-left: 1.25vw;
  margin-top: 0.5vw;
  box-sizing: border-box;
  padding-left:20px;
  padding-top:10px;
}

input:focus {
  outline: none;
}

#searchbar::placeholder {
  color: var(--schriftfarbe);
  filter: opacity(0.5);
}

<input id="searchbar" type="text" placeholder="Suche..." />


来源: stackexchange

问:
react-native start EACCESS error for setup_env.sh
So, I got my first project in ReactNative to run from Windows for Android OS. Took a checkout on a Mac, configured it in an identical manner and as I try to start the react package manager using react-native start and get the following error:

```<code>child_process.js:506
    throw err;
    ^
Error: spawnSync /Users/UserName/Desktop/Path/node_modules/react-native/local-cli/setup_env.sh EACCES
    at exports._errnoException (util.js:1022:11)
    at spawnSync (child_process.js:461:20)
    at Object.execFileSync (child_process.js:498:13)
    at Object.run (/Users/UserName/Desktop/Path/node_modules/react-native/local-cli/cliEntry.js:156:16)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:117:7)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
</code>```

I am aware that it only tries to set the ulimit (open file limit) to 2048 which is permissible for non root users. Also tried running the command with sudo giving it root permissions.
Running ulimit -a on the machine revealed an open file limit of 256 and I tried changing the default 2048 to this. Tried increasing it to 4096 as well removing the command altogether. Seems to make no difference what so ever and the error persists.

Created a new project using react-native init DemoProject and the packager seems to start within that folder so the issue is something else?

My package.json is:

```<code>{
  "name": "React Native",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "native-base": "^0.5.18",
    "react": "15.4.1",
    "react-addons-shallow-compare": "^15.4.1",
    "react-native": "0.39.2",
    "react-native-drawer": "^2.3.0",
    "react-native-icons": "^0.7.1",
    "react-native-loading-spinner-overlay": "^0.4.1",
    "react-native-md-textinput": "^2.0.4",
    "react-native-overlay": "^0.5.0",
    "react-native-scrollable-tab-view": "^0.7.0",
    "react-native-tab-view": "0.0.40",
    "react-redux": "^4.4.6",
    "react-timer-mixin": "^0.13.3",
    "redux": "^3.6.0"
  },
  "devDependencies": {
    "babel-jest": "17.0.2",
    "babel-preset-react-native": "1.9.0",
    "jest": "17.0.3",
    "react-test-renderer": "15.4.1"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

Also, if it matters I have sinopia, browserify and yarn installed globally.

To start with, I am not sure if I should add all local dependencies through npm yet again on the Mac and then just copy my code or that should be fine and something else is amiss.

It would be great if I can sort this out without re-adding dependencies. Thanks in advance.

答:
i have the same issue i tried this and the initial issue got fixed

chmod -R 775 android

ContentLicense: CC BY-SA 3.0

Body:
So, I got my first project in ReactNative to run from Windows for Android OS. Took a checkout on a Mac, configured it in an identical manner and as I try to start the react package manager using react-native start and get the following error:

child_process.js:506
    throw err;
    ^
Error: spawnSync /Users/UserName/Desktop/Path/node_modules/react-native/local-cli/setup_env.sh EACCES
    at exports._errnoException (util.js:1022:11)
    at spawnSync (child_process.js:461:20)
    at Object.execFileSync (child_process.js:498:13)
    at Object.run (/Users/UserName/Desktop/Path/node_modules/react-native/local-cli/cliEntry.js:156:16)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:117:7)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

I am aware that it only tries to set the ulimit (open file limit) to 2048 which is permissible for non root users. Also tried running the command with sudo giving it root permissions.
Running ulimit -a on the machine revealed an open file limit of 256 and I tried changing the default 2048 to this. Tried increasing it to 4096 as well removing the command altogether. Seems to make no difference what so ever and the error persists.

Created a new project using react-native init DemoProject and the packager seems to start within that folder so the issue is something else?

My package.json is:

{
  "name": "React Native",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "native-base": "^0.5.18",
    "react": "15.4.1",
    "react-addons-shallow-compare": "^15.4.1",
    "react-native": "0.39.2",
    "react-native-drawer": "^2.3.0",
    "react-native-icons": "^0.7.1",
    "react-native-loading-spinner-overlay": "^0.4.1",
    "react-native-md-textinput": "^2.0.4",
    "react-native-overlay": "^0.5.0",
    "react-native-scrollable-tab-view": "^0.7.0",
    "react-native-tab-view": "0.0.40",
    "react-redux": "^4.4.6",
    "react-timer-mixin": "^0.13.3",
    "redux": "^3.6.0"
  },
  "devDependencies": {
    "babel-jest": "17.0.2",
    "babel-preset-react-native": "1.9.0",
    "jest": "17.0.3",
    "react-test-renderer": "15.4.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

Also, if it matters I have sinopia, browserify and yarn installed globally.

To start with, I am not sure if I should add all local dependencies through npm yet again on the Mac and then just copy my code or that should be fine and something else is amiss.

It would be great if I can sort this out without re-adding dependencies. Thanks in advance.

ContentLicense: CC BY-SA 4.0


问:
Why is np.cumprod() slower than my own function for large arrays?
Doing a few tests, I noticed that a custom loop function I wrote could be faster than NumPy built-in function np.cumprod(). I didn't think it was possible, could someone explain what happens?

```<code>import time
import numpy as np

def custom_cumprod(x):
    xb = [1]
    for xi in x:
        xb.append(xb[-1]*xi)
    return np.array(xb[1:])

x = np.random.random((10000, 10000))

t0 = time.time()
b = custom_cumprod(x)
t1 = time.time()
print(t1-t0)
t0 = time.time()
c = np.cumprod(x,0)
t1 = time.time()
print(t1-t0)
print(np.sum(c-b))
</code>```

Thanks!

答:
The issue is that the computation runs along the outer dimension and numpy doesn't seem to optimize this case. By looping along this dimension, values are not consecutive in memory, resulting in cache and TLB misses.

This can be fixed by storing the array in Fortran order (np.asfortranarray), or transposing it and running the computation along the inner dimension.

perf shows the difference clearly:

perf stat -e LLC-load-misses,dTLB-load-misses python3 -c \
    'import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=0)'

 Performance counter stats for 'python3 -c import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=0)':

        22.254.639      LLC-load-misses:u
       114.772.180      dTLB-load-misses:u

       3,200727804 seconds time elapsed

       2,148422000 seconds user
       1,044664000 seconds sys

perf stat -e LLC-load-misses,dTLB-load-misses python3 -c \
    'import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=1)'

 Performance counter stats for 'python3 -c import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=1)':

           633.959      LLC-load-misses:u
         2.485.725      dTLB-load-misses:u

       2,276527365 seconds time elapsed

       0,947946000 seconds user
       1,316536000 seconds sys
```

Ideally numpy should run the computation the same way you did in your custom version.

Body:
Doing a few tests, I noticed that a custom loop function I wrote could be faster than NumPy built-in function np.cumprod(). I didn't think it was possible, could someone explain what happens?

import time
import numpy as np

def custom_cumprod(x):
    xb = [1]
    for xi in x:
        xb.append(xb[-1]*xi)
    return np.array(xb[1:])

x = np.random.random((10000, 10000))

t0 = time.time()
b = custom_cumprod(x)
t1 = time.time()
print(t1-t0)
t0 = time.time()
c = np.cumprod(x,0)
t1 = time.time()
print(t1-t0)
print(np.sum(c-b))

Thanks!

Body:
The issue is that the computation runs along the outer dimension and numpy doesn't seem to optimize this case. By looping along this dimension, values are not consecutive in memory, resulting in cache and TLB misses.

This can be fixed by storing the array in Fortran order (np.asfortranarray), or transposing it and running the computation along the inner dimension.

perf shows the difference clearly:

perf stat -e LLC-load-misses,dTLB-load-misses python3 -c \
    'import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=0)'

 Performance counter stats for 'python3 -c import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=0)':

        22.254.639      LLC-load-misses:u
       114.772.180      dTLB-load-misses:u

       3,200727804 seconds time elapsed

       2,148422000 seconds user
       1,044664000 seconds sys

perf stat -e LLC-load-misses,dTLB-load-misses python3 -c \
    'import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=1)'

 Performance counter stats for 'python3 -c import numpy as np; np.cumprod(np.random.random((10000, 10000)), axis=1)':

           633.959      LLC-load-misses:u
         2.485.725      dTLB-load-misses:u

       2,276527365 seconds time elapsed

       0,947946000 seconds user
       1,316536000 seconds sys

Ideally numpy should run the computation the same way you did in your custom version.


问:
Combine variables from a dataframe
Good morning, I have the following dataframe:

```<code>dft
</code>```
```<code>Country Brazil  Brazil  Brazil  Brazil  Bolivia Bolivia Bolivia Bolivia Bolivia Bolivia Bolivia Bolivia Chile   Chile   Chile   Chile   Chile   Chile   Chile   Chile
Order   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20
Product TV  TV  Computer    TV  TV  Computer    Computer    Computer    TV  Radio   TV  Radio   Radio   Radio   Computer    Computer    TV  TV  Radio   TV
</code>```

I want to group the dataframe into something like:

```<code>Country Brazil Brazil Brazil Bolívia Bolívia Bolívia Chile Chile Chile
Order 7 3 0 25 21 22 22 55 31 58
Product Tv Computer Radio Tv Computer Radio Tv Computer Radio
</code>```

How can I make it?

答:
You can group by the by country and product and sum by order:

df2 = df.groupby(['Country','Product'])['Order'].sum()

Title: Combine variables from a dataframe

Body:
Good morning, I have the following dataframe:

dft

Country Brazil  Brazil  Brazil  Brazil  Bolivia Bolivia Bolivia Bolivia Bolivia Bolivia Bolivia Bolivia Chile   Chile   Chile   Chile   Chile   Chile   Chile   Chile
Order   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20
Product TV  TV  Computer    TV  TV  Computer    Computer    Computer    TV  Radio   TV  Radio   Radio   Radio   Computer    Computer    TV  TV  Radio   TV

I want to group the dataframe into something like:

Country Brazil Brazil Brazil Bolívia Bolívia Bolívia Chile Chile Chile
Order 7 3 0 25 21 22 22 55 31 58
Product Tv Computer Radio Tv Computer Radio Tv Computer Radio

How can I make it?


问:
Replace substring of NSAttributedString with another NSAttributedString
I want to replace a substring (e.g. @"replace") of an NSAttributedString with another NSAttributedString.

I am looking for an equivalent method to NSString's stringByReplacingOccurrencesOfString:withString: for NSAttributedString.

答:
i created a Swift 5 extension for that

```<code>extension NSMutableAttributedString {

    func replace(_ findString: String, with replacement: String, attributes: [NSAttributedString.Key : Any]) {

        let ms = mutableString

        var range = ms.range(of: findString)
        while range.location != NSNotFound {
            addAttributes(attributes, range: range)
            ms.replaceCharacters(in: range, with: replacement)

            range = ms.range(of: findString)
        }

    }

}
</code>```

use case

```<code>attributedString.replace("%EMAIL%", with: email, attributes: [.font:boldFont])

</code>```

Body:
i created a Swift 5 extension for that

extension NSMutableAttributedString {

    func replace(_ findString: String, with replacement: String, attributes: [NSAttributedString.Key : Any]) {

        let ms = mutableString

        var range = ms.range(of: findString)
        while range.location != NSNotFound {
            addAttributes(attributes, range: range)
            ms.replaceCharacters(in: range, with: replacement)

            range = ms.range(of: findString)
        }

    }

}

use case

attributedString.replace("%EMAIL%", with: email, attributes: [.font:boldFont])


问:
Return consecutive items or single items with null property from an array of objects as array of subsets
I'm looking for a solution on how to extract only consecutive objects with a null property from an array of objects, please see the example below.

Important note:

Array.proptype.filter((item)=> item.y === null) doesn't solve the problem here, .filter method will simply return an array objects where y is equal null.

What I'm willing to achieve here is actually quite more sophisticated than returning a simple array, the goal is to write a method that can iterate through each item in the array, check if the next item also has a null y, if true, the next item must be added to the extracted subset of objects.

Consecutive items are simply the items that come after each other, if the object with the index 3 has a null y property and the object with index 4 has a null y property as well, objects with indexes 3 and 4 can be considered as consecutive items,

If the item with index 8 has a null y but the items respectively with indexes 7 and 9 doesn't have a null y, only the item with index 8 must be added to the extracted subset.

First use case:

the method must be able to spot consecutive nulls and extract them as a subset of the original input set.

input:

```<code>['spider', null, null, null, 'cat','horse', 'eagle']
</code>```

output:

```<code>[
 [null, null, null], <= one subset of nulls representing the nulls between 'spider' and 'cat'
]
</code>```

Second use case:

The method must be able to consider single null items and also extract them into a single item subset array.

input:

```<code>['spider', null, null, null, 'cat', null, 'horse', 'eagle']

</code>```

output:

```<code>[
 [null, null, null], <== first subset
 [null], <== second subset representing the null item between the 'cat' and 'horse'
]
</code>```

Given the dataSet below, I want to extract the items where y property is null.

output pattern

```<code>[
  [first-subset-of-consecutive-nulls],
  [second-subset-of-consecutive-nulls],
  [....]
]
</code>```

Please note that the expected output data structure is an array of arrays and not an array of objects.

Here's a more real-life dataSet example with the expected output.
The expected output should be an array of arrays that contain a subset of the dataSet where the y property is null and the objects are consecutive.

```<code>const dataSet = [
 {x: 'foo', y: 'random-y'},
 {x: 'bar', y: 'random-y'},
 {x: 'yo', y: null}, <=
 {x: 'random', y: null}, <=
 {x: 'lorem', y: null}, <=
 {x: 'ipsum', y: 'random-y'},
 {x: 'dolor', y: 'random-y'},
 {x: 'var', y: null}, <=
 {x: 'mit', y: null}, <=
 {x: 'oder', y: 'random-y'},
 {x: 'whatever', y: null}, <=
 {x: 'something', y: 'random-y'}
];

// Method signature e.g extractSuccesiveNullBy(objectProp: string, from: Array<any>);

extractSuccessiveNullsBy('y', dataSet);
</code>```

Expected output:

```<code>[
  [ {x: 'yo', y: null}, {x: 'random', y: null}, {x: 'lorem', y: null}],
  [ {x: 'var', y: null}, {x: 'mit', y: null}],
  [ {x: 'whatever', y: null]
]
</code>```

Any proposal will be well appreciated.
Thanks.

答:
The hash grouping approach can be applied:

const dataSet = [{x: 'foo', y: 'random-y'},{x: 'bar', y: 'random-y'},{x: 'yo', y: null},{x: 'random', y: null},{x: 'lorem', y: null},{x: 'ipsum', y: 'random-y'},{x: 'dolor', y: 'random-y'},{x: 'var', y: null},{x: 'mit', y: null},{x: 'oder', y: 'random-y'},{x: 'whatever', y: null},{x: 'something', y: 'random-y'}];

let counter = 0;
const result = Object.values(dataSet.reduce((acc, obj) => {
    if (obj.y !== null) {
        counter += 1;
        return acc;
    }

    acc[counter] = acc[counter] ? [...acc[counter], obj] : [obj];
    return acc;
}, {}));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

Body:
I'm looking for a solution on how to extract only consecutive objects with a null property from an array of objects, please see the example below.

Important note:

Array.proptype.filter((item)=> item.y === null) doesn't solve the problem here, .filter method will simply return an array objects where y is equal null.

What I'm willing to achieve here is actually quite more sophisticated than returning a simple array, the goal is to write a method that can iterate through each item in the array, check if the next item also has a null y, if true, the next item must be added to the extracted subset of objects.

Consecutive items are simply the items that come after each other, if the object with the index 3 has a null y property and the object with index 4 has a null y property as well, objects with indexes 3 and 4 can be considered as consecutive items,

If the item with index 8 has a null y but the items respectively with indexes 7 and 9 doesn't have a null y, only the item with index 8 must be added to the extracted subset.

First use case:

the method must be able to spot consecutive nulls and extract them as a subset of the original input set.

input:

['spider', null, null, null, 'cat','horse', 'eagle']

output:

[
 [null, null, null], <= one subset of nulls representing the nulls between 'spider' and 'cat'
]

Second use case:

The method must be able to consider single null items and also extract them into a single item subset array.

input:

['spider', null, null, null, 'cat', null, 'horse', 'eagle']

output:

[
 [null, null, null], <== first subset
 [null], <== second subset representing the null item between the 'cat' and 'horse'
]

Given the dataSet below, I want to extract the items where y property is null.

output pattern

[
  [first-subset-of-consecutive-nulls],
  [second-subset-of-consecutive-nulls],
  [....]
]

Please note that the expected output data structure is an array of arrays and not an array of objects.

Here's a more real-life dataSet example with the expected output.
The expected output should be an array of arrays that contain a subset of the dataSet where the y property is null and the objects are consecutive.

const dataSet = [
 {x: 'foo', y: 'random-y'},
 {x: 'bar', y: 'random-y'},
 {x: 'yo', y: null}, <=
 {x: 'random', y: null}, <=
 {x: 'lorem', y: null}, <=
 {x: 'ipsum', y: 'random-y'},
 {x: 'dolor', y: 'random-y'},
 {x: 'var', y: null}, <=
 {x: 'mit', y: null}, <=
 {x: 'oder', y: 'random-y'},
 {x: 'whatever', y: null}, <=
 {x: 'something', y: 'random-y'}
];

// Method signature e.g extractSuccesiveNullBy(objectProp: string, from: Array<any>);

extractSuccessiveNullsBy('y', dataSet);

Expected output:

[
  [ {x: 'yo', y: null}, {x: 'random', y: null}, {x: 'lorem', y: null}],
  [ {x: 'var', y: null}, {x: 'mit', y: null}],
  [ {x: 'whatever', y: null]
]

Any proposal will be well appreciated.
Thanks.

Body:
The hash grouping approach can be applied:

const dataSet = [{x: 'foo', y: 'random-y'},{x: 'bar', y: 'random-y'},{x: 'yo', y: null},{x: 'random', y: null},{x: 'lorem', y: null},{x: 'ipsum', y: 'random-y'},{x: 'dolor', y: 'random-y'},{x: 'var', y: null},{x: 'mit', y: null},{x: 'oder', y: 'random-y'},{x: 'whatever', y: null},{x: 'something', y: 'random-y'}];

let counter = 0;
const result = Object.values(dataSet.reduce((acc, obj) => {
    if (obj.y !== null) {
        counter += 1;
        return acc;
    }

    acc[counter] = acc[counter] ? [...acc[counter], obj] : [obj];
    return acc;
}, {}));

console.log(result);

.as-console-wrapper{min-height: 100%!important; top: 0}


问:
Keycloak same username in multiple federations
I have two user federations in one realm (different active directories). Because both are completely independent, in occurs that the same username is used.

In Microsoft Applications you can use something like "ad1\ttestuser" and "ad2\ttestuser". Is there a way I can configure Keycloak to choose the user federation on login? A solution would be to add a prefix to the username in the mapper but there is no way to do it.

答:
Is there a way I can configure Keycloak to choose the user federation
on login?

You could create a different realm per user federation that you want your users to be able to explicitly authentication against. Then you configure each user federation in its own realm. Finally,
you configured those realms to do identity brokering against the original realm.

The login page would look something like:

You can have a look a this answer which describes this setup in more detail.


问:
Javascript selecting nth element but excluding some elements
Consider the following markup:

```<code><div class="body">
     <p>...<p>
     <p>...<p>
     <blockquote>
          <p>...<p>
     </blockquote>
     <p>...<p>
     <p>...<p>
</div>
</code>```

I want to select the first
 element. I can do this with:

```<code>$( ".body p:nth-child(1)
</code>```

However if I wanted to select the 3rd
 (excluding the blockquote) this will not work:

```<code>$( ".body p:nth-child(3)
</code>```

I tried using nth-type, but if I do:

```<code>$( ".body p:nth-of-type(1)
</code>```

It will select the first
 in the body and also the next p in block quote.

I need to be able to exclude or ignore the blockquote. Would it work if I read the dom into a variable and removed the blockquote before calling nth-child?

答:
Since you're using jQuery, which returns an array of elements, you can avoid the quirks of the CSS nth-... rules. All you really need is a selector that only selects the elements you want.

e.g. .body > p which only matches direct children of the body class

then select the third element using jQuery's .eq(2) (It's 0 indexed, so 2 is the 3rd matching element)

$(document).ready(function() {
  $(".body > p").eq(2).text("New text")
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <p>1</p>
  <p>2</p>
  <blockquote>
    <p>3</p>
  </blockquote>
  <p>4</p>
  <p>5</p>
</div></code>```

Body:
Consider the following markup:

...

...

...

...

...

I want to select the first
 element. I can do this with:

$( ".body p:nth-child(1)

However if I wanted to select the 3rd
 (excluding the blockquote) this will not work:

$( ".body p:nth-child(3)

I tried using nth-type, but if I do:

$( ".body p:nth-of-type(1)

It will select the first
 in the body and also the next p in block quote.

I need to be able to exclude or ignore the blockquote. Would it work if I read the dom into a variable and removed the blockquote before calling nth-child?

Body:
Since you're using jQuery, which returns an array of elements, you can avoid the quirks of the CSS nth-... rules. All you really need is a selector that only selects the elements you want.

e.g. .body > p which only matches direct children of the body class

then select the third element using jQuery's .eq(2) (It's 0 indexed, so 2 is the 3rd matching element)

$(document).ready(function() {
  $(".body > p").eq(2).text("New text")
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
  <p>1</p>
  <p>2</p>
  <blockquote>
    <p>3</p>
  </blockquote>
  <p>4</p>
  <p>5</p>
</div>


问:
JSON object return of an array of objects which contains the keys and its values
Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.

JSON file with data:
https://challenge.codingsans.com/beers.json

Output Example:

```<code>[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]
</code>```

//

I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)

```<code>request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);

        //final list

        var finalList = [];

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();
</code>```

答:
Follow below steps :

Grouping input array of objects by brand and resulting with an object using Array.reduce() method.

Structuring the output based on the reduced brand object we have.

Working Demo :

const data = [
  {
    "id": "ccw-1",
    "name": "Coding Challenge White",
    "brand": "Coding Challenge Brewery"
  }, {
    "id": "sw-1",
    "name": "Share White",
    "brand": "Share",
  }, {
    "id": "bspa-1",
    "name": "Beer Sans Pale Ale",
    "brand": "Beer Sans Brewery"
  }, {
    "id": "ccb-1",
    "name": "Coding Challenge Brown",
    "brand": "Coding Challenge Brewery"
  }, {
    "id": "ccw-2",
    "name": "Coding Challenge Wheat",
    "brand": "Coding Challenge Brewery"
  }];

// result array
const resultArr = [];

// grouping by brand and resulting with an object using Array.reduce() method
const groupByBrand = data.reduce((group, item) => {
  const { brand } = item;
  group[brand] = group[brand] ?? [];
  group[brand].push(item.id);
  return group;
}, {});

// Finally structuring the output based on the brand object we have.
Object.keys(groupByBrand).forEach((item) => {
    resultArr.push({
      'brand': item,
      'beers': groupByBrand[item]
    })
})

// Result
console.log(resultArr);```

Body:
Boris has a list of all the beers available in his pub, but it's a huge mess. He would like to see the beers grouped by brands. Boris also told you that the Function should return an array of objects which contains the Brand name and an array of beer IDs of that Brand.

JSON file with data:
https://challenge.codingsans.com/beers.json

Output Example:

[
  {
    "brand": "brandName2",
    "beers": [
      "beerID3",
      "beerID4"
    ]
  },
  {
    "brand": "brandName1",
    "beers": [
      "beerID2",
      "beerID1"
    ]
  }
]

//

I have done this:
(So basically nothing. I just would like to get some idea how to solve it.)

request = new XMLHttpRequest;
request.open('GET', 'https://challenge.codingsans.com/beers.json', true);
var data = [];
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Date Parse
        data = JSON.parse(request.responseText);
        // Success!

        // Arrays
        var beerIDs = [];
        var beerBrand = [];
        // Iteration

        for (var key in data) {
            beerIDs.push(data[key].id);
            beerBrand.push(data[key].brand);
            // console.log(beerIDs);
            // console.log(beerBrand);
        }
        console.log(beerIDs);
        console.log(beerBrand);

        //final list

        var finalList = [];

    } else {
        // We reached our target server, but it returned an error
    }
};

request.onerror = function() {
    // There was a connection error of some sort
};

request.send();


问:
SQL Server proc running 5x slower than plain query
I have the following query:

```<code>DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC
</code>```

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?

答:
I would recommend recompiling the execution plan for the stored procedure.

usage:   sp_recompile '[target]'

example: sp_recompile 'dbo.GetObject'

When you execute a query from SSMS the query plan is automatically redone every time its executed. However with stored procs, sql server caches execution plans for stored procedures, and its this execution plan that gets used everytime the stored proc is called.

Link for sp_recompile.

You can also change the proc to use with WITH RECOMPILE clause within the stored proc.

Example:

```<code>CREATE PROCEDURE dbo.GetObject
(
    @parm1 VARCHAR(20)
)
WITH RECOMPILE
AS
BEGIN
  -- Queries/work here.
END
</code>```

However this will force the execution plan to be recompiled every time the stored proc is called. This is good for dev/testing where the proc and/or data changes quite frequently. Make sure you remove it when you deploy it to production, as this can have a performance hit.

sp_recompile only recompiles the execution plan once. If you need to do it again at a later date, you will need to make the call again.

Good luck!

Body:
I have the following query:

DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?

Body:
I would recommend recompiling the execution plan for the stored procedure.

usage:   sp_recompile '[target]'

example: sp_recompile 'dbo.GetObject'

When you execute a query from SSMS the query plan is automatically redone every time its executed. However with stored procs, sql server caches execution plans for stored procedures, and its this execution plan that gets used everytime the stored proc is called.

Link for sp_recompile.

You can also change the proc to use with WITH RECOMPILE clause within the stored proc.

Example:

CREATE PROCEDURE dbo.GetObject
(
    @parm1 VARCHAR(20)
)
WITH RECOMPILE
AS
BEGIN
  -- Queries/work here.
END

However this will force the execution plan to be recompiled every time the stored proc is called. This is good for dev/testing where the proc and/or data changes quite frequently. Make sure you remove it when you deploy it to production, as this can have a performance hit.

sp_recompile only recompiles the execution plan once. If you need to do it again at a later date, you will need to make the call again.

Good luck!


问:
Lisp: How to set element in list of lists?
I am familiar with how to set elements in a 2D array, which can be done using the following statement.

```<code>(setf (aref array2D 0 0) 3)
</code>```

However, I am not familiar how to set elements in a list of lists, such as the following input: '((1) (2) (2) (1)). I can't use aref, since it only works on arrays.

答:
To access the nth element of a list, there are (at least) two functions: nth and elt. The order of the parameters is different, and nth only work on lists while elt works on any sequence (i.e. lists, vector, strings ...):

```<code>(nth 1 '(foo bar baz)) => BAR
(nth 1 #(foo bar baz)) => ERROR
(elt '(foo bar baz) 1) => BAR
(elt #(foo bar baz) 1) => BAR
</code>```

Now, in general, the way to set a value (as opposed to simply access it) is very straightforward, and at least for built-in functions this is almost always the case: whenever you have some form FORM which retrieves some value from what is called a place, the form (setf FORM <value>) will set this element to the given <value>. This works for functions such as car, cdr, gethash, aref, slot-value, symbol-function and many others, and any combination of those.

In your example, you have a list of lists. So, for example, to modify the "inner integer" in say the third list:

```<code>* (setf test-list '((0) (1) (2) (3))) ; changed the values to have something clearer
((0) (1) (2) (3))
* (car (nth 2 test-list)) ; this accesses the integer in the second list
2
* (setf (car (nth 2 test-list)) 12) ; this modifies it. Notice the syntax
12
* test-list
((0) (1) (12) (3))
</code>```

On a side note, you should avoid modifying literal lists (created using the quote symbol '). If you want to modify lists, create them at runtime using the list function.

EDIT:
What happens is that setf knows, by "looking" at the form you give it, how to actually find the place that you want to modify, potentially using functions in this process.

If you look at other languages, such as Python, you also have some kind of duality in the syntax used both to get and to set values. Indeed, if you have a list L or a dictionary d, then L[index] and d[thing] will get the corresponding element while L[index] = 12 and d[thing] = "hello" will modify it.

However, in Python, those accessors use a special syntax, namely, the squares brackets []. Other types of objects use another syntax, for example, the dot notation to access slots/attributes of an object as in my-object.attr. A consequence is that the following code is invalid in Python:

```<code>>>> L = [1, 2, 3, 2, 1]

>>> max(L)

3
>>> max(L) = 12

Traceback (most recent call last):
  File "<string>", line 9, in __PYTHON_EL_eval
  File "/usr/lib/python3.8/ast.py", line 47, in parse
    return compile(source, filename, mode, flags,
  File "<string>", line 1
SyntaxError: cannot assign to function call
</code>```

You have to write an other function, for example, setMax(L, val), to change the maximum of a list. This means that you now have to functions, and no symmetry anymore.

In Common Lisp, everything is (at least syntactically) a function call. This means that you can define new ways to access and modify things, for any function ! As a (bad) example of what you could do:

```<code>* (defun my-max (list)
    (reduce #'max list))
MY-MAX
* (my-max '(1 2 3 8 4 5))
8
* (defun (setf my-max) (val list)
    (do ((cur list (cdr cur))
         (cur-max list (if (< (car cur-max) (car cur))
                               cur
                               cur-max)))
        ((endp (cdr cur)) (setf (car cur-max) val))))

(SETF MY-MAX)
* (setf test-list (list 0 4 5 2 3 8 6 3))
(0 4 5 2 3 8 6 3)
* (setf (my-max test-list) 42)
42
* test-list
(0 4 5 2 3 42 6 3)
</code>```

This way, the syntax used to both set and get the maximum of a list is identical (FORM to get, (setf FORM val) to set), and combines automatically with every other "setter". No explicit pointers/references involved, it's just functions.

Body:
I am familiar with how to set elements in a 2D array, which can be done using the following statement.

(setf (aref array2D 0 0) 3)

However, I am not familiar how to set elements in a list of lists, such as the following input: '((1) (2) (2) (1)). I can't use aref, since it only works on arrays.

Body:
To access the nth element of a list, there are (at least) two functions: nth and elt. The order of the parameters is different, and nth only work on lists while elt works on any sequence (i.e. lists, vector, strings ...):

(nth 1 '(foo bar baz)) => BAR
(nth 1 #(foo bar baz)) => ERROR
(elt '(foo bar baz) 1) => BAR
(elt #(foo bar baz) 1) => BAR

Now, in general, the way to set a value (as opposed to simply access it) is very straightforward, and at least for built-in functions this is almost always the case: whenever you have some form FORM which retrieves some value from what is called a place, the form (setf FORM <value>) will set this element to the given <value>. This works for functions such as car, cdr, gethash, aref, slot-value, symbol-function and many others, and any combination of those.

In your example, you have a list of lists. So, for example, to modify the "inner integer" in say the third list:

* (setf test-list '((0) (1) (2) (3))) ; changed the values to have something clearer
((0) (1) (2) (3))
* (car (nth 2 test-list)) ; this accesses the integer in the second list
2
* (setf (car (nth 2 test-list)) 12) ; this modifies it. Notice the syntax
12
* test-list
((0) (1) (12) (3))

On a side note, you should avoid modifying literal lists (created using the quote symbol '). If you want to modify lists, create them at runtime using the list function.

EDIT:
What happens is that setf knows, by "looking" at the form you give it, how to actually find the place that you want to modify, potentially using functions in this process.

If you look at other languages, such as Python, you also have some kind of duality in the syntax used both to get and to set values. Indeed, if you have a list L or a dictionary d, then L[index] and d[thing] will get the corresponding element while L[index] = 12 and d[thing] = "hello" will modify it.

However, in Python, those accessors use a special syntax, namely, the squares brackets []. Other types of objects use another syntax, for example, the dot notation to access slots/attributes of an object as in my-object.attr. A consequence is that the following code is invalid in Python:

>>> L = [1, 2, 3, 2, 1]

>>> max(L)

3
>>> max(L) = 12

Traceback (most recent call last):
  File "<string>", line 9, in __PYTHON_EL_eval
  File "/usr/lib/python3.8/ast.py", line 47, in parse
    return compile(source, filename, mode, flags,
  File "<string>", line 1
SyntaxError: cannot assign to function call

You have to write an other function, for example, setMax(L, val), to change the maximum of a list. This means that you now have to functions, and no symmetry anymore.

In Common Lisp, everything is (at least syntactically) a function call. This means that you can define new ways to access and modify things, for any function ! As a (bad) example of what you could do:

* (defun my-max (list)
    (reduce #'max list))
MY-MAX
* (my-max '(1 2 3 8 4 5))
8
* (defun (setf my-max) (val list)
    (do ((cur list (cdr cur))
         (cur-max list (if (< (car cur-max) (car cur))
                               cur
                               cur-max)))
        ((endp (cdr cur)) (setf (car cur-max) val))))

(SETF MY-MAX)
* (setf test-list (list 0 4 5 2 3 8 6 3))
(0 4 5 2 3 8 6 3)
* (setf (my-max test-list) 42)
42
* test-list
(0 4 5 2 3 42 6 3)

This way, the syntax used to both set and get the maximum of a list is identical (FORM to get, (setf FORM val) to set), and combines automatically with every other "setter". No explicit pointers/references involved, it's just functions.


问:
get npm process exitcode as output in powershell
I'm new to Powershell and want to automate some process by Powershell script.
Is there any way to get the status of npm run build, if it fails. Currently, if I'm not adding a condition then it sequencely runs the next commands either its success or fails.

I already added $ErrorActionPreference = "Stop" but it only works for cmdlet.

```<code>$exitcode = npm run build
#need exitcode as output to check
if ($exitcode -eq 0) {
   Remove-Item -Path $spaNodeModulePath -Force -Recurse
   mkdir $spaNodeModulePath
   xcopy $libDistPath $spaNodeModulePath /e
   Set-Location $spaPath
}
</code>```

答:
You can use $LASTEXITCODE variable which contains the exit code of the last native program that was run. So first execute the program and check the $LASTEXITCODE later.

```<code>npm run build
if ($LASTEXITCODE -eq 0) {
    Write-Output "NPM build was successful"
}
</code>```

Please note that $LASTEXITCODE is not something that user defines, It's created and maintained by the PowerShell runtime.

Body:
I'm new to Powershell and want to automate some process by Powershell script.
Is there any way to get the status of npm run build, if it fails. Currently, if I'm not adding a condition then it sequencely runs the next commands either its success or fails.

I already added $ErrorActionPreference = "Stop" but it only works for cmdlet.

$exitcode = npm run build
#need exitcode as output to check
if ($exitcode -eq 0) {
   Remove-Item -Path $spaNodeModulePath -Force -Recurse
   mkdir $spaNodeModulePath
   xcopy $libDistPath $spaNodeModulePath /e
   Set-Location $spaPath
}

Body:
You can use $LASTEXITCODE variable which contains the exit code of the last native program that was run. So first execute the program and check the $LASTEXITCODE later.

npm run build
if ($LASTEXITCODE -eq 0) {
    Write-Output "NPM build was successful"
}

Please note that $LASTEXITCODE is not something that user defines, It's created and maintained by the PowerShell runtime.


问:
How to design button with box shadow in native script
I am new in native script.I want to design button with box shadow

.boxShadow {
   box-shadow: 10px 10px 5px grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><Button class="boxShadow" text="submit"></Button></code>```

答:
You can set your style with Js by following code

const btn = document.querySelector('#boxShadow');
btn.style.boxShadow = '10px 10px 5px grey';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><Button id="boxShadow" text="submit">btn</Button></code>```

Body:
I am new in native script.I want to design button with box shadow

.boxShadow {
   box-shadow: 10px 10px 5px grey;
}

<Button class="boxShadow" text="submit"></Button>

Body:
You can set your style with Js by following code

const btn = document.querySelector('#boxShadow');
btn.style.boxShadow = '10px 10px 5px grey';

<Button id="boxShadow" text="submit">btn</Button>


问:
react-pdf/renderer IE takes very long time to generate blob to download pdf
```<code>    async function saveBlob() {
        const doc = <TableDocument/>;
        const asPdf = pdf([]);
        await asPdf.updateContainer(doc);
        const blob = await asPdf.toBlob();
        saveAs(blob, 'instructions.pdf');
    }

    return (
        <IconButton
            onClick={() => saveBlob()}>
        </IconButton>
    );
</code>```

This is how I am trying to generate my pdf doc by getting blob and then download it. I am doing all things at client side only using reactJS.

On Chrome and Edge browsers it takes 3-4 seconds only but on IE it takes around 30-40 seconds. Its a 3 page pdf doc with simple table (For single page IE takes around 8-9 seconds).

And even after using async await it blocks the UI.
Any help to reduce time to generate pdf on IE will be highly appreciated.

答:
I found pdfmake(https://pdfmake.github.io/docs/0.1/) library which is very fast in generating pdf from client side. on IE also it takes merely 2 seconds to generate pdf.</p>
```<code>function TablePDF(t, headerGroups, rows, pageName, messageTitle, messageBody, fontLocale, fontMargin, rowFlag) {
  const moreRows = [...rows];

  const createTableHeader = col => {
    const val = t(col.Header);
    return { text: val && val.replace(/<\/br>|<br>/g, '\n'), style: 'tableHeader' };
  };

  const createTableRow = row => {
    const rowElement = [];
    Object.entries(row).map(([key, val]) => {
      if (key === 'notes' || (rowFlag && key === 'fileNameFileReference')) return null;
      const rowCellFormatted =
        key === 'instructionStatus'
          ? mapInstructionStatus(val)
          : key === 'instructionType'
          ? t(mapInstructionTypeStoreData(val))
          : val;

      const cellText =
        (rowCellFormatted &&
          (typeof rowCellFormatted === 'string' && rowCellFormatted.replace(/<\/br>|<br>/g, '\n'))) ||
        rowCellFormatted ||
        '';
      rowElement.push({
        text: cellText,
        margin: [5, fontMargin(getLanguageFont(cellText)), 5, 5],
        font: getLanguageFont(cellText)
      });
      return null;
    });
    return rowElement;
  };

  const getTableHeader = () => {
    const arrOfHeader =
      headerGroups &&
      headerGroups.length &&
      headerGroups[0].headers
        .filter(col => {
          if (
            col.render('Header') === 'ila.notes' ||
            (rowFlag && col.render('Header') === 'ila.fileNameFileReference')
          ) {
            return false;
          }
          return true;
        })
        .map((col, index) => createTableHeader(col, index));
    return arrOfHeader;
  };

  const arrOfHeader = getTableHeader();

  const getTableRows = () => moreRows.map(row => createTableRow(row.values));

  const pdfNote = t('ila.pdfNote');

  const mapInstructionStatus = status => {
    let statusToReturn = '';
    const INSTRUCTION_STATUS = ROW_INSTRUCTION_STATUS;
    switch (status) {
      case 'PA':
        statusToReturn = INSTRUCTION_STATUS[0].label;
        break;
      case 'RA':
        statusToReturn = INSTRUCTION_STATUS[1].label;
        break;
      case 'P2':
        statusToReturn = INSTRUCTION_STATUS[2].label;
        break;
      case 'R2':
        statusToReturn = INSTRUCTION_STATUS[3].label;
        break;
      case 'P3':
        statusToReturn = INSTRUCTION_STATUS[4].label;
        break;
      case 'R3':
        statusToReturn = INSTRUCTION_STATUS[5].label;
        break;
      case 'P4':
        statusToReturn = INSTRUCTION_STATUS[6].label;
        break;
      case 'P5':
        statusToReturn = INSTRUCTION_STATUS[7].label;
        break;
      case 'RB':
        statusToReturn = 'ila.receivedByBank';
        break;
      case 'JB':
        statusToReturn = 'ila.rejectedByBank';
        break;
      case 'JC':
        statusToReturn = 'ila.rejectedByCustomer';
        break;
      case 'RF':
        statusToReturn = 'ila.receivedFwdInstr';
        break;
      default:
        statusToReturn = t(`ila.instructionStatus_${status}`) ? `ila.instructionStatus_${status}` : '';
        break;
    }
    return t(statusToReturn);
  };

  const mapInstructionTypeStoreData = type => {
    switch (type) {
      case 'C0':
      case 'C1':
      case 'PP':
        return 'ila.pp';
      case 'CS':
      case 'COS':
        return 'ila.cos';
      case 'AP':
      case 'ACH':
      case 'APC':
        return 'ila.achCredit';
      case 'AD':
      case 'APD':
        return 'ila.achDebit';
      default:
        return type;
    }
  };

  const tableDoc = {
    pageOrientation: 'landscape',
    pageMargins: [25, 74, 25, 60],
    footer: (currentPage, pageCount) => PDFFooter(pageName, pageCount, currentPage),
    header: () => PDFHeader(fontMargin(fontLocale), pageName),
    content: [
      {
        text: [{ text: messageTitle, bold: true, color: 'black' }, { text: messageBody }, '\n', { text: pdfNote }],
        style: 'note'
      },
      {
        style: 'tableStyle',
        table: {
          headerRows: 1,
          dontBreakRows: true,
          body: [arrOfHeader, ...getTableRows()],
          widths:
            arrOfHeader.length === 9
              ? ['13.3%', '11.3%', '11.3%', '13.3%', '12.3%', '9.1%', '9.1%', '8.6%', '11.6%']
              : ['12.8%', '12.8%', '14.8%', '13.8%', '10.6%', '10.6%', '11.4%', '13.1%']
        },
        layout: {
          vLineWidth: () => 1.2,
          hLineWidth: hLineIndex => (hLineIndex === 1 ? 0 : 1.2),
          hLineColor: () => '#E4E8EA',
          // eslint-disable-next-line no-confusing-arrow
          vLineColor: (i, node, rowIndex) =>
            rowIndex === 0 || (i === 0 || i === arrOfHeader.length) ? 'white' : '#E4E8EA',
          fillColor: rowIndex => (rowIndex === 0 ? '#E4E8EA' : null)
        }
      }
    ],
    styles: {
      tableStyle: {
        margin: [0, fontMargin(fontLocale), 0, 20]
      },
      tableHeader: {
        bold: true,
        color: 'black',
        margin: [5, fontMargin(fontLocale), 5, 5]
      },
      note: {
        lineHeight: 2,
        italics: false
      }
    },
    defaultStyle: {
      columnGap: 10,
      font: fontLocale,
      color: '#333333',
      fontSize: 8
    }
  };
  return tableDoc;
}
export default TablePDF;

const date = new Date();
const gmtString = date.toGMTString();

const finalDate =
  JSON.stringify(gmtString).slice(6, 17) +
  ',' +
  JSON.stringify(gmtString).slice(17, 23) +
  JSON.stringify(gmtString).slice(26, 30);

const PDF_Footer = (pageName, totalPages, pageNumber, reference) => ({
  margin: [30, 20, 30, 10],
  stack: [
    {
      table: {
        headerRows: 1,
        widths: ['*'],
        body: [[''], ['']]
      },
      layout: {
        hLineWidth: i => (i === 0 ? 1 : 0),
        vLineWidth: () => 0,
        hLineColor: () => 'black'
      }
    },
    {
      columns: [
        finalDate + ' | ' + pageName + (reference || ''),
        {
          text: pageNumber && totalPages && `Page ${pageNumber} of ${totalPages}`,
          alignment: 'right'
        }
      ]
    }
  ],
  color: '#333333',
  bold: false
});

export default PDF_Footer;

export function getLanguageFont(text) {
  const universal = /^[a-zA-Z0-9_\-/.!@#$%^&*' 'wığüşöçĞÜŞÖÇİÀ-ÿ/]+$/;
  const arabic = /[\u0600-\u06FF]/;
  const hebrew = /[\u0590-\u05FF]/;
  const greek = /[\u0370-\u03ff\u1f00-\u1fff]/;
  const japanese = /[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/;
  const korean = /[\u3130-\u318F\uAC00-\uD7AF]/g;
  const russian = /[\u0401\u0451\u0410-\u044f]/;
  const vietnamese = /^[a-zA-ZÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂẾưăạảấầẩẫậắằẳẵặẹẻẽềềểếỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ\s\W|_]+$/;
  const chinese = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/;
  if (universal.test(text)) {
    return 'UniverseNextHSBC';
  } else if (arabic.test(text)) {
    return 'arabicFont';
  } else if (hebrew.test(text)) {
    return 'hebrewFont';
  } else if (greek.test(text)) {
    return 'hebrewFont';
  } else if (japanese.test(text)) {
    return 'chineseSimple';
  } else if (korean.test(text)) {
    return 'korean';
  } else if (vietnamese.test(text)) {
    return 'vietnamese';
  } else if (chinese.test(text)) {
    return 'chineseSimple';
  }

  return 'UniverseNextHSBC';
}

      pdfMake.createPdf(tableDoc, null, fontCategories).download(('file.pdf', () => setDownloading(false)));

</code>```

Body:
    async function saveBlob() {
        const doc = <TableDocument/>;
        const asPdf = pdf([]);
        await asPdf.updateContainer(doc);
        const blob = await asPdf.toBlob();
        saveAs(blob, 'instructions.pdf');
    }

    return (
        <IconButton
            onClick={() => saveBlob()}>
        </IconButton>
    );

This is how I am trying to generate my pdf doc by getting blob and then download it. I am doing all things at client side only using reactJS.

On Chrome and Edge browsers it takes 3-4 seconds only but on IE it takes around 30-40 seconds. Its a 3 page pdf doc with simple table (For single page IE takes around 8-9 seconds).

And even after using async await it blocks the UI.
Any help to reduce time to generate pdf on IE will be highly appreciated.

Body:
I found pdfmake(https://pdfmake.github.io/docs/0.1/) library which is very fast in generating pdf from client side. on IE also it takes merely 2 seconds to generate pdf.

function TablePDF(t, headerGroups, rows, pageName, messageTitle, messageBody, fontLocale, fontMargin, rowFlag) {
  const moreRows = [...rows];

  const createTableHeader = col => {
    const val = t(col.Header);
    return { text: val && val.replace(/<\/br>|<br>/g, '\n'), style: 'tableHeader' };
  };

  const createTableRow = row => {
    const rowElement = [];
    Object.entries(row).map(([key, val]) => {
      if (key === 'notes' || (rowFlag && key === 'fileNameFileReference')) return null;
      const rowCellFormatted =
        key === 'instructionStatus'
          ? mapInstructionStatus(val)
          : key === 'instructionType'
          ? t(mapInstructionTypeStoreData(val))
          : val;

      const cellText =
        (rowCellFormatted &&
          (typeof rowCellFormatted === 'string' && rowCellFormatted.replace(/<\/br>|<br>/g, '\n'))) ||
        rowCellFormatted ||
        '';
      rowElement.push({
        text: cellText,
        margin: [5, fontMargin(getLanguageFont(cellText)), 5, 5],
        font: getLanguageFont(cellText)
      });
      return null;
    });
    return rowElement;
  };

  const getTableHeader = () => {
    const arrOfHeader =
      headerGroups &&
      headerGroups.length &&
      headerGroups[0].headers
        .filter(col => {
          if (
            col.render('Header') === 'ila.notes' ||
            (rowFlag && col.render('Header') === 'ila.fileNameFileReference')
          ) {
            return false;
          }
          return true;
        })
        .map((col, index) => createTableHeader(col, index));
    return arrOfHeader;
  };

  const arrOfHeader = getTableHeader();

  const getTableRows = () => moreRows.map(row => createTableRow(row.values));

  const pdfNote = t('ila.pdfNote');

  const mapInstructionStatus = status => {
    let statusToReturn = '';
    const INSTRUCTION_STATUS = ROW_INSTRUCTION_STATUS;
    switch (status) {
      case 'PA':
        statusToReturn = INSTRUCTION_STATUS[0].label;
        break;
      case 'RA':
        statusToReturn = INSTRUCTION_STATUS[1].label;
        break;
      case 'P2':
        statusToReturn = INSTRUCTION_STATUS[2].label;
        break;
      case 'R2':
        statusToReturn = INSTRUCTION_STATUS[3].label;
        break;
      case 'P3':
        statusToReturn = INSTRUCTION_STATUS[4].label;
        break;
      case 'R3':
        statusToReturn = INSTRUCTION_STATUS[5].label;
        break;
      case 'P4':
        statusToReturn = INSTRUCTION_STATUS[6].label;
        break;
      case 'P5':
        statusToReturn = INSTRUCTION_STATUS[7].label;
        break;
      case 'RB':
        statusToReturn = 'ila.receivedByBank';
        break;
      case 'JB':
        statusToReturn = 'ila.rejectedByBank';
        break;
      case 'JC':
        statusToReturn = 'ila.rejectedByCustomer';
        break;
      case 'RF':
        statusToReturn = 'ila.receivedFwdInstr';
        break;
      default:
        statusToReturn = t(`ila.instructionStatus_${status}`) ? `ila.instructionStatus_${status}` : '';
        break;
    }
    return t(statusToReturn);
  };

  const mapInstructionTypeStoreData = type => {
    switch (type) {
      case 'C0':
      case 'C1':
      case 'PP':
        return 'ila.pp';
      case 'CS':
      case 'COS':
        return 'ila.cos';
      case 'AP':
      case 'ACH':
      case 'APC':
        return 'ila.achCredit';
      case 'AD':
      case 'APD':
        return 'ila.achDebit';
      default:
        return type;
    }
  };

  const tableDoc = {
    pageOrientation: 'landscape',
    pageMargins: [25, 74, 25, 60],
    footer: (currentPage, pageCount) => PDFFooter(pageName, pageCount, currentPage),
    header: () => PDFHeader(fontMargin(fontLocale), pageName),
    content: [
      {
        text: [{ text: messageTitle, bold: true, color: 'black' }, { text: messageBody }, '\n', { text: pdfNote }],
        style: 'note'
      },
      {
        style: 'tableStyle',
        table: {
          headerRows: 1,
          dontBreakRows: true,
          body: [arrOfHeader, ...getTableRows()],
          widths:
            arrOfHeader.length === 9
              ? ['13.3%', '11.3%', '11.3%', '13.3%', '12.3%', '9.1%', '9.1%', '8.6%', '11.6%']
              : ['12.8%', '12.8%', '14.8%', '13.8%', '10.6%', '10.6%', '11.4%', '13.1%']
        },
        layout: {
          vLineWidth: () => 1.2,
          hLineWidth: hLineIndex => (hLineIndex === 1 ? 0 : 1.2),
          hLineColor: () => '#E4E8EA',
          // eslint-disable-next-line no-confusing-arrow
          vLineColor: (i, node, rowIndex) =>
            rowIndex === 0 || (i === 0 || i === arrOfHeader.length) ? 'white' : '#E4E8EA',
          fillColor: rowIndex => (rowIndex === 0 ? '#E4E8EA' : null)
        }
      }
    ],
    styles: {
      tableStyle: {
        margin: [0, fontMargin(fontLocale), 0, 20]
      },
      tableHeader: {
        bold: true,
        color: 'black',
        margin: [5, fontMargin(fontLocale), 5, 5]
      },
      note: {
        lineHeight: 2,
        italics: false
      }
    },
    defaultStyle: {
      columnGap: 10,
      font: fontLocale,
      color: '#333333',
      fontSize: 8
    }
  };
  return tableDoc;
}
export default TablePDF;

const date = new Date();
const gmtString = date.toGMTString();

const finalDate =
  JSON.stringify(gmtString).slice(6, 17) +
  ',' +
  JSON.stringify(gmtString).slice(17, 23) +
  JSON.stringify(gmtString).slice(26, 30);

const PDF_Footer = (pageName, totalPages, pageNumber, reference) => ({
  margin: [30, 20, 30, 10],
  stack: [
    {
      table: {
        headerRows: 1,
        widths: ['*'],
        body: [[''], ['']]
      },
      layout: {
        hLineWidth: i => (i === 0 ? 1 : 0),
        vLineWidth: () => 0,
        hLineColor: () => 'black'
      }
    },
    {
      columns: [
        finalDate + ' | ' + pageName + (reference || ''),
        {
          text: pageNumber && totalPages && `Page ${pageNumber} of ${totalPages}`,
          alignment: 'right'
        }
      ]
    }
  ],
  color: '#333333',
  bold: false
});

export default PDF_Footer;

export function getLanguageFont(text) {
  const universal = /^[a-zA-Z0-9_\-/.!@#$%^&*' 'wığüşöçĞÜŞÖÇİÀ-ÿ/]+$/;
  const arabic = /[\u0600-\u06FF]/;
  const hebrew = /[\u0590-\u05FF]/;
  const greek = /[\u0370-\u03ff\u1f00-\u1fff]/;
  const japanese = /[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/;
  const korean = /[\u3130-\u318F\uAC00-\uD7AF]/g;
  const russian = /[\u0401\u0451\u0410-\u044f]/;
  const vietnamese = /^[a-zA-ZÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂẾưăạảấầẩẫậắằẳẵặẹẻẽềềểếỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ\s\W|_]+$/;
  const chinese = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/;
  if (universal.test(text)) {
    return 'UniverseNextHSBC';
  } else if (arabic.test(text)) {
    return 'arabicFont';
  } else if (hebrew.test(text)) {
    return 'hebrewFont';
  } else if (greek.test(text)) {
    return 'hebrewFont';
  } else if (japanese.test(text)) {
    return 'chineseSimple';
  } else if (korean.test(text)) {
    return 'korean';
  } else if (vietnamese.test(text)) {
    return 'vietnamese';
  } else if (chinese.test(text)) {
    return 'chineseSimple';
  }

  return 'UniverseNextHSBC';
}

      pdfMake.createPdf(tableDoc, null, fontCategories).download(('file.pdf', () => setDownloading(false)));


问:
split a number and populate N number of fields in react
for example if we take a number 100 and the  user has three fields when user enters a number say 20 in one of the fields the other two fields should populate with the numbers 40 and 40 as 40+40+20 = 100. Unable to think of a logic which would help me solve this.This is just an example, the number of fields can be considered as N where N = 1,2,3,4 etc .</p>

答:
Seems straightforward, so I might be overlooking the point?

So, first we get whatever element the user interacted with. We could use either onChange, which will fire everytime the user changes the input, or onBlur which fires when the element loses focus, i.e. submits the form or selects the next input. Then we simply get the event.target.value, which in your presented case is 20.

Get the rest of the inputs by either storing a ref to their parent and getting said parents .children, or by using document.querySelectorAll(".some-selector"), iterate over the nodelist, skip any entry with a .value !== null and add 100 - 20 / (nodeList.length - 1) as the .value of the remaining entries.

I would probably use the ref route.


问:
SUMIFS where one of the conditions is at the top of table | Microsoft Excel
Sample: Two tables in one excel sheet.

Criteria 1:

```<code>ColumnA | ColumnB
Name    | Amount
John    | 3
Smith   | 2
John    | 6
</code>```

Criteria 2:

```<code>Name    | Amount
John    | 10
Smith   | 20
</code>```

I would like to perform => SUMIFS range is B:B and where the table name is "Criteria 1".

Note: there are a lot more names and criteria #.

答:
Have you tried in this way? So what i have done is, i have created a Defined Named Ranges for Criteria 1 and use the same within an INDEX Function so that gives a range which can be used within SUMIFS Function - SUM_RANGE & CRITERIA RANGE

So the formula used in Cell B7

```<code>=SUMIFS(INDEX(Criteria_1,,2),INDEX(Criteria_1,,1),$A7)
</code>```

Where Criteria_1 is Defined Named Ranges, how to create it, follow the steps

• Select the whole range i.e. in the image below, A2:B4

• Press ALT F3 and in the NAME BOX write Criteria_1

This is one way to define a range -->

The other way is select the range from Formulas Tab, Under Defined Names Group select Define Name. A new pop up shows --> Name it as Criteria_1 and refers to already has been selected as the range required, and press OK

Therefore as per the sample provided in my sheet the

```<code>Where Criteria_1 is ='Blad (24)'!$A$2:$B$4
</code>```

Blad is sheet name so don't get confused!

Body:
Sample: Two tables in one excel sheet.

Criteria 1:

ColumnA | ColumnB
Name    | Amount
John    | 3
Smith   | 2
John    | 6

Criteria 2:

Name    | Amount
John    | 10
Smith   | 20

I would like to perform => SUMIFS range is B:B and where the table name is "Criteria 1".

Note: there are a lot more names and criteria #.

Body:
Have you tried in this way? So what i have done is, i have created a Defined Named Ranges for Criteria 1 and use the same within an INDEX Function so that gives a range which can be used within SUMIFS Function - SUM_RANGE & CRITERIA RANGE

So the formula used in Cell B7

=SUMIFS(INDEX(Criteria_1,,2),INDEX(Criteria_1,,1),$A7)

Where Criteria_1 is Defined Named Ranges, how to create it, follow the steps

• Select the whole range i.e. in the image below, A2:B4

• Press ALT F3 and in the NAME BOX write Criteria_1

This is one way to define a range -->

The other way is select the range from Formulas Tab, Under Defined Names Group select Define Name. A new pop up shows --> Name it as Criteria_1 and refers to already has been selected as the range required, and press OK

Therefore as per the sample provided in my sheet the

Where Criteria_1 is ='Blad (24)'!$A$2:$B$4

Blad is sheet name so don't get confused!


问:
Materialize CSS - multiple select with disabled selected issue
Even on official MaterializeCSS page for Select when you select a value for multiple select you see the disabled selected "Choose your Option" and then the selected option(s).

It seems to me more user friendly to shoe only Option 1 as "Choose your option" is not a valid option.

I use the

```<code>      <option value="" disabled selected>Choose your option</option>
</code>```

so once page is rendered the user got a hint what is required of them.

Working jsFiddle.

It seems to me that using jQuery solves this issue (see an example) but I am using pure javascript only.

So the question is How to not display disabled, selected text for multiple MaterializeCSS select.

答:
Copied from your js fiddle , this will fix your unselect issue.</p>
```<code>function  onSelectChange(s){
  const elOptions = s.querySelectorAll('option')
  elOptions[0].removeAttribute('selected') // this won't work
  elOptions[0].selected  = false; ///this will - tested //first option will be unselected
}
</code>```

Body:
Even on official MaterializeCSS page for Select when you select a value for multiple select you see the disabled selected "Choose your Option" and then the selected option(s).

It seems to me more user friendly to shoe only Option 1 as "Choose your option" is not a valid option.

I use the

      <option value="" disabled selected>Choose your option</option>

so once page is rendered the user got a hint what is required of them.

Working jsFiddle.

It seems to me that using jQuery solves this issue (see an example) but I am using pure javascript only.

So the question is How to not display disabled, selected text for multiple MaterializeCSS select.

Body:
Copied from your js fiddle , this will fix your unselect issue.

function  onSelectChange(s){
  const elOptions = s.querySelectorAll('option')
  elOptions[0].removeAttribute('selected') // this won't work
  elOptions[0].selected  = false; ///this will - tested //first option will be unselected
}


问:
Python Business hours calculation - add hours and result should be business opening hours
I'm developing a small app in Python with Flask

I've looked but maybe not hard enough to find a Python library that will help me do the following:

I want to add X hours to the current time. If the result goes outside of business hours then the result will be the time X business open hours from now.

For example, if a business operated between 9 am and 5 pm on weekdays. The current time is Friday 4 pm and I add 6 hours, the result should be 2 pm on the following Monday. If for some reason the Monday is a public holiday it is pushed out to Tuesday.

My use case is that if a job is logged, depending on the priority of the job, it has to be completed within a certain period of time. But that time has to be calculated in working hours.

I'm hoping there is a simple way to do this (pre-existing library) as it seems like such a common thing to do.

Edit: I forgot to mention, I've looked at the following packages:

date-time

time

calendar

business-duration

Edit 2: Still playing with it but I think I have found a library that does exactly what I want:

```<code> sla-calculator 1.0.0
</code>```

There is also this:

```<code>sla-checker 0.0.2
</code>```

答:
I don't think there is a need for a library for that. This can be refined, as I haven't thought of any edge cases, but you get the idea.

Example at the end 11.02.2022, 16:00 + 6 hours = 14.02.2022 12:00 (with business hours monday - friday, 8am - 6pm).

from datetime import datetime, timedelta, date, time

business_hours = {
    # monday = 0, tuesday = 1, ... same pattern as date.weekday()
    "weekdays": [0, 1, 2, 3, 4],
    "from": time(hour=8),
    "to": time(hour=18)
}
holidays = [date(2022, 2, 25), date(2022, 2, 24)]

def is_in_open_hours(dt):
    return dt.weekday() in business_hours["weekdays"] \
           and dt.date() not in holidays \
           and business_hours["from"].hour <= dt.time().hour < business_hours["to"].hour

def get_next_open_datetime(dt):
    while True:
        dt = dt + timedelta(days=1)
        if dt.weekday() in business_hours["weekdays"] and dt.date() not in holidays:
            dt = datetime.combine(dt.date(), business_hours["from"])
            return dt

def add_hours(dt, hours):
    while hours != 0:
        if is_in_open_hours(dt):
            dt = dt + timedelta(hours=1)
            hours = hours - 1
        else:
            dt = get_next_open_datetime(dt)
    return dt

dt_test = datetime(2022, 2, 11, 16)
print(add_hours(dt_test, 6))
```

Body:
I'm developing a small app in Python with Flask

I've looked but maybe not hard enough to find a Python library that will help me do the following:

I want to add X hours to the current time. If the result goes outside of business hours then the result will be the time X business open hours from now.

For example, if a business operated between 9 am and 5 pm on weekdays. The current time is Friday 4 pm and I add 6 hours, the result should be 2 pm on the following Monday. If for some reason the Monday is a public holiday it is pushed out to Tuesday.

My use case is that if a job is logged, depending on the priority of the job, it has to be completed within a certain period of time. But that time has to be calculated in working hours.

I'm hoping there is a simple way to do this (pre-existing library) as it seems like such a common thing to do.

Edit: I forgot to mention, I've looked at the following packages:

date-time

time

calendar

business-duration

Edit 2: Still playing with it but I think I have found a library that does exactly what I want:

 sla-calculator 1.0.0

There is also this:

sla-checker 0.0.2


问:
Mint new ERC20 token from other smart contract
Recently I am facing an issue while working on a smart contract that has staking functionality. Through the IERC20 interface, I manage to interact with Erc20 token from another contract but there is still one confusion left.
I am working on a smart contract in which users can stake my token(token is already deployed in network) in smart contract and when the staking duration ends stakeholder can get their staking amount along with the rewarded token. For rewarded tokens
I want to mint new tokens to give rewards to the stakeholder in my smart contract.
How can I use the mint function in another smart contract?
I want to use the Erc20 mint function in my staking smart contract.
Waiting for your positive response.

```<code>IERC20 private _token;
constructor(IERC20 token) {
    _mytoken = token;

  }
</code>```

transfer and approve is working perfectly but there is no option of mint in IERC20

```<code> _mytoken.approve(address(this),quantity);
 _mytoken.safeTransferFrom(msg.sender,address(this),quantity);
</code>```

答:
IERC20 does not contain _mint but ERC20 does so you inherit from ERC20

```<code>contract RewardToken is ERC20 {
    constructor() public ERC20("Reward Token","RWD"){
        // give initial supply 1million + 18 zeros
        _mint(msg.sender,1000000000000000000000000);
    }
</code>```

Your RewardToken has _mint functionality and it can still inherit from IERC20. But you have an initialization mistake in your constructor:

```<code>constructor(IERC20 token) {
    // you have to initialize with IERC20
    _mytoken = IERC20(token);
  }
</code>```

Body:
Recently I am facing an issue while working on a smart contract that has staking functionality. Through the IERC20 interface, I manage to interact with Erc20 token from another contract but there is still one confusion left.
I am working on a smart contract in which users can stake my token(token is already deployed in network) in smart contract and when the staking duration ends stakeholder can get their staking amount along with the rewarded token. For rewarded tokens
I want to mint new tokens to give rewards to the stakeholder in my smart contract.
How can I use the mint function in another smart contract?
I want to use the Erc20 mint function in my staking smart contract.
Waiting for your positive response.

IERC20 private _token;
constructor(IERC20 token) {
    _mytoken = token;

  }

transfer and approve is working perfectly but there is no option of mint in IERC20

 _mytoken.approve(address(this),quantity);
 _mytoken.safeTransferFrom(msg.sender,address(this),quantity);

Body:
IERC20 does not contain _mint but ERC20 does so you inherit from ERC20

contract RewardToken is ERC20 {
    constructor() public ERC20("Reward Token","RWD"){
        // give initial supply 1million + 18 zeros
        _mint(msg.sender,1000000000000000000000000);
    }

Your RewardToken has _mint functionality and it can still inherit from IERC20. But you have an initialization mistake in your constructor:

constructor(IERC20 token) {
    // you have to initialize with IERC20
    _mytoken = IERC20(token);
  }


问:
How to access LocalComponent.current in Composable Buttons onClick?
I have a Button and I would like to access LocalComponents.current in its onClick

```<code>Button(onClick = {
    with(LocalRootComponent) {
        current.doStuff()
    }
})
</code>```

but IDE complains with

@Composable invocations can only happen from the context of a
@Composable function

答:
You can access and store that object outside the onClick method, and then use that variable inside onClick , e.g.:

```<code>val rootComponent = LocalRootComponent.current

Button(onClick = {
    rootComponent.doStuff()
})
</code>```

Body:
I have a Button and I would like to access LocalComponents.current in its onClick

Button(onClick = {
    with(LocalRootComponent) {
        current.doStuff()
    }
})

but IDE complains with

@Composable invocations can only happen from the context of a
@Composable function

Body:
You can access and store that object outside the onClick method, and then use that variable inside onClick , e.g.:

val rootComponent = LocalRootComponent.current

Button(onClick = {
    rootComponent.doStuff()
})


问:
Does JavaScript provide a history of prior events that occurred?
I was wondering if JavaScript records information about the prior events that occurred so that I could use the information to perform a specific course of action in the current event?

For example, I have an element that has an OnBlur event handler, but I would like to know the event that occurred prior to the OnBlur event that triggered the OnBlur event to occur, such as the user pressing the Tab key, arrow key, or mouse click that moved focus away from the element.

So does JavaScript provide any mechanism to facilitate access to the events history or can people throw ideas to me at good ways of implementing this?

答: You could bind to any event on the object and maintain that event on the object for the next event handler.  Here is a jsfiddle that shows a binding to many events and storing the last event type on the object.  There is also a click event handler that makes a decision based on the last event saved on the object:  http://jsfiddle.net/xEjGA/</p>


问:
Repeated record to one string, BigQuery
I have a table that contains query jobs, with a repeated record colomn referenced_tables. There are 3 colomns and several rows inside this record, and I would like to transform the whole record into a single string, with a seperator for the colomns '.' and ',' for the rows. The colomns inside the record are project, dataset and table id's (string), and each row is a different table. I am trying something like this :

```<code>select array_to_string(
    [
        array_to_string(
            [
                referenced_tables[ordinal(1)].project_id,
                referenced_tables[ordinal(1)].dataset_id,
                referenced_tables[ordinal(1)].table_id
            ], "."
        ),
        array_to_string(
            [
                referenced_tables[ordinal(2)].project_id,
                referenced_tables[ordinal(2)].dataset_id,
                referenced_tables[ordinal(2)].table_id
            ], "."
        )
    ], ", "
)
FROM my_table
</code>```

The result of this is like : project1.dataset1.table1,project2.dataset2.table2 when i specify a job. So it works but I have to repeat the array_to_string as much as there are rows, and of course the number of rows changes from a job to another, and referenced_tables can be NULL, so if i do this on the whole table, an error will occur.

Is there a way to transform the records into strings, for the whole table, with my conditions ?

答:
I made some assumptions about how your data is structured.  Given you said this is by query there is some kind of query_id associated to group by.

Try the following

```<code>select
  string_agg(concat(t.project_id,".",t.dataset_id,".",t.table_id),", ")
from sample_data
, unnest(referenced_tables) t
</code>```

With the following sample data:

```<code>with sample_data as (
    select 1 as query_id
        , [STRUCT('my_project' as project_id, 'my_dataset' as dataset_id, 'table' as table_id)
           ,STRUCT('my_project1' as project_id, 'my_datase1' as dataset_id, 'table1' as table_id)
           ,STRUCT('my_projec2' as project_id, 'my_dataset2' as dataset_id, 'table2' as table_id)
           ] as referenced_tables
    UNION ALL
    select 2
        , [STRUCT('my_project3' as project_id, 'my_dataset3' as dataset_id, 'table3' as table_id)
           ,STRUCT('my_project4' as project_id, 'my_datase4' as dataset_id, 'table4' as table_id)
           ,STRUCT('my_projec5' as project_id, 'my_dataset5' as dataset_id, 'table5' as table_id)
           ] as referenced_tables
)
</code>```

It produces

Title: Repeated record to one string, BigQuery

Body:
I have a table that contains query jobs, with a repeated record colomn referenced_tables. There are 3 colomns and several rows inside this record, and I would like to transform the whole record into a single string, with a seperator for the colomns '.' and ',' for the rows. The colomns inside the record are project, dataset and table id's (string), and each row is a different table. I am trying something like this :

select array_to_string(
    [
        array_to_string(
            [
                referenced_tables[ordinal(1)].project_id,
                referenced_tables[ordinal(1)].dataset_id,
                referenced_tables[ordinal(1)].table_id
            ], "."
        ),
        array_to_string(
            [
                referenced_tables[ordinal(2)].project_id,
                referenced_tables[ordinal(2)].dataset_id,
                referenced_tables[ordinal(2)].table_id
            ], "."
        )
    ], ", "
)
FROM my_table

The result of this is like : project1.dataset1.table1,project2.dataset2.table2 when i specify a job. So it works but I have to repeat the array_to_string as much as there are rows, and of course the number of rows changes from a job to another, and referenced_tables can be NULL, so if i do this on the whole table, an error will occur.

Is there a way to transform the records into strings, for the whole table, with my conditions ?

Body:
I made some assumptions about how your data is structured.  Given you said this is by query there is some kind of query_id associated to group by.

Try the following

select
  string_agg(concat(t.project_id,".",t.dataset_id,".",t.table_id),", ")
from sample_data
, unnest(referenced_tables) t

With the following sample data:

with sample_data as (
    select 1 as query_id
        , [STRUCT('my_project' as project_id, 'my_dataset' as dataset_id, 'table' as table_id)
           ,STRUCT('my_project1' as project_id, 'my_datase1' as dataset_id, 'table1' as table_id)
           ,STRUCT('my_projec2' as project_id, 'my_dataset2' as dataset_id, 'table2' as table_id)
           ] as referenced_tables
    UNION ALL
    select 2
        , [STRUCT('my_project3' as project_id, 'my_dataset3' as dataset_id, 'table3' as table_id)
           ,STRUCT('my_project4' as project_id, 'my_datase4' as dataset_id, 'table4' as table_id)
           ,STRUCT('my_projec5' as project_id, 'my_dataset5' as dataset_id, 'table5' as table_id)
           ] as referenced_tables
)

It produces


问:
How to put icon inside an input box
Can anyone help me to put the tick icon inside the input box at right corner?

Also is it possible to display a 'Field Saved' message along with the tick icon?

Update:

What if form contains multiple input in single row, then how to show icon inside the input boxes?

Fiddle: https://jsfiddle.net/sanadqazi/5Len09ad/1/

.test {
  position: relative;
}

.test .fas.fa-check {
  position: absolute;
  top: 0;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

<div class="row">
  <div class="col-8">
    <div class="test">
      <input type="text">
      <i class="fas fa-check inp"></i>
    </div>
  </div>
  <div class="col-4">
    <div class="test">
      <input type="text">
      <i class="fas fa-check inp"></i>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script></code>```

答:
A little bit of CSS should do the trick here.

Either add the following code snippet to a stylesheet or to a style block. Alternatively, you could apply the styles inline, directly on the HTML elements themselves.

CSS:

```<code>.test {
  position: relative;
}

.test .fas.fa-check {
  position: absolute;
  top: 0;
  right: 0;
}
</code>```

UPDATE

If the form contains multiple select boxes in the same row, then they must be wrapped in a div which has relative positioning and inline display.

Title: How to put icon inside an input box

Body:
Can anyone help me to put the tick icon inside the input box at right corner?

Also is it possible to display a 'Field Saved' message along with the tick icon?

Update:

What if form contains multiple input in single row, then how to show icon inside the input boxes?

Fiddle: https://jsfiddle.net/sanadqazi/5Len09ad/1/

.test {
  position: relative;
}

.test .fas.fa-check {
  position: absolute;
  top: 0;
  right: 0;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

      <input type="text">

      <input type="text">

Body:
A little bit of CSS should do the trick here.

Either add the following code snippet to a stylesheet or to a style block. Alternatively, you could apply the styles inline, directly on the HTML elements themselves.

CSS:

.test {
  position: relative;
}

.test .fas.fa-check {
  position: absolute;
  top: 0;
  right: 0;
}

UPDATE

If the form contains multiple select boxes in the same row, then they must be wrapped in a div which has relative positioning and inline display.


问:
BeyondCompare git difftool -d closes immediately without waiting for user
Note: this is similar to WebStorm git difftool -d closes immediately without waiting for user, but for Beyond Compare

When I run git difftool -d with Beyond Compare set as my default difftool, git closes right away without letting Beyond Compare show any comparisons. How do I fix that?

答:
There are chances, that your version of Beyond Compare does not work as expected.  See discussion Scooter's forum.  Check at commandline prompt if

bcomp file1 file2 waits until closing the window.

bcomp dir1 dir2 waits until closing the window.

bcompare -solo dir1 dir2 waits until closing the window.

(1) probably works.

(2) Is not expected to wait, according to the forum.

(3) I found that this does not work either, although it should, according to command line reference.

If even (3) does not help, you can edit mergetools/bc file.  Add this line to the end of diff_cmd():

```<code>[ -d "$LOCAL" -o -d "$REMOTE" ] && [ -t 0 ] && read -p "Press ENTER to continue..."
</code>```

Location of the file is /lib/git-core/mergetools/bc or something similar.  In my gitforwindows, it is c:\Program Files\Git\mingw64\libexec\git-core\mergetools\bc.

Body:
There are chances, that your version of Beyond Compare does not work as expected.  See discussion Scooter's forum.  Check at commandline prompt if

bcomp file1 file2 waits until closing the window.

bcomp dir1 dir2 waits until closing the window.

bcompare -solo dir1 dir2 waits until closing the window.

(1) probably works.

(2) Is not expected to wait, according to the forum.

(3) I found that this does not work either, although it should, according to command line reference.

If even (3) does not help, you can edit mergetools/bc file.  Add this line to the end of diff_cmd():

[ -d "$LOCAL" -o -d "$REMOTE" ] && [ -t 0 ] && read -p "Press ENTER to continue..."

Location of the file is /lib/git-core/mergetools/bc or something similar.  In my gitforwindows, it is c:\Program Files\Git\mingw64\libexec\git-core\mergetools\bc.