问:
run f# code on server even when f# is not installed there
is it possible to run f# code on server if it's not installed there (shared server)? I mean maybe I can upload and reference all the necessary assemblies? f# download place contains zip for "other cli implementations" - maybe someone had simillar issues?

Edit More context: actually I'm using c# to compile and run f# program. So I call

using (CodeDomProvider provider = new Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider())
{
  cr = provider.CompileAssemblyFromSource(cp, new string[] { data.Program });
}
```

<p>Now on my machine everything is fine. I have included FSharp.Core.dll (version 4) as well as FSharp.Compiler.CodeDom (version 2). Everything is copied locally. On server I get this error:</p>

<pre class="lang-none prettyprint-override"><code>Could not load file or assembly 'FSharp.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  at Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider.CreateCompiler()
  at System.CodeDom.Compiler.CodeDomProvider.CreateCompilerHelper()
  at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)...
</code>```

Edit2:
So actually I wanted to compile f# code on a server with no f# installed. Here is what I had to do:

```<code>1. put FSharp.Compiler.CodeDom.dll (version 2 as there is now newer now) and FSharp.Core.dll version 2 in bin directory.
2. create new directory in bin directory and put there this:
-FSharp.Compiler.dll (version 4)
-FSharp.Core (.dll, .xml, .sigdata, .optdata) (version 4)
-Fsc.exe - f# compiler
3. From code set process' FSHARP_BIN environment variable to point to above directory:
System.Environment.SetEnvironmentVariable("FSHARP_BIN", Utils.RootFolder + @"bin\comilersstuff");
</code>```

This way compilation is successful and if you'd want to run it, you'd had to put Fsharp.Core.dll (v. 4)  in the same directory as compiled F# program.

答:
of course - just copy the FSharp-Dlls with your project or use the --standalone compiler option. Of course you will need the .net (4.0/3.5/2.0 depending of your F#-version) Framework on your server.

Easiest way to do the first: use the "Copy Local" settings for the References - the Dll will be put beside your .exe/.dll in the bin folder (or whereever you let your output go):

Body:
is it possible to run f# code on server if it's not installed there (shared server)? I mean maybe I can upload and reference all the necessary assemblies? f# download place contains zip for "other cli implementations" - maybe someone had simillar issues?

Edit More context: actually I'm using c# to compile and run f# program. So I call

using (CodeDomProvider provider = new Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider())
{
  cr = provider.CompileAssemblyFromSource(cp, new string[] { data.Program });
}

Now on my machine everything is fine. I have included FSharp.Core.dll (version 4) as well as FSharp.Compiler.CodeDom (version 2). Everything is copied locally. On server I get this error:

Could not load file or assembly 'FSharp.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
  at Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider.CreateCompiler()
  at System.CodeDom.Compiler.CodeDomProvider.CreateCompilerHelper()
  at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(CompilerParameters options, String[] sources)...

Edit2:
So actually I wanted to compile f# code on a server with no f# installed. Here is what I had to do:

1. put FSharp.Compiler.CodeDom.dll (version 2 as there is now newer now) and FSharp.Core.dll version 2 in bin directory.
2. create new directory in bin directory and put there this:
-FSharp.Compiler.dll (version 4)
-FSharp.Core (.dll, .xml, .sigdata, .optdata) (version 4)
-Fsc.exe - f# compiler
3. From code set process' FSHARP_BIN environment variable to point to above directory:
System.Environment.SetEnvironmentVariable("FSHARP_BIN", Utils.RootFolder + @"bin\comilersstuff");

This way compilation is successful and if you'd want to run it, you'd had to put Fsharp.Core.dll (v. 4)  in the same directory as compiled F# program.


来源: stackexchange

问:
Can I add background color only for padding?
I have a header box including border and padding and background color for that box,
can I change the background color only for the padded region after the border and then the same background color for the rest of the width (i.e. grey in the given code)?

Just a pinch of the code where I want the padded background color:

```<code>nav {
    margin:0px auto;
    width:100%;
    height:50px;
    background-color:grey;
    float:left;
    padding:10px;
    border:2px solid red;
}
</code>```

答:
in case you don't want to affect the content background, and you have different padding for each direction, use the following:

div {
  width: 440px;
  padding: 10px 20px 30px 40px;
  box-shadow: inset 0 10px 0 0 lightGreen, inset -20px 0 0 0 lightGreen, inset 0 -30px 0 0 lightGreen, inset 40px 0 0 0 lightGreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>The light green background color shows the padding of the element</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a header box including border and padding and background color for that box,
can I change the background color only for the padded region after the border and then the same background color for the rest of the width (i.e. grey in the given code)?

Just a pinch of the code where I want the padded background color:

nav {
    margin:0px auto;
    width:100%;
    height:50px;
    background-color:grey;
    float:left;
    padding:10px;
    border:2px solid red;
}

Body:
in case you don't want to affect the content background, and you have different padding for each direction, use the following:

div {
  width: 440px;
  padding: 10px 20px 30px 40px;
  box-shadow: inset 0 10px 0 0 lightGreen, inset -20px 0 0 0 lightGreen, inset 0 -30px 0 0 lightGreen, inset 40px 0 0 0 lightGreen;
}

<div>The light green background color shows the padding of the element</div>

ContentLicense: CC BY-SA 4.0


问:
why does `nix flake show` builds ghc?
If I look at the outputs provided by the haskell.nix flake from a M1 computer, it starts building ghc-8.8.4 etc..

```<code>❯ nix flake show github:input-output-hk/haskell.nix
github:input-output-hk/haskell.nix/1b54ea01568299a0eda578ae9395e20d5c699ee1
├───checks
│   ├───aarch64-darwin
trace: haskell-nix.haskellLib.cleanGit: /nix/store/jmx2m0ldgrjq7p3gb4yyca47nvbvspfl-source does not seem to be a git repository,
assuming it is a clean checkout.
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: WARNING: No materialized dummy-ghc-data for ghc-8.8.4-aarch64-darwin.
trace: To make this a fixed-output derivation but not materialized, set `sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize this entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
[1/0/579 built, 0.1 MiB DL] building ghc-8.8.4 (buildPhase):.....
</code>```

From an Intel Mac, I get

```<code>❯ nix flake show github:input-output-hk/haskell.nix
github:input-output-hk/haskell.nix/1b54ea01568299a0eda578ae9395e20d5c699ee1
├───checks
│   ├───aarch64-darwin
trace: haskell-nix.haskellLib.cleanGit: /nix/store/jmx2m0ldgrjq7p3gb4yyca47nvbvspfl-source does not seem to be a git repository,
assuming it is a clean checkout.
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
error: --- Error ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- nix
a 'aarch64-darwin' with features {} is required to build '/nix/store/sc11rh4l348yw3z4q4fy4byw324nm5yz-nix-tools-plan-to-nix-pkgs.drv', but I am a 'x86_64-darwin' with features {benchmark, big-parallel, nixos-test, recursive-nix}
(use '--show-trace' to show detailed location information)
</code>```

Why do those flakes need to build anything for showing their outputs ?

If I run this command on some other flake I have, after a few fetches :

```<code>❯ nix flake show github:edolstra/dwarffs
github:edolstra/dwarffs/69d73417d83ebeb7711912e33515d87049b39de0
├───checks
│   ├───aarch64-linux
│   │   ├───build: derivation 'dwarffs-0.1.20220128.69d7341'
│   │   └───test: derivation 'vm-test-run-unnamed'
│   ├───i686-linux
│   │   ├───build: derivation 'dwarffs-0.1.20220128.69d7341'
│   │   └───test: derivation 'vm-test-run-unnamed'
│   └───x86_64-linux
│       ├───build: derivation 'dwarffs-0.1.20220128.69d7341'
│       └───test: derivation 'vm-test-run-unnamed'
├───defaultPackage
│   ├───aarch64-linux: package 'dwarffs-0.1.20220128.69d7341'
│   ├───i686-linux: package 'dwarffs-0.1.20220128.69d7341'
│   └───x86_64-linux: package 'dwarffs-0.1.20220128.69d7341'
├───nixosModules
│   └───dwarffs: NixOS module
└───overlay: Nixpkgs overlay
</code>```

答:
haskell.nix depends heavily on what is commonly called "import from derivation" or IFD. These are expressions such as

foo = import "${mkDerivation bar}/expr.nix";
```
<p>or</p>
<pre class="lang-hs prettyprint-override"><code>qux = builtins.readFile (somePackage + "/data.json");
</code>```

These can not be evaluated without building bar and somePackage.

haskell.nix does have a feature that lets you avoid such expressions altogether. They've called it materialization.

Title: why does `nix flake show` builds ghc?

Body:
If I look at the outputs provided by the haskell.nix flake from a M1 computer, it starts building ghc-8.8.4 etc..

❯ nix flake show github:input-output-hk/haskell.nix
github:input-output-hk/haskell.nix/1b54ea01568299a0eda578ae9395e20d5c699ee1
├───checks
│   ├───aarch64-darwin
trace: haskell-nix.haskellLib.cleanGit: /nix/store/jmx2m0ldgrjq7p3gb4yyca47nvbvspfl-source does not seem to be a git repository,
assuming it is a clean checkout.
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: WARNING: No materialized dummy-ghc-data for ghc-8.8.4-aarch64-darwin.
trace: To make this a fixed-output derivation but not materialized, set `sha256` to the output of the 'calculateMaterializedSha' script in 'passthru'.
trace: To materialize this entirely, pass a writable path as the `materialized` argument and run the 'updateMaterialized' script in 'passthru'.
[1/0/579 built, 0.1 MiB DL] building ghc-8.8.4 (buildPhase):.....

From an Intel Mac, I get

❯ nix flake show github:input-output-hk/haskell.nix
github:input-output-hk/haskell.nix/1b54ea01568299a0eda578ae9395e20d5c699ee1
├───checks
│   ├───aarch64-darwin
trace: haskell-nix.haskellLib.cleanGit: /nix/store/jmx2m0ldgrjq7p3gb4yyca47nvbvspfl-source does not seem to be a git repository,
assuming it is a clean checkout.
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
trace: No index state specified for haskell-project, using the latest index state that we know about (2022-02-07T00:00:00Z)!
error: --- Error ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- nix
a 'aarch64-darwin' with features {} is required to build '/nix/store/sc11rh4l348yw3z4q4fy4byw324nm5yz-nix-tools-plan-to-nix-pkgs.drv', but I am a 'x86_64-darwin' with features {benchmark, big-parallel, nixos-test, recursive-nix}
(use '--show-trace' to show detailed location information)

Why do those flakes need to build anything for showing their outputs ?

If I run this command on some other flake I have, after a few fetches :

❯ nix flake show github:edolstra/dwarffs
github:edolstra/dwarffs/69d73417d83ebeb7711912e33515d87049b39de0
├───checks
│   ├───aarch64-linux
│   │   ├───build: derivation 'dwarffs-0.1.20220128.69d7341'
│   │   └───test: derivation 'vm-test-run-unnamed'
│   ├───i686-linux
│   │   ├───build: derivation 'dwarffs-0.1.20220128.69d7341'
│   │   └───test: derivation 'vm-test-run-unnamed'
│   └───x86_64-linux
│       ├───build: derivation 'dwarffs-0.1.20220128.69d7341'
│       └───test: derivation 'vm-test-run-unnamed'
├───defaultPackage
│   ├───aarch64-linux: package 'dwarffs-0.1.20220128.69d7341'
│   ├───i686-linux: package 'dwarffs-0.1.20220128.69d7341'
│   └───x86_64-linux: package 'dwarffs-0.1.20220128.69d7341'
├───nixosModules
│   └───dwarffs: NixOS module
└───overlay: Nixpkgs overlay

Body:
haskell.nix depends heavily on what is commonly called "import from derivation" or IFD. These are expressions such as

foo = import "${mkDerivation bar}/expr.nix";

or

qux = builtins.readFile (somePackage + "/data.json");

These can not be evaluated without building bar and somePackage.

haskell.nix does have a feature that lets you avoid such expressions altogether. They've called it materialization.


问:
ProjectItem.moveBin() not working correctly Extends Script (Adobe)
im currently developping a script with extends script which is a javascript-similar script language, that we use to automate tasks in Adobe's Softwares (here its premiere pro)
Here is what my code is doing :
-i import files from a folder in my computer
-then i put them in a bin in my prpro project
-and for each of this file i create a bin with the file and a sequence

My problem is that the last file is not move in a bin

here is my code

    root = app.project.rootItem
    newFilesPath = "C:/Path"
    newFilesBin = root.children[0]

    app.project.importFiles(newFilesPath, true, newFilesBin, false)

    app.project.save()

    newFilesBin = root.children[0]

    for(i=0; i<newFilesBin.children.numItems; i++){
        newFile = newFilesBin.children[0]
        name = newFile.name

        newBin = root.createBin(name)
        file.moveBin(newBin)
    }
```

So if i put several file in the path it doesnt move the last file instead of moving every files

Thanks for help

答:
I found the solution :

i just change the parameters of my for loop

```<code>for(i=-1; i<newFilesBin.children.numItems+1; i++)
</code>```

I dont exatly know why its working but it works

Body:
im currently developping a script with extends script which is a javascript-similar script language, that we use to automate tasks in Adobe's Softwares (here its premiere pro)
Here is what my code is doing :
-i import files from a folder in my computer
-then i put them in a bin in my prpro project
-and for each of this file i create a bin with the file and a sequence

My problem is that the last file is not move in a bin

here is my code

    root = app.project.rootItem
    newFilesPath = "C:/Path"
    newFilesBin = root.children[0]

    app.project.importFiles(newFilesPath, true, newFilesBin, false)

    app.project.save()

    newFilesBin = root.children[0]

    for(i=0; i<newFilesBin.children.numItems; i++){
        newFile = newFilesBin.children[0]
        name = newFile.name

        newBin = root.createBin(name)
        file.moveBin(newBin)
    }

So if i put several file in the path it doesnt move the last file instead of moving every files

Thanks for help

Body:
I found the solution :

i just change the parameters of my for loop

for(i=-1; i<newFilesBin.children.numItems+1; i++)

I dont exatly know why its working but it works


问:
How to sort a list by the number of items in another list that is inside dict, with keys similar to the first list
how to sort a list by the number of elements of another list that is inside dict (Keys of dict are similar with elements of list that should be sorted) .

This is the list I want to sort: list_to_sort = ['a','b','c','d']
This is a dict with the elements: reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}

I should get list_after_sort = ['d','a', 'b', 'c']

答:
Using key in a sorted function gives an ability to pass a function by which the elements would be sorted.

This answer covers useful information.

You can use:

```<code>list_to_sort = ['a','b','c','d']
reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}
sorted(list_to_sort, key = lambda x: sum(reference_dict[x]))

# ['d', 'a', 'b', 'c']
</code>```

Body:
Using key in a sorted function gives an ability to pass a function by which the elements would be sorted.

This answer covers useful information.

You can use:

list_to_sort = ['a','b','c','d']
reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}
sorted(list_to_sort, key = lambda x: sum(reference_dict[x]))

# ['d', 'a', 'b', 'c']


问:
Iterable Sum over row in google sheets?
I have data in google sheets, looking like this:

A
B
C
D
E
F
G

TP
14656
18885
14317
19312
13303
14311

FN
12216
20107
14066
16323
11180
3478

and I want to implement the following formula:

which would manually look like this:

```<code>=(B1/(B1+B2))+(C1/(C1+C2))+...+(G1/(G1/G2))
</code>```

However, I need this formula to be scalable. I've tried to use ARRAYFORMULA and SERIESSUM but could not manage to actually iterate over the row. Does sheets even support this, and if so, how does sheets implement iterating sums?

答:
You can do the following:

```<code>=Sum(ArrayFormula(B1:G1/(B1:G1+B2:G2)))
</code>```

Update:

If you want the range to be dependent on a manually entered j, use:

```<code>=Sum(ArrayFormula(Indirect("R1C2:"&"R1C"&j+1,0)/(Indirect("R1C2:"&"R1C"&j+1,0)+Indirect("R2C2:"&"R2C"&j+1,0))))
</code>```

This assumes that the table in your post starts in A1 (R1C1).

Title: Iterable Sum over row in google sheets?

Body:
I have data in google sheets, looking like this:

A
B
C
D
E
F
G

TP
14656
18885
14317
19312
13303
14311

FN
12216
20107
14066
16323
11180
3478

and I want to implement the following formula:

which would manually look like this:

=(B1/(B1+B2))+(C1/(C1+C2))+...+(G1/(G1/G2))

However, I need this formula to be scalable. I've tried to use ARRAYFORMULA and SERIESSUM but could not manage to actually iterate over the row. Does sheets even support this, and if so, how does sheets implement iterating sums?

Body:
You can do the following:

=Sum(ArrayFormula(B1:G1/(B1:G1+B2:G2)))

Update:

If you want the range to be dependent on a manually entered j, use:

=Sum(ArrayFormula(Indirect("R1C2:"&"R1C"&j+1,0)/(Indirect("R1C2:"&"R1C"&j+1,0)+Indirect("R2C2:"&"R2C"&j+1,0))))

This assumes that the table in your post starts in A1 (R1C1).


问:
Using ZipArchive Zip file in iphone mail attachment?
is it possible to send a zip Archive file inside an email attachment using the mail api?</p>

答:
Try This .. This one worked for me</p>

```<code>MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:kFilename];

NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];

[picker addAttachmentData:data mimeType:@"application/zip" fileName:@"/abc.zip"];
[picker setSubject:@"Database"];

[picker setMessageBody:@"Database testing" isHTML:NO];

[self presentModalViewController:picker animated:YES];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try This .. This one worked for me

MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *WritableDBPath= [documentsDirectory stringByAppendingPathComponent:kFilename];

NSData *data = [NSData dataWithContentsOfFile:WritableDBPath];

[picker addAttachmentData:data mimeType:@"application/zip" fileName:@"/abc.zip"];
[picker setSubject:@"Database"];

[picker setMessageBody:@"Database testing" isHTML:NO];

[self presentModalViewController:picker animated:YES];


答:
You can use the key parameter of sorted to pass an arbitrary function.

In this case, get the values from the dictionary and sum them:

```<code>list_after_sort = sorted(list_to_sort, key=lambda x: sum(reference_dict[x]))
</code>```

output: ['d', 'a', 'b', 'c']

using truthy values:

```<code>reference_dict = {'a':[1,0,0,'X',0],
                  'b':[1,0,0,0,1,1],
                  'c':[1,1,1,1,0],
                  'd':['element', 'element', None, None, None]}

sorted(list_to_sort, key=lambda x: sum(map(bool, reference_dict[x])))
# ['a', 'd', 'b', 'c']
</code>```

using blacklist of objects

```<code>blacklist = set([0, None, 'None'])

sorted(list_to_sort, key=lambda x: sum(e not in blacklist
                                       for e in reference_dict[x]))
</code>```

Title: How to sort a list by the number of items in another list that is inside dict, with keys similar to the first list

Body:
how to sort a list by the number of elements of another list that is inside dict (Keys of dict are similar with elements of list that should be sorted) .

This is the list I want to sort: list_to_sort = ['a','b','c','d']
This is a dict with the elements: reference_dict = {'a':[1,0,0,1,0], 'b':[1,0,0,0,1,1], 'c':[1,1,1,1,0], 'd':[1,0,0,0,0]}

I should get list_after_sort = ['d','a', 'b', 'c']

Body:
You can use the key parameter of sorted to pass an arbitrary function.

In this case, get the values from the dictionary and sum them:

list_after_sort = sorted(list_to_sort, key=lambda x: sum(reference_dict[x]))

output: ['d', 'a', 'b', 'c']

using truthy values:

reference_dict = {'a':[1,0,0,'X',0],
                  'b':[1,0,0,0,1,1],
                  'c':[1,1,1,1,0],
                  'd':['element', 'element', None, None, None]}

sorted(list_to_sort, key=lambda x: sum(map(bool, reference_dict[x])))
# ['a', 'd', 'b', 'c']

using blacklist of objects

blacklist = set([0, None, 'None'])

sorted(list_to_sort, key=lambda x: sum(e not in blacklist
                                       for e in reference_dict[x]))


问:
How to add undo action to NSMenuItem programmatically?
I'm building NSMenu programmatically without any Nib(s).

Please take a look at this code:

```<code>self.editMenu = [[NSMenu alloc] initWithTitle:@"Edit"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Undo", nil)
                         action:@selector(undo:)
                  keyEquivalent:@"z"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Redo", nil)
                         action:nil
                  keyEquivalent:@"Z"];

[self.editMenu addItem:[NSMenuItem separatorItem]];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Cut", nil)
                         action:@selector(cut:)
                  keyEquivalent:@"x"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Copy", nil)
                         action:@selector(copy:)
                  keyEquivalent:@"c"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Paste", nil)
                         action:@selector(paste:)
                  keyEquivalent:@"v"];
</code>```

As you can see there are @selector(cut:), @selector(copy:) and @selector(paste:). But there are no @selector(undo:) and @selector(paste:). The compiler says "Undeclared selector 'undo:'.

How can I implement undo and redo menu item's action programmatically?

答:
found a solution here(if still need) -

https://github.com/lapcat/Bonjeff/blob/master/source/MainMenu.swift

```<code>@objc protocol EditMenuActions {
    func redo(_ sender:AnyObject)
    func undo(_ sender:AnyObject)
}

menu.addItem(withTitle:title, action:#selector(EditMenuActions.undo(_:)), keyEquivalent:"z")
menu.addItem(withTitle:title, action:#selector(EditMenuActions.redo(_:)), keyEquivalent:"Z")
</code>```

Body:
I'm building NSMenu programmatically without any Nib(s).

Please take a look at this code:

self.editMenu = [[NSMenu alloc] initWithTitle:@"Edit"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Undo", nil)
                         action:@selector(undo:)
                  keyEquivalent:@"z"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Redo", nil)
                         action:nil
                  keyEquivalent:@"Z"];

[self.editMenu addItem:[NSMenuItem separatorItem]];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Cut", nil)
                         action:@selector(cut:)
                  keyEquivalent:@"x"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Copy", nil)
                         action:@selector(copy:)
                  keyEquivalent:@"c"];

[self.editMenu addItemWithTitle:NSLocalizedString(@"Paste", nil)
                         action:@selector(paste:)
                  keyEquivalent:@"v"];

As you can see there are @selector(cut:), @selector(copy:) and @selector(paste:). But there are no @selector(undo:) and @selector(paste:). The compiler says "Undeclared selector 'undo:'.

How can I implement undo and redo menu item's action programmatically?

Body:
found a solution here(if still need) -

https://github.com/lapcat/Bonjeff/blob/master/source/MainMenu.swift

@objc protocol EditMenuActions {
    func redo(_ sender:AnyObject)
    func undo(_ sender:AnyObject)
}

menu.addItem(withTitle:title, action:#selector(EditMenuActions.undo(_:)), keyEquivalent:"z")
menu.addItem(withTitle:title, action:#selector(EditMenuActions.redo(_:)), keyEquivalent:"Z")


问:
Calling conn.query in a loop causes: Variable 'conn' implicitly has an 'any' type
I have a route like below in which I want to get all posts (like in twitter) from the db. I have separated the likes and images for each post in its own sql table called "post_likes" & "post_images".

After retrieving the posts I want to add the likes for each post and then send it back to the client.

But looping through an array and calling conn.query each time gives me these two errors:

error TS7034: Variable 'conn' implicitly has type 'any' in some locations where its type cannot be determined.

error TS7005: Variable 'conn' implicitly has an 'any' type.

Why can't typescript determine the type of conn in a map or forEach loop?

```<code>router.get("/get/:token", async (req: Request, res: Response) => {
  /**
   * Gets all Post from you and your friends
   */

  ...

  let conn;  // ERROR <-- Variable 'conn' implicitly has type 'any' in some locations where its type cannot be determined.

  try {
    conn = await pool.getConnection();

    ...

    /* get all posts */
    const queryGetPostsResult = await conn.query(queryGetPosts);
    const getPosts: Array<Post> = [...queryGetPostsResult];

    /* add images and likes to each post */
    let clientPosts: Array<ClientPost> = await Promise.all(getPosts.map(async (post: Post) => {

      /* FIXME get the likes */
      const queryGetLikes: string = `SELECT user_id FROM post_likes WHERE post_id=?`

      const queryGetLikesResult = await conn.query(queryGetLikes, [post.id]); // ERROR <-- Variable 'conn' implicitly has an 'any' type.

      const likes: Array<number> = queryGetLikesResult.map((x: { user_id: number }) => x.user_id);

      /* TODO get the images */
      const images: Array<string> = [];

      const clientPost: ClientPost = {
        id: post.id,
        writtenBy: post.written_by,
        content: post.content,
        writtenAt: post.written_at,
        images,
        likes,
      };

      return clientPost;
    }));

    return res.send(clientPosts);
  } catch(err: unknown) {
    throw console.log(colors.red(`/api/post/get/:token => ${err}`));
  } finally {
    if (conn) return conn.release();
  }
});
</code>```

答:
Like T.J. Crowder suggested the problem was the missing type annotation at let conn; but I still don't understand why typescript only throws an error when I try to call conn.query() inside a loop. If someone knows please explain this to me.

I also had to add if (!conn) throw "conn is undefined" to break out of the try & map block.

So I've edited the route to the following:

```<code>router.get("/get/:token", async (req: Request, res: Response) => {
  /**
   * Gets all Post from you and your friends
   */

  ...

  let conn: PoolConnection | undefined;  // <-- ADDED TO FIX THE ERROR!!!

  try {
    conn = await pool.getConnection();
    if (!conn) throw "conn is unknown"; // <-- ADDED TO FIX THE ERROR!!!

    ...

    /* get all posts */
    const queryGetPostsResult = await conn.query(queryGetPosts);
    const getPosts: Array<Post> = [...queryGetPostsResult];

    /* add images and likes to each post */
    let clientPosts: Array<ClientPost> = await Promise.all(getPosts.map(async (post: Post) => {

      if (!conn) throw "conn is unknown"; // <-- ADDED TO FIX THE ERROR!!!

      /* FIXME get the likes */
      const queryGetLikes: string = `SELECT user_id FROM post_likes WHERE post_id=?`

      const queryGetLikesResult = await conn.query(queryGetLikes, [post.id]);

      const likes: Array<number> = queryGetLikesResult.map((x: { user_id: number }) => x.user_id);

      /* TODO get the images */
      const images: Array<string> = [];

      const clientPost: ClientPost = {
        id: post.id,
        writtenBy: post.written_by,
        content: post.content,
        writtenAt: post.written_at,
        images,
        likes,
      };

      return clientPost;
    }));

    return res.send(clientPosts);
  } catch(err: unknown) {
    throw console.log(colors.red(`/api/post/get/:token => ${err}`));
  } finally {
    if (conn) return conn.release();
  }
});
</code>```

Body:
I have a route like below in which I want to get all posts (like in twitter) from the db. I have separated the likes and images for each post in its own sql table called "post_likes" & "post_images".

After retrieving the posts I want to add the likes for each post and then send it back to the client.

But looping through an array and calling conn.query each time gives me these two errors:

error TS7034: Variable 'conn' implicitly has type 'any' in some locations where its type cannot be determined.

error TS7005: Variable 'conn' implicitly has an 'any' type.

Why can't typescript determine the type of conn in a map or forEach loop?

router.get("/get/:token", async (req: Request, res: Response) => {
  /**
   * Gets all Post from you and your friends
   */

  ...

  let conn;  // ERROR <-- Variable 'conn' implicitly has type 'any' in some locations where its type cannot be determined.

  try {
    conn = await pool.getConnection();

    ...

    /* get all posts */
    const queryGetPostsResult = await conn.query(queryGetPosts);
    const getPosts: Array<Post> = [...queryGetPostsResult];

    /* add images and likes to each post */
    let clientPosts: Array<ClientPost> = await Promise.all(getPosts.map(async (post: Post) => {

      /* FIXME get the likes */
      const queryGetLikes: string = `SELECT user_id FROM post_likes WHERE post_id=?`

      const queryGetLikesResult = await conn.query(queryGetLikes, [post.id]); // ERROR <-- Variable 'conn' implicitly has an 'any' type.

      const likes: Array<number> = queryGetLikesResult.map((x: { user_id: number }) => x.user_id);

      /* TODO get the images */
      const images: Array<string> = [];

      const clientPost: ClientPost = {
        id: post.id,
        writtenBy: post.written_by,
        content: post.content,
        writtenAt: post.written_at,
        images,
        likes,
      };

      return clientPost;
    }));

    return res.send(clientPosts);
  } catch(err: unknown) {
    throw console.log(colors.red(`/api/post/get/:token => ${err}`));
  } finally {
    if (conn) return conn.release();
  }
});

Body:
Like T.J. Crowder suggested the problem was the missing type annotation at let conn; but I still don't understand why typescript only throws an error when I try to call conn.query() inside a loop. If someone knows please explain this to me.

I also had to add if (!conn) throw "conn is undefined" to break out of the try & map block.

So I've edited the route to the following:

router.get("/get/:token", async (req: Request, res: Response) => {
  /**
   * Gets all Post from you and your friends
   */

  ...

  let conn: PoolConnection | undefined;  // <-- ADDED TO FIX THE ERROR!!!

  try {
    conn = await pool.getConnection();
    if (!conn) throw "conn is unknown"; // <-- ADDED TO FIX THE ERROR!!!

    ...

    /* get all posts */
    const queryGetPostsResult = await conn.query(queryGetPosts);
    const getPosts: Array<Post> = [...queryGetPostsResult];

    /* add images and likes to each post */
    let clientPosts: Array<ClientPost> = await Promise.all(getPosts.map(async (post: Post) => {

      if (!conn) throw "conn is unknown"; // <-- ADDED TO FIX THE ERROR!!!

      /* FIXME get the likes */
      const queryGetLikes: string = `SELECT user_id FROM post_likes WHERE post_id=?`

      const queryGetLikesResult = await conn.query(queryGetLikes, [post.id]);

      const likes: Array<number> = queryGetLikesResult.map((x: { user_id: number }) => x.user_id);

      /* TODO get the images */
      const images: Array<string> = [];

      const clientPost: ClientPost = {
        id: post.id,
        writtenBy: post.written_by,
        content: post.content,
        writtenAt: post.written_at,
        images,
        likes,
      };

      return clientPost;
    }));

    return res.send(clientPosts);
  } catch(err: unknown) {
    throw console.log(colors.red(`/api/post/get/:token => ${err}`));
  } finally {
    if (conn) return conn.release();
  }
});


问:
Running a stored procedure using a resultset as the parameter and insert into a table
I have the question below,

I do have a query which returns 10 rows for example.

```<code>SELECT CarId FROM Car

EXEC spQ_GetCar (@CarId)
</code>```

Also, I have a stored procedure that uses an id from the table above.

My question is, how can I run the stored procedure and use the output of the table as the parameter and then insert that into another temp table.

Would it be possible by using a cursor and dynamic SQL ?, has anyone faced this before ?

NOTES: I cannot create a table type to use it

答:
A fast answer:

Create a table, then you can insert-exec:

```<code>insert yourPreparedtable
EXEC spQ_GetCar (@CarId)
</code>```

The true answer:

Erland Sommarskog's article is the most in-depth resource you will find. Many alternatives with detailed advantages and disadvantages.

Body:
I have the question below,

I do have a query which returns 10 rows for example.

SELECT CarId FROM Car

EXEC spQ_GetCar (@CarId)

Also, I have a stored procedure that uses an id from the table above.

My question is, how can I run the stored procedure and use the output of the table as the parameter and then insert that into another temp table.

Would it be possible by using a cursor and dynamic SQL ?, has anyone faced this before ?

NOTES: I cannot create a table type to use it

Body:
A fast answer:

Create a table, then you can insert-exec:

insert yourPreparedtable
EXEC spQ_GetCar (@CarId)

The true answer:

Erland Sommarskog's article is the most in-depth resource you will find. Many alternatives with detailed advantages and disadvantages.


问:
java.lang.ClassCastException: org.apache.hadoop.conf.Configuration cannot be cast to org.apache.hadoop.yarn.conf.YarnConfiguration
I am running a spark application using yarn in cloudera.
Spark version: 2.1

I get the following error:

SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found
  binding in
  [jar:file:/data/yarn/nm/filecache/13/jars/slf4j-log4j12-1.7.16.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  SLF4J: Found binding in
  [jar:file:/opt/cloudera/parcels/CDH-5.10.2-1.cdh5.10.2.p0.5/jars/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
  SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an
  explanation. SLF4J: Actual binding is of type
  [org.slf4j.impl.Log4jLoggerFactory] 18/04/14 22:20:57 INFO
  util.SignalUtils: Registered signal handler for TERM 18/04/14 22:20:57
  INFO util.SignalUtils: Registered signal handler for HUP 18/04/14
  22:20:57 INFO util.SignalUtils: Registered signal handler for INT
  Exception in thread "main" java.lang.ClassCastException:
  org.apache.hadoop.conf.Configuration cannot be cast to
  org.apache.hadoop.yarn.conf.YarnConfiguration     at
  org.apache.spark.deploy.yarn.ApplicationMaster.(ApplicationMaster.scala:60)
    at
  org.apache.spark.deploy.yarn.ApplicationMaster$$anonfun$main$1.apply$mcV$sp(ApplicationMaster.scala:764)
    at
  org.apache.spark.deploy.SparkHadoopUtil$$anon$1.run(SparkHadoopUtil.scala:67)
    at
  org.apache.spark.deploy.SparkHadoopUtil$$anon$1.run(SparkHadoopUtil.scala:66)
    at java.security.AccessController.doPrivileged(Native Method)   at
  javax.security.auth.Subject.doAs(Subject.java:415)    at
  org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at
  org.apache.spark.deploy.SparkHadoopUtil.runAsSparkUser(SparkHadoopUtil.scala:66)
    at
  org.apache.spark.deploy.yarn.ApplicationMaster$.main(ApplicationMaster.scala:763)
    at
  org.apache.spark.deploy.yarn.ApplicationMaster.main(ApplicationMaster.scala)

答:
I encounter the same issue while trying to start a Spark job using Yarn Rest API.
And the reason was that the environment variable SPARK_YARN_MODE was missing. Adding this env var, everything works fine :</p>
```<code>export SPARK_YARN_MODE=true
</code>```

Body:
I encounter the same issue while trying to start a Spark job using Yarn Rest API.
And the reason was that the environment variable SPARK_YARN_MODE was missing. Adding this env var, everything works fine :

export SPARK_YARN_MODE=true


问:
Where can I find SLAs for AWS CloudFormation APIs
Looking for SLA of CloudFormation APIs like listExports.

Is there any doc like this for CloudFormation?

答: There isn't a service level agreement for CloudFormation in the list of SLAs</p>


问:
jsonify a SQLAlchemy result set in Flask
I'm trying to jsonify a SQLAlchemy result set in Flask/Python.

The Flask mailing list suggested the following method http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e :

```<code>return jsonify(json_list = qryresult)
</code>```

However I'm getting the following error back:

```<code>TypeError: <flaskext.sqlalchemy.BaseQuery object at 0x102c2df90>
is not JSON serializable
</code>```

What am I overlooking here?

I have found this question: How to serialize SqlAlchemy result to JSON? which seems very similar however I didn't know whether Flask had some magic to make it easier as the mailing list post suggested.

Edit: for clarification, this is what my model looks like

```<code>class Rating(db.Model):

    __tablename__ = 'rating'

    id = db.Column(db.Integer, primary_key=True)
    fullurl = db.Column(db.String())
    url = db.Column(db.String())
    comments = db.Column(db.Text)
    overall = db.Column(db.Integer)
    shipping = db.Column(db.Integer)
    cost = db.Column(db.Integer)
    honesty = db.Column(db.Integer)
    communication = db.Column(db.Integer)
    name = db.Column(db.String())
    ipaddr = db.Column(db.String())
    date = db.Column(db.String())

    def __init__(self, fullurl, url, comments, overall, shipping, cost, honesty, communication, name, ipaddr, date):
        self.fullurl = fullurl
        self.url = url
        self.comments = comments
        self.overall = overall
        self.shipping = shipping
        self.cost = cost
        self.honesty = honesty
        self.communication = communication
        self.name = name
        self.ipaddr = ipaddr
        self.date = date
</code>```

答:
It seems that you actually haven't executed your query. Try following:

```<code>return jsonify(json_list = qryresult.all())
</code>```

[Edit]: Problem with jsonify is, that usually the objects cannot be jsonified automatically. Even Python's datetime fails ;)

What I have done in the past, is adding an extra property (like serialize) to classes that need to be serialized.

```<code>def dump_datetime(value):
    """Deserialize datetime object into string form for JSON processing."""
    if value is None:
        return None
    return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]

class Foo(db.Model):
    # ... SQLAlchemy defs here..
    def __init__(self, ...):
       # self.foo = ...
       pass

    @property
    def serialize(self):
       """Return object data in easily serializable format"""
       return {
           'id'         : self.id,
           'modified_at': dump_datetime(self.modified_at),
           # This is an example how to deal with Many2Many relations
           'many2many'  : self.serialize_many2many
       }
    @property
    def serialize_many2many(self):
       """
       Return object's relations in easily serializable format.
       NB! Calls many2many's serialize property.
       """
       return [ item.serialize for item in self.many2many]
</code>```

And now for views I can just do:

```<code>return jsonify(json_list=[i.serialize for i in qryresult.all()])
</code>```

[Edit 2019]:
In case you have more complex objects or circular references, use a library like marshmallow).

Body:
I'm trying to jsonify a SQLAlchemy result set in Flask/Python.

The Flask mailing list suggested the following method http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e :

return jsonify(json_list = qryresult)

However I'm getting the following error back:

TypeError: <flaskext.sqlalchemy.BaseQuery object at 0x102c2df90>
is not JSON serializable

What am I overlooking here?

I have found this question: How to serialize SqlAlchemy result to JSON? which seems very similar however I didn't know whether Flask had some magic to make it easier as the mailing list post suggested.

Edit: for clarification, this is what my model looks like

class Rating(db.Model):

    __tablename__ = 'rating'

    id = db.Column(db.Integer, primary_key=True)
    fullurl = db.Column(db.String())
    url = db.Column(db.String())
    comments = db.Column(db.Text)
    overall = db.Column(db.Integer)
    shipping = db.Column(db.Integer)
    cost = db.Column(db.Integer)
    honesty = db.Column(db.Integer)
    communication = db.Column(db.Integer)
    name = db.Column(db.String())
    ipaddr = db.Column(db.String())
    date = db.Column(db.String())

    def __init__(self, fullurl, url, comments, overall, shipping, cost, honesty, communication, name, ipaddr, date):
        self.fullurl = fullurl
        self.url = url
        self.comments = comments
        self.overall = overall
        self.shipping = shipping
        self.cost = cost
        self.honesty = honesty
        self.communication = communication
        self.name = name
        self.ipaddr = ipaddr
        self.date = date

Body:
It seems that you actually haven't executed your query. Try following:

return jsonify(json_list = qryresult.all())

[Edit]: Problem with jsonify is, that usually the objects cannot be jsonified automatically. Even Python's datetime fails ;)

What I have done in the past, is adding an extra property (like serialize) to classes that need to be serialized.

def dump_datetime(value):
    """Deserialize datetime object into string form for JSON processing."""
    if value is None:
        return None
    return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]

class Foo(db.Model):
    # ... SQLAlchemy defs here..
    def __init__(self, ...):
       # self.foo = ...
       pass

    @property
    def serialize(self):
       """Return object data in easily serializable format"""
       return {
           'id'         : self.id,
           'modified_at': dump_datetime(self.modified_at),
           # This is an example how to deal with Many2Many relations
           'many2many'  : self.serialize_many2many
       }
    @property
    def serialize_many2many(self):
       """
       Return object's relations in easily serializable format.
       NB! Calls many2many's serialize property.
       """
       return [ item.serialize for item in self.many2many]

And now for views I can just do:

return jsonify(json_list=[i.serialize for i in qryresult.all()])

[Edit 2019]:
In case you have more complex objects or circular references, use a library like marshmallow).


问:
R update a tibble using data from a second tibble as row and column
I have an empty tibble full of NA's with the rows and columns, respectively named for id numbers and all the dates in a period of time.  For example, this code:

```<code>tbl <- tibble(PERSONAL_ID = c("A", "B", "C", "D"))
dates = as.character((seq(as.Date("2016-01-01"), as.Date("2016-01-05"), by="days")))
tbl[dates] <- NA
tbl <- column_to_rownames(tbl, var = "PERSONAL_ID")
</code>```

I have a second tibble that contains columns matching up one ID number with one date, as in this example:

```<code>enrollments <- tibble(ID = c("D", "B", "C", "D"),
                      date = c("2016-01-01", "2016-01-03", "2016-01-05", "2016-01-02"))
</code>```

What I would like to do is add "1" to the row and column of the first tibble (tbl) corresponding to the ID and date listed in the second tibble (enrollments).  For the example code above, the desired output would be:

```<code>  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A       <NA>       <NA>       <NA>        <NA>      <NA>
B       <NA>       <NA>          1        <NA>      <NA>
C       <NA>       <NA>       <NA>        <NA>         1
D          1          1       <NA>        <NA>      <NA>
</code>```

Thank you!

答:
Here's a data.table approach, using PERSONAL_IDS, dates, and enrollments

```<code>dcast(rbind(
  rbindlist(lapply(setdiff(PERSONAL_ID,enrollments$ID), \(x) data.table(ID=x, date=dates)))[,value:=NA],
  enrollments[,value:=1]
  ), ID~date,value.var="value")
</code>```

Output:

```<code>   ID 2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
1:  A         NA         NA         NA         NA         NA
2:  B         NA         NA          1         NA         NA
3:  C         NA         NA         NA         NA          1
4:  D          1          1         NA         NA         NA
</code>```

Body:
I have an empty tibble full of NA's with the rows and columns, respectively named for id numbers and all the dates in a period of time.  For example, this code:

tbl <- tibble(PERSONAL_ID = c("A", "B", "C", "D"))
dates = as.character((seq(as.Date("2016-01-01"), as.Date("2016-01-05"), by="days")))
tbl[dates] <- NA
tbl <- column_to_rownames(tbl, var = "PERSONAL_ID")

I have a second tibble that contains columns matching up one ID number with one date, as in this example:

enrollments <- tibble(ID = c("D", "B", "C", "D"),
                      date = c("2016-01-01", "2016-01-03", "2016-01-05", "2016-01-02"))

What I would like to do is add "1" to the row and column of the first tibble (tbl) corresponding to the ID and date listed in the second tibble (enrollments).  For the example code above, the desired output would be:

  2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
A       <NA>       <NA>       <NA>        <NA>      <NA>
B       <NA>       <NA>          1        <NA>      <NA>
C       <NA>       <NA>       <NA>        <NA>         1
D          1          1       <NA>        <NA>      <NA>

Thank you!

Body:
Here's a data.table approach, using PERSONAL_IDS, dates, and enrollments

dcast(rbind(
  rbindlist(lapply(setdiff(PERSONAL_ID,enrollments$ID), \(x) data.table(ID=x, date=dates)))[,value:=NA],
  enrollments[,value:=1]
  ), ID~date,value.var="value")

Output:

   ID 2016-01-01 2016-01-02 2016-01-03 2016-01-04 2016-01-05
1:  A         NA         NA         NA         NA         NA
2:  B         NA         NA          1         NA         NA
3:  C         NA         NA         NA         NA          1
4:  D          1          1         NA         NA         NA


问:
trues and length of bool list f#
Directly using recursion, write a function truesAndLength : bool list -> int * int that
returns both the length of the list (in the first component of the pair), and the number of
elements of the list that are true (in the second component). Your function must only iterate
over the elements of the list once. (Do not use any of the functions from the List module.)

this is my code so far:

```<code>let rec length bs =
    match bs with
    | [] -> 0
    | b::bs -> 1 + length bs

let rec trues bs =
    match bs with
    | [] -> 0
    | b::bs -> if b = true then 1 + trues bs else trues bs

let truesandlength bs =
    let l = length bs
    let t = trues bs
    (l, t)

truesandlength [true; true; false]
</code>```

This works by im iterating through the list 2 times, i can't figure out how to iterate only 1. Any tips?

答:
```<code>let rec truesAndLength bs =
  let sum a b = (fst a + fst b, snd a + snd b)
  match bs with
  | [] -> 0, 0
  | head::tail ->
    if head then sum (1,1) (truesAndLength tail) else sum (1, 0) (truesAndLength tail)
</code>```

Title: trues and length of bool list f#

Body:
Directly using recursion, write a function truesAndLength : bool list -> int * int that
returns both the length of the list (in the first component of the pair), and the number of
elements of the list that are true (in the second component). Your function must only iterate
over the elements of the list once. (Do not use any of the functions from the List module.)

this is my code so far:

let rec length bs =
    match bs with
    | [] -> 0
    | b::bs -> 1 + length bs

let rec trues bs =
    match bs with
    | [] -> 0
    | b::bs -> if b = true then 1 + trues bs else trues bs

let truesandlength bs =
    let l = length bs
    let t = trues bs
    (l, t)

truesandlength [true; true; false]

This works by im iterating through the list 2 times, i can't figure out how to iterate only 1. Any tips?


问:
React Native Gesture Handle PinchGestureHandler Text Component
So I'm trying to implement a pinch to zoom on a Text component in React Native and I can't seem to understand the documentation, and most other posts are about making an Image Zoomable, I tried to extrapolate from those but does not want to work.

I'm using the PinchGestureHandler component from react-native-gesture-handler

This is what I got so far and it does not do anything:

```<code>import { PinchGestureHandler } from 'react-native-gesture-handler';

const ArticlesScreen = () => {

...

  const scale = useRef(new Animated.Value(0)).current;

  const handlePinch = () => {
    Animated.event(
    [
      {
        nativeEvent: {
          scale,
        },
      },
    ],
    { useNativeDriver: true }
  )}

return (

<View>
   <PinchGestureHandler onGestureEvent={handlePinch}>
            <Animated.Text
              style={{
                backgroundColor: theme === 'light' ? '#FFF' : '#2D65A7',
                transform: [{ scale }],
              }}
            >
              <TouchableOpacity
                onPress={changeTheme}
                style={tw`pt-3 pl-60 flex-row items-center`}
              >
                <MaterialCommunityIcons
                  name="desk-lamp"
                  size={34}
                  color={theme === 'light' ? '#2D65A7' : '#FFF'}
                />
                <Text style={{ color: theme === 'light' ? '#2D65A7' : '#FFF' }}>
                  {theme === 'light' ? 'Dark Mode' : 'Light Mode'}
                </Text>
              </TouchableOpacity>
              <RenderHtml
                enableCSSInlineProcessing={true}
                contentWidth={Dimensions.get('window').width - 32}
                source={html}
                enableExperimentalMarginCollapsing={false}
                renderersProps={renderersProps}
                tagsStyles={
                  theme === 'light' ? tagsStylesLight : tagsStylesDark
                }
                classesStyles={
                  theme === 'light' ? classesStyles : classesStylesDark
                }
                customHTMLElementModels={customHTMLElementModels}
                ignoredDomTags={['colgroup']}
              />
            </Animated.Text>
          </PinchGestureHandler>
    </View>

 );
};

</code>```

There is more code in the file, I didn't want to cram it a lot to more readable, I  think I got what is relevant for this.

Thank you in advance

答:
So after a lot of testing and trying to figure out how to get the gesture-handler to work and failing. I just decided to use this package, easy and simple to set up

https://www.npmjs.com/package/@dudigital/react-native-zoomable-view

Body:
So I'm trying to implement a pinch to zoom on a Text component in React Native and I can't seem to understand the documentation, and most other posts are about making an Image Zoomable, I tried to extrapolate from those but does not want to work.

I'm using the PinchGestureHandler component from react-native-gesture-handler

This is what I got so far and it does not do anything:

import { PinchGestureHandler } from 'react-native-gesture-handler';

const ArticlesScreen = () => {

...

  const scale = useRef(new Animated.Value(0)).current;

  const handlePinch = () => {
    Animated.event(
    [
      {
        nativeEvent: {
          scale,
        },
      },
    ],
    { useNativeDriver: true }
  )}

return (

<View>
   <PinchGestureHandler onGestureEvent={handlePinch}>
            <Animated.Text
              style={{
                backgroundColor: theme === 'light' ? '#FFF' : '#2D65A7',
                transform: [{ scale }],
              }}
            >
              <TouchableOpacity
                onPress={changeTheme}
                style={tw`pt-3 pl-60 flex-row items-center`}
              >
                <MaterialCommunityIcons
                  name="desk-lamp"
                  size={34}
                  color={theme === 'light' ? '#2D65A7' : '#FFF'}
                />
                <Text style={{ color: theme === 'light' ? '#2D65A7' : '#FFF' }}>
                  {theme === 'light' ? 'Dark Mode' : 'Light Mode'}
                </Text>
              </TouchableOpacity>
              <RenderHtml
                enableCSSInlineProcessing={true}
                contentWidth={Dimensions.get('window').width - 32}
                source={html}
                enableExperimentalMarginCollapsing={false}
                renderersProps={renderersProps}
                tagsStyles={
                  theme === 'light' ? tagsStylesLight : tagsStylesDark
                }
                classesStyles={
                  theme === 'light' ? classesStyles : classesStylesDark
                }
                customHTMLElementModels={customHTMLElementModels}
                ignoredDomTags={['colgroup']}
              />
            </Animated.Text>
          </PinchGestureHandler>
    </View>

 );
};

There is more code in the file, I didn't want to cram it a lot to more readable, I  think I got what is relevant for this.

Thank you in advance


问:
Nestjs how to change socket.io message data
If the message data is not null, I can edit value like this:

```<code>context.switchToWs().getData().custom = true
</code>```

But, how to change it, if the message data is null?

答:
Try please this way:

const data = context.switchToWs().getData();

data = {
  ...data,
  custom: true
}
```

Body:
If the message data is not null, I can edit value like this:

context.switchToWs().getData().custom = true

But, how to change it, if the message data is null?


问:
How to create a new Context from scratch in NodeJS
I am working on a bot-based application that sends proactive messages to the team.

My query is, How can we create a new Context to work with to be able to send a proactive message after server restart.

So, that means we are getting context only after receiving messages from Teams. which results in we can’t send messages after the server is restarted.

答:
When you say you're losing the context, it sounds like you're only storing them in memory - this is not correct, otherwise you will experience exactly that. These context details need to be saved on your server side into a proper permanent data storage mechanism (e.g. dDatabase or blob storage or whatever you choose, but something permanent, not just memory).

Separately though, it's worth noting that you don't -actually- need to store the 'context' - that's just one approach, that's used a lot in the Microsoft samples. I find it easier to store just a subset of required data, being the ServiceUrl and the Conversation Id. Please see here for a sample: https://github.com/pnp/teams-dev-samples/tree/main/samples/bot-proactive-messaging . I put both a dotnet as well as a node.js version in the sample, and there are some links at the bottom of the page to read more about the topic. Here is also a link to a video session where I talk more about the concept: https://www.youtube.com/watch?v=mM7-fYdcJhw&t=1398s.


问:
Python Pandas read_excel dtype str replace nan by blank ('') when reading or when writing via to_csv
Python version: Python 2.7.13 :: Anaconda custom (64-bit)
Pandas version: pandas 0.20.2

Hello,

I have a quite simple requirement.
I would like to read an excel file and write a specific sheet to a csv file.
Blank values in the source Excel file should be treated / written as blank when writing the csv file.
However, my blank records are always written as 'nan' to the output file. (without the quotes)

I read the Excel file via method

read_excel(xlsx, sheetname='sheet1', dtype = str)

I am specifying dtype because I have some columns that are numbers but should be treated as string. (Otherwise they might lose leading 0s etc)
i.e. I would like to read the exact value from every cell.

Now I write the output .csv file via
to_csv(output_file,index=False,mode='wb',sep=',',encoding='utf-8')

However, my result csv file contains nan for all blank cells from the excel file.

What am I missing? I already tried .fillna('', inplace=True) function but it seems to be doing nothing to my data.
I also tried to add parameter na_rep ='' to the to_csv method but without success.

Thanks for any help!

Addendum: Please find hereafter a reproducible example.

Please find hereafter a reproducible example code.
Please first create a new Excel file with 2 columns with the following content:
COLUMNA COLUMNB COLUMNC
01      test
02  test

03      test

(I saved this Excel file to c:\test.xls
Please note that 1st and 3rd row for column B as well as the 2nd row for Column C is blank/empty)

Now here is my code:

```<code>import pandas as pd
xlsx = pd.ExcelFile('c:\\test.xlsx')
df = pd.read_excel(xlsx, sheetname='Sheet1', dtype = str)
df.fillna('', inplace=True)
df.to_csv('c:\\test.csv', index=False,mode='wb',sep=',',encoding='utf-8', na_rep ='')
</code>```

My result is:

 COLUMNA,COLUMNB,COLUMNC

 01,nan,test

 02,test,nan

 03,nan,test

My desired result would be:

COLUMNA,COLUMNB,COLUMNC

01,,test

02,test,

03,,test

答:
I had the same problem and used the option  keep_default_na=False in read_excel.
df = pd.read_excel(content, sheet_name=sheet, header=[0], keep_default_na=False)</p>

Body:
Python version: Python 2.7.13 :: Anaconda custom (64-bit)
Pandas version: pandas 0.20.2

Hello,

I have a quite simple requirement.
I would like to read an excel file and write a specific sheet to a csv file.
Blank values in the source Excel file should be treated / written as blank when writing the csv file.
However, my blank records are always written as 'nan' to the output file. (without the quotes)

I read the Excel file via method

read_excel(xlsx, sheetname='sheet1', dtype = str)

I am specifying dtype because I have some columns that are numbers but should be treated as string. (Otherwise they might lose leading 0s etc)
i.e. I would like to read the exact value from every cell.

Now I write the output .csv file via
to_csv(output_file,index=False,mode='wb',sep=',',encoding='utf-8')

However, my result csv file contains nan for all blank cells from the excel file.

What am I missing? I already tried .fillna('', inplace=True) function but it seems to be doing nothing to my data.
I also tried to add parameter na_rep ='' to the to_csv method but without success.

Thanks for any help!

Addendum: Please find hereafter a reproducible example.

Please find hereafter a reproducible example code.
Please first create a new Excel file with 2 columns with the following content:
COLUMNA COLUMNB COLUMNC
01      test
02  test

03      test

(I saved this Excel file to c:\test.xls
Please note that 1st and 3rd row for column B as well as the 2nd row for Column C is blank/empty)

Now here is my code:

import pandas as pd
xlsx = pd.ExcelFile('c:\\test.xlsx')
df = pd.read_excel(xlsx, sheetname='Sheet1', dtype = str)
df.fillna('', inplace=True)
df.to_csv('c:\\test.csv', index=False,mode='wb',sep=',',encoding='utf-8', na_rep ='')

My result is:

 COLUMNA,COLUMNB,COLUMNC

 01,nan,test

 02,test,nan

 03,nan,test

My desired result would be:

COLUMNA,COLUMNB,COLUMNC

01,,test

02,test,

03,,test


问:
Can I create a template within XSLT?
I want to create a ASP.NET user control from an XML using XSLT.
Currently I really put the result together bit by bit:

```<code><xsl:template match="TextField">
   <xsl:apply-templates select="Label" />
   <xsl:text><![CDATA[<asp:TextBox ID="]]></xsl:text>
   <xsl:value-of select="@id"/>
   <xsl:if test="@defaultValue">
      <xsl:text><![CDATA[" value="]]></xsl:text>
      <xsl:value-of select="@defaultValue"/>
   </xsl:if>
   <xsl:text><![CDATA[" runat="server"></asp:TextBox>]]></xsl:text>
   <xsl:copy-of select="$br"/>
</xsl:template>
</code>```

It would be rally cool if I could instead do something like this:

```<code><xsl:template match="TextField">
   <xsl:apply-templates select="Label" />

   <xsl:variable name="localTemplate" select="expression">
      <xsl:text><![CDATA[
         <asp:TextBox ID="{theID}" value="{theDefaultValue}" runat="server"></asp:TextBox>
      ]]></xsl:text>
      <xsl:copy-of select="$br"/>
   </xsl:variable>

   <!-- replace {theID} and {theDefaultValue} from the corresponding
       values of the input XML and then return the content of that
       variable
   -->
</xsl:template>
</code>```

Because that seems much cleaner and more easy to maintain later on when there is the need to change the html structure.

Is there a way to achieve this and if yes, how would that look like?
I don't need a working solution, just some hints on what to do.

Update: Here is some sample input XML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<Form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="XmlForm.xsd">

   <Validation enabled="false" enableValidationSummary="true" />
   <FieldSet>
      <TextField id="firstInput" css-class="textfield-css-class" />

      <TextField id="secondInput" defaultValue="Wrdlbmrpft">
         <Label translatable="true" >Label Text</Label>
      </TextField>
   </FieldSet>
</Form>
</code>```

The output should look like this:

```<code><%@ Control Language="C#" AutoEventWireup="true" Inherits="DevelopmentWeb.WebUserControl1" %>
<asp:TextBox runat="server" ID="firstInput" CssClass="textfield-css-class"></asp:TextBox>
<asp:Label runat="server" AssociatedControlID="secondInput">Label Text</asp:Label>
<asp:TextBox runat="server" ID="secondInput">Wrdlbrmpft</asp:TextBox>
</code>```

答:
Define appropriate namespace for prefix asp, e.g.:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:asp="System.Web.UI.WebControls">
</code>```

In your template simply write:

```<code><asp:TextBox ID="{@id}" runat="server">
    <xsl:if test="@defaultValue">
        <xsl:attribute name="value">
            <xsl:value-of select="@defaultValue"/>
        </xsl:attribute>
    </xsl:if>
</asp:TextBox>
</code>```

Title: Can I create a template within XSLT?

Body:
I want to create a ASP.NET user control from an XML using XSLT.
Currently I really put the result together bit by bit:

<xsl:template match="TextField">
   <xsl:apply-templates select="Label" />
   <xsl:text><![CDATA[<asp:TextBox ID="]]></xsl:text>
   <xsl:value-of select="@id"/>
   <xsl:if test="@defaultValue">
      <xsl:text><![CDATA[" value="]]></xsl:text>
      <xsl:value-of select="@defaultValue"/>
   </xsl:if>
   <xsl:text><![CDATA[" runat="server"></asp:TextBox>]]></xsl:text>
   <xsl:copy-of select="$br"/>
</xsl:template>

It would be rally cool if I could instead do something like this:

<xsl:template match="TextField">
   <xsl:apply-templates select="Label" />

   <xsl:variable name="localTemplate" select="expression">
      <xsl:text><![CDATA[
         <asp:TextBox ID="{theID}" value="{theDefaultValue}" runat="server"></asp:TextBox>
      ]]></xsl:text>
      <xsl:copy-of select="$br"/>
   </xsl:variable>

</xsl:template>

Because that seems much cleaner and more easy to maintain later on when there is the need to change the html structure.

Is there a way to achieve this and if yes, how would that look like?
I don't need a working solution, just some hints on what to do.

Update: Here is some sample input XML:

<?xml version="1.0" encoding="utf-8" ?>
<Form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="XmlForm.xsd">

   <Validation enabled="false" enableValidationSummary="true" />
   <FieldSet>
      <TextField id="firstInput" css-class="textfield-css-class" />

      <TextField id="secondInput" defaultValue="Wrdlbmrpft">
         Label Text
      </TextField>
   </FieldSet>
</Form>

The output should look like this:

<%@ Control Language="C#" AutoEventWireup="true" Inherits="DevelopmentWeb.WebUserControl1" %>
<asp:TextBox runat="server" ID="firstInput" CssClass="textfield-css-class"></asp:TextBox>
<asp:Label runat="server" AssociatedControlID="secondInput">Label Text</asp:Label>
<asp:TextBox runat="server" ID="secondInput">Wrdlbrmpft</asp:TextBox>

Body:
Define appropriate namespace for prefix asp, e.g.:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:asp="System.Web.UI.WebControls">

In your template simply write:

<asp:TextBox ID="{@id}" runat="server">
    <xsl:if test="@defaultValue">
        <xsl:attribute name="value">
            <xsl:value-of select="@defaultValue"/>
        </xsl:attribute>
    </xsl:if>
</asp:TextBox>


问:
JSON Tree structure with the key Folder on each level
I will make requests to an API that have a folder structure.

Some request may respons with one level, others with 20 levels but I don't want this ugly structure.

Is there any good explanation for doing this recursive without knowing level depth?

```<code>for parent_folder in server_folders['folders']:
    print(parent_folder['name'] + ' (PARENT)')

    for children in parent_folder['folders']:
        print("- " + children['name'])

        for sub_children in children['folders']:
            print("- - " + sub_children['name'])

            for sub_sub_children in sub_children['folders']:
                print("- - - " + sub_sub_children['name'])

                for sub_sub_sub_children in sub_sub_children['folders']:
                    print("- - - " + sub_sub_sub_children['name'])
</code>```

答:
I'd solve this with recursion.

So by creating a method, called nested_list_print, with two parameters,
the nested list that you are looping through, and how deep you want the depth to be.

like so:

def nested_list_print(init_folder, init_depth, depth=0):
    for i in init_folder:
        print('-'*depth + i)
        if depth > 0:
            nested_list(i, init_depth-1, depth+1)
```

Now you can call the method with a depth of ex. 3 like this: nested_list_print(input_list, 3).

Body:
I will make requests to an API that have a folder structure.

Some request may respons with one level, others with 20 levels but I don't want this ugly structure.

Is there any good explanation for doing this recursive without knowing level depth?

for parent_folder in server_folders['folders']:
    print(parent_folder['name'] + ' (PARENT)')

    for children in parent_folder['folders']:
        print("- " + children['name'])

        for sub_children in children['folders']:
            print("- - " + sub_children['name'])

            for sub_sub_children in sub_children['folders']:
                print("- - - " + sub_sub_children['name'])

                for sub_sub_sub_children in sub_sub_children['folders']:
                    print("- - - " + sub_sub_sub_children['name'])

Body:
I'd solve this with recursion.

So by creating a method, called nested_list_print, with two parameters,
the nested list that you are looping through, and how deep you want the depth to be.

like so:

def nested_list_print(init_folder, init_depth, depth=0):
    for i in init_folder:
        print('-'*depth + i)
        if depth > 0:
            nested_list(i, init_depth-1, depth+1)

Now you can call the method with a depth of ex. 3 like this: nested_list_print(input_list, 3).


问:
Create adjacency matrix from a path given as a vector of nodes in base R
Is there a compact and elegant way to create an adjacency matrix given a vector of the form shown (see code excerpt) in base R?

I give my best attempt below. Ideally, I would like to create the already-populated adjacency matrix in a single step as opposed to having to create the matrix data structure then fill it.

p <- 25 # Cardinality of vertex set; Number of nodes

hypothesis_path <- c(17, 7, 6, 1) # path in this form

path_to_D <- function(hypothesis_path, p) {
  path_len <- length(hypothesis_path) - 1
  idx_path <- t(sapply(1:path_len, function(i) hypothesis_path[i:(i+1)]))
  D <- matrix(0, p, p); D[idx_path] <- 1
  D
}

D <- path_to_D(hypothesis_path, p)

which(D == 1, arr.ind = TRUE)

# Desired indices of adjacency matrix are populated (with ones)
#      row col
# [1,]   6   1
# [2,]   7   6
# [3,]  17   7
```

Acceptable answers will avoid use of igraph or similar and will use the path vector in the form given. That said, advice and alternatives are of course always welcomed and appreciated.

答:
You can use the powerful but little-known trick of matrix-based indexing:

index_mat <- rbind(
               c(1, 2),
               c(2, 3),
               c(3, 1)
             )

mat <- matrix(FALSE, 3, 3)
mat[index_mat] <- TRUE
mat
      [,1]  [,2]  [,3]
[1,] FALSE  TRUE FALSE
[2,] FALSE FALSE  TRUE
[3,]  TRUE FALSE FALSE
```
<p>So do this:</p>
<pre class="lang-r prettyprint-override"><code>path_to_D <- function (path, p) {
  indices <- cbind(path[-length(path)], path[-1])
  D <- matrix(0, p, p)
  D[indices] <- 1
  D
}

D <- path_to_D(hypothesis_path, 25)
which(D == 1, arr.ind=TRUE)

     row col
[1,]   6   1
[2,]   7   6
[3,]  17   7

</code>```

Body:
Is there a compact and elegant way to create an adjacency matrix given a vector of the form shown (see code excerpt) in base R?

I give my best attempt below. Ideally, I would like to create the already-populated adjacency matrix in a single step as opposed to having to create the matrix data structure then fill it.

p <- 25 # Cardinality of vertex set; Number of nodes

hypothesis_path <- c(17, 7, 6, 1) # path in this form

path_to_D <- function(hypothesis_path, p) {
  path_len <- length(hypothesis_path) - 1
  idx_path <- t(sapply(1:path_len, function(i) hypothesis_path[i:(i+1)]))
  D <- matrix(0, p, p); D[idx_path] <- 1
  D
}

D <- path_to_D(hypothesis_path, p)

which(D == 1, arr.ind = TRUE)

# Desired indices of adjacency matrix are populated (with ones)
#      row col
# [1,]   6   1
# [2,]   7   6
# [3,]  17   7

Acceptable answers will avoid use of igraph or similar and will use the path vector in the form given. That said, advice and alternatives are of course always welcomed and appreciated.

Body:
You can use the powerful but little-known trick of matrix-based indexing:

index_mat <- rbind(
               c(1, 2),
               c(2, 3),
               c(3, 1)
             )

mat <- matrix(FALSE, 3, 3)
mat[index_mat] <- TRUE
mat
      [,1]  [,2]  [,3]
[1,] FALSE  TRUE FALSE
[2,] FALSE FALSE  TRUE
[3,]  TRUE FALSE FALSE

So do this:

path_to_D <- function (path, p) {
  indices <- cbind(path[-length(path)], path[-1])
  D <- matrix(0, p, p)
  D[indices] <- 1
  D
}

D <- path_to_D(hypothesis_path, 25)
which(D == 1, arr.ind=TRUE)

     row col
[1,]   6   1
[2,]   7   6
[3,]  17   7


问:
GKE upgrading Kubernetes cluster from 1.21.6-gke.1500 to 1.22.3-gke.1500 fails
I've noticed that Kubernetes 1.22.3-gke.1500 version is available in GKE's Regular channel. My cluster is in version 1.21.6-gke.1500 (master and node pool). I am trying to upgrade to newer version, but I get an error:

Master version "1.22.3-gke.1500" is unsupported.

No further explanations or details. Why is the newer version unsupported? How can I fix that?

答:
Use gcloud container get-server-config --region {your-region} to see what versions your region supports. For example, I'm in europe-west2

```<code>$ gcloud container get-server-config --region europe-west2
Fetching server config for europe-west2
channels:
- channel: RAPID
  defaultVersion: 1.22.3-gke.1500
  validVersions:
  - 1.23.1-gke.500
  - 1.22.4-gke.1501
  - 1.22.3-gke.1500
  - 1.22.3-gke.700
  - 1.21.6-gke.1500
  - 1.21.5-gke.1802
- channel: REGULAR
  defaultVersion: 1.21.6-gke.1500
  validVersions:
  - 1.21.6-gke.1500
  - 1.21.5-gke.1802
  - 1.20.12-gke.1500
  - 1.20.11-gke.1801
- channel: STABLE
  defaultVersion: 1.20.12-gke.1500
  validVersions:
  - 1.21.5-gke.1802
  - 1.20.12-gke.1500
  - 1.20.11-gke.1801
  - 1.20.11-gke.1300
  - 1.19.15-gke.1801
...
</code>```

So in this scenario, if your cluster is on RAPID channel, then 1.22.3-gke.1500 is supported. But if it's on REGULAR or STABLE, it will not be.

Additionally, the updates to the available releases may take a few days. Just because a release note might say it's available does not mean its immediately available.

Body:
Use gcloud container get-server-config --region {your-region} to see what versions your region supports. For example, I'm in europe-west2

$ gcloud container get-server-config --region europe-west2
Fetching server config for europe-west2
channels:
- channel: RAPID
  defaultVersion: 1.22.3-gke.1500
  validVersions:
  - 1.23.1-gke.500
  - 1.22.4-gke.1501
  - 1.22.3-gke.1500
  - 1.22.3-gke.700
  - 1.21.6-gke.1500
  - 1.21.5-gke.1802
- channel: REGULAR
  defaultVersion: 1.21.6-gke.1500
  validVersions:
  - 1.21.6-gke.1500
  - 1.21.5-gke.1802
  - 1.20.12-gke.1500
  - 1.20.11-gke.1801
- channel: STABLE
  defaultVersion: 1.20.12-gke.1500
  validVersions:
  - 1.21.5-gke.1802
  - 1.20.12-gke.1500
  - 1.20.11-gke.1801
  - 1.20.11-gke.1300
  - 1.19.15-gke.1801
...

So in this scenario, if your cluster is on RAPID channel, then 1.22.3-gke.1500 is supported. But if it's on REGULAR or STABLE, it will not be.

Additionally, the updates to the available releases may take a few days. Just because a release note might say it's available does not mean its immediately available.


问:
Class AMSupportURLConnectionDelegate is implemented in both
I'm trying to build a flutter app on M1 mac and getting the following error.

```<code>$ flutter build ios --release
Building XXX for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: XXX
Running pod install...                                             13.2s
Running Xcode build...
Xcode build done.                                            6.7s
Failed to build iOS app
Error output from Xcode build:
↳
    objc[65074]: Class AMSupportURLConnectionDelegate is implemented in both ?? (0x1f66de518) and ?? (0x1160d82b8). One
    of the two will be used. Which one is undefined.
    objc[65074]: Class AMSupportURLSession is implemented in both ?? (0x1f66de568) and ?? (0x1160d8308). One of the two
    will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    error: The linked framework 'Pods_Runner.framework' is missing one or more architectures required by this target:
    armv7. (in target 'Runner' from project 'Runner')

Encountered error while building for device.
</code>```

Here is my flutter doctor -v

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 1.22.4, on macOS 11.0 20A2411 darwin-arm, locale en-AU)
    • Flutter version 1.22.4 at /Users/mlee/development/flutter
    • Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/mlee/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[!] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (2 available)

! Doctor found issues in 1 category.
</code>```

答:
This was quite a journey for me to fix. I tried many things and I'm not exactly sure which one fixed it but here's what I did

First off try building the app for Android instead of iOS. This will tell you if the error is specific to iOS or if it's something else. After building for android I had the error "member not found package root". To fix this I did

```<code>flutter pub upgrade
</code>```

I use Apple silicon, I ran this command

```<code>sudo gem install ffi
</code>```

Along my journey of fixing this I realized I use the system ruby when I should be using homebrew installed ruby

```<code>brew install ruby
echo 'export PATH="/usr/local/opt/ruby/bin:$PATH"' >> ~/.zshrc
</code>```

uninstall all cocoapods from gem

```<code>gem list --local | grep cocoapods | awk '{print $1}' | xargs sudo gem uninstall
</code>```

install cococapods from brew

```<code>brew install cocoapods
</code>```

then try and rebuild your project

Body:
I'm trying to build a flutter app on M1 mac and getting the following error.

$ flutter build ios --release
Building XXX for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: XXX
Running pod install...                                             13.2s
Running Xcode build...
Xcode build done.                                            6.7s
Failed to build iOS app
Error output from Xcode build:
↳
    objc[65074]: Class AMSupportURLConnectionDelegate is implemented in both ?? (0x1f66de518) and ?? (0x1160d82b8). One
    of the two will be used. Which one is undefined.
    objc[65074]: Class AMSupportURLSession is implemented in both ?? (0x1f66de568) and ?? (0x1160d8308). One of the two
    will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    error: The linked framework 'Pods_Runner.framework' is missing one or more architectures required by this target:
    armv7. (in target 'Runner' from project 'Runner')

Encountered error while building for device.

Here is my flutter doctor -v

flutter doctor -v
[✓] Flutter (Channel stable, 1.22.4, on macOS 11.0 20A2411 darwin-arm, locale en-AU)
    • Flutter version 1.22.4 at /Users/mlee/development/flutter
    • Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/mlee/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[!] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (2 available)

! Doctor found issues in 1 category.

Body:
This was quite a journey for me to fix. I tried many things and I'm not exactly sure which one fixed it but here's what I did

First off try building the app for Android instead of iOS. This will tell you if the error is specific to iOS or if it's something else. After building for android I had the error "member not found package root". To fix this I did

flutter pub upgrade

I use Apple silicon, I ran this command

sudo gem install ffi

Along my journey of fixing this I realized I use the system ruby when I should be using homebrew installed ruby

brew install ruby
echo 'export PATH="/usr/local/opt/ruby/bin:$PATH"' >> ~/.zshrc

uninstall all cocoapods from gem

gem list --local | grep cocoapods | awk '{print $1}' | xargs sudo gem uninstall

install cococapods from brew

brew install cocoapods

then try and rebuild your project


问:
Generate const array of pointers to callback functions
I'd like to generate an array of N pointers to callbacks so I don't have to type them explicitly (LOC is not the issue here).
I use C++17.

Here is what I have:

```<code>using Callback = void(*)();
auto constexpr N = 2;

const Callback callbacks[N] = {
 [](){ auto i = 0; std::cout<<"callback " << i << "\n";},
 [](){ auto i = 1; std::cout<<"callback " << i << "\n";}
};

callbacks[0]();
callbacks[N-1]();
</code>```

Here is what I want:

```<code>const auto callbacks = generate_callbacks<N>();  // or generate_callbacks(N)
callbacks[i](); // cout<<"callback " << i << "\n";
</code>```

I tried various ways, but I keep running into the problems with constant parameters even when they are from a constexpr function or variadic template.

If I try this:

```<code>Callback callbacks[N] = { };

for(int i=0;i<N;++i)
{
callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};
}

for(int i=0;i<N;++i)
{
callbacks[i]();
}
</code>```

I get the following error:

```<code>main.cpp:91:66: error: cannot convert ‘main()::’ to ‘Callback {aka void (*)()}’ in assignment
        callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};
</code>```

If I make i static and leave out the capture it only uses the last value of i:

```<code>callback 2
callback 2
</code>```

This is odd to me as capturing should be done at construction. Are the lambdas constructed after the loop exits?

As for the purpose. I want to apply this technique to generating interrupt handlers for microcontrollers. I can put the function pointers in the interrupt vector table directly. These functions have no parameters and I don't know a clean way to detect which interrupt source called the handler. I can write a handler for each interrupt, but I don't like repeating this code 6 times:

```<code>void handler0()
{
  do_something(0);
}
</code>```

Typing it as a lambda and/or using a template makes it a little cleaner, but I still have to type something N times. And if N changes I have to change multiple lines of code. This is not elegant.

答:
Off Topic Suggestion: don't use, when you can, C-styles arrays but C++ std::array.

For example: the following line

```<code>const auto callbacks = generate_callbacks<N>();
</code>```

can't works if you want that callbacks is a C-style array (a function can't return that type) but works when generate_callback() return a std::array<Callback, N> instance.

End of Off Topic Suggestion.

In this particular case, given that N is a constexpr value, I propose the use of template meta-programming.

So I suggest the following generate_callbacks() function, that just create a sequence of template values from zero to N-1 and call an helper function

```<code>template <std::size_t N>
auto generate_callbacks ()
{ return gc_helper(std::make_index_sequence<N>{}); }
</code>```

and a simple helper function that uses the template values and create the callbacks lambdas without capturing them (so remaining convertible to function pointers)

```<code>template <std::size_t ... Is>
std::array<Callback, sizeof...(Is)> gc_helper (std::index_sequence<Is...>)
{ return {{ []{ auto i = Is; std::cout<<"callback " << i << "\n"; }... }}; }
</code>```

If you can use C++20, using template lambdas you can avoid the external gc_helper() function and make all inside generate_callbacks() as follows

```<code>template <std::size_t N>
auto generate_callbacks ()
{
  return []<std::size_t ... Is>(std::index_sequence<Is...>)
    -> std::array<Callback, N>
  { return {{ []{ std::cout<<"callback " << Is << "\n"; }... }}; }
  (std::make_index_sequence<N>{});
}
</code>```

The following is a full compiling <s>C++17</s> C++14 example

```<code>#include <iostream>
#include <utility>
#include <array>

using Callback = void(*)();
auto constexpr N = 2;

template <std::size_t ... Is>
std::array<Callback, sizeof...(Is)> gc_helper (std::index_sequence<Is...>)
{ return {{ []{ auto i = Is; std::cout<<"callback " << i << "\n"; }... }}; }

template <std::size_t N>
auto generate_callbacks ()
{ return gc_helper(std::make_index_sequence<N>{}); }

int main()
{
  const auto callbacks = generate_callbacks<N>();

  for ( auto ui = 0 ; ui < N ; ++ui )
    callbacks[ui]();
}
</code>```

Body:
I'd like to generate an array of N pointers to callbacks so I don't have to type them explicitly (LOC is not the issue here).
I use C++17.

Here is what I have:

using Callback = void(*)();
auto constexpr N = 2;

const Callback callbacks[N] = {
 [](){ auto i = 0; std::cout<<"callback " << i << "\n";},
 [](){ auto i = 1; std::cout<<"callback " << i << "\n";}
};

callbacks[0]();
callbacks[N-1]();

Here is what I want:

const auto callbacks = generate_callbacks<N>();  // or generate_callbacks(N)
callbacks[i](); // cout<<"callback " << i << "\n";

I tried various ways, but I keep running into the problems with constant parameters even when they are from a constexpr function or variadic template.

If I try this:

Callback callbacks[N] = { };

for(int i=0;i<N;++i)
{
callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};
}

for(int i=0;i<N;++i)
{
callbacks[i]();
}

I get the following error:

main.cpp:91:66: error: cannot convert ‘main()::’ to ‘Callback {aka void (*)()}’ in assignment
        callbacks[i] = [i](){ std::cout<<"callback " << i << "\n";};

If I make i static and leave out the capture it only uses the last value of i:

callback 2
callback 2

This is odd to me as capturing should be done at construction. Are the lambdas constructed after the loop exits?

As for the purpose. I want to apply this technique to generating interrupt handlers for microcontrollers. I can put the function pointers in the interrupt vector table directly. These functions have no parameters and I don't know a clean way to detect which interrupt source called the handler. I can write a handler for each interrupt, but I don't like repeating this code 6 times:

void handler0()
{
  do_something(0);
}

Typing it as a lambda and/or using a template makes it a little cleaner, but I still have to type something N times. And if N changes I have to change multiple lines of code. This is not elegant.

Body:
Off Topic Suggestion: don't use, when you can, C-styles arrays but C++ std::array.

For example: the following line

const auto callbacks = generate_callbacks<N>();

can't works if you want that callbacks is a C-style array (a function can't return that type) but works when generate_callback() return a std::array<Callback, N> instance.

End of Off Topic Suggestion.

In this particular case, given that N is a constexpr value, I propose the use of template meta-programming.

So I suggest the following generate_callbacks() function, that just create a sequence of template values from zero to N-1 and call an helper function

template <std::size_t N>
auto generate_callbacks ()
{ return gc_helper(std::make_index_sequence<N>{}); }

and a simple helper function that uses the template values and create the callbacks lambdas without capturing them (so remaining convertible to function pointers)

template <std::size_t ... Is>
std::array<Callback, sizeof...(Is)> gc_helper (std::index_sequence<Is...>)
{ return {{ []{ auto i = Is; std::cout<<"callback " << i << "\n"; }... }}; }

If you can use C++20, using template lambdas you can avoid the external gc_helper() function and make all inside generate_callbacks() as follows

template <std::size_t N>
auto generate_callbacks ()
{
  return []<std::size_t ... Is>(std::index_sequence<Is...>)
    -> std::array<Callback, N>
  { return {{ []{ std::cout<<"callback " << Is << "\n"; }... }}; }
  (std::make_index_sequence<N>{});
}

The following is a full compiling <s>C++17</s> C++14 example

#include <iostream>
#include <utility>
#include <array>

using Callback = void(*)();
auto constexpr N = 2;

template <std::size_t ... Is>
std::array<Callback, sizeof...(Is)> gc_helper (std::index_sequence<Is...>)
{ return {{ []{ auto i = Is; std::cout<<"callback " << i << "\n"; }... }}; }

template <std::size_t N>
auto generate_callbacks ()
{ return gc_helper(std::make_index_sequence<N>{}); }

int main()
{
  const auto callbacks = generate_callbacks<N>();

  for ( auto ui = 0 ; ui < N ; ++ui )
    callbacks[ui]();
}


问:
OpenCV VideoWriter Error "dimensions too large for MPEG-4"
I have some frames (dimensions: 8192x2160) that are generated from concatenating two 4096x2160 frames side by side. When writing these frames to a video file using OpenCV VideoWriter, I get this error: dimensions too large for MPEG-4

Here is my code:

```<code>video_name = "vid.mp4"

images = sorted([img for img in os.listdir(images_folder) if img.endswith(".png")])

frame = cv2.imread(os.path.join(images_folder, images[0]))
height, width, layers = frame.shape

fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, FRAME_RATE, (width, height))

for image in images:
    video.write(cv2.imread(os.path.join(images_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

This didn't work either:

```<code>video_name = "output.avi"
video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 10, (width, height))
</code>```

Does anyone have any suggestions?

答:
DivX is related to MPEG-4 Part 2 and H.263.

Those video format specifications can't handle that size of frame. They have limits by design, that are below your requirements. No codec (implementation) can work around that.

If you need that size of frame handled, you'll need a different format.

You'd need to research available formats/codecs and see if they're suitable.

More modern formats/codecs have a better chance of being designed for large frame sizes. HEVC, AV1, ... might be suitable.

Some non-modern formats/codecs might not have this limitation either. MJPEG (MJPG) will work (just tested this). It's built into OpenCV, always there. Ffmpeg also has an implementation, so that's a very compatible choice of codec.

Body:
I have some frames (dimensions: 8192x2160) that are generated from concatenating two 4096x2160 frames side by side. When writing these frames to a video file using OpenCV VideoWriter, I get this error: dimensions too large for MPEG-4

Here is my code:

video_name = "vid.mp4"

images = sorted([img for img in os.listdir(images_folder) if img.endswith(".png")])

frame = cv2.imread(os.path.join(images_folder, images[0]))
height, width, layers = frame.shape

fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, FRAME_RATE, (width, height))

for image in images:
    video.write(cv2.imread(os.path.join(images_folder, image)))

cv2.destroyAllWindows()
video.release()

This didn't work either:

video_name = "output.avi"
video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 10, (width, height))

Does anyone have any suggestions?


问:
Plant UML in Visual Studio Code // Config file
I'm using Plant UML in VS-Code to generate diagrams: https://marketplace.visualstudio.com/items?itemName=jebbs.plantuml

I want to edit the global default extension setting:

Set input folder for the .puml files and ...

the output folder for the generated .png files

Question: I can't find the config file with the Export Settings for PlantUML in VS Code. Where could I find it, or how shall it be set up correctly to work with the IDE?

答:
On vscode

Go to File --> Preferences --> Settings

Search for plantuml and you will be presented by screen below

Change export format

Set output folder, default is out

uncheck the box if you don't want subfolder created, check if you want subfolder

Test