问:
Dart FormatException: Unexpected character (at character 1) in empty json
Basically what the title says, simply trying to implement a condition that either writes to a an existing file or decodes the json and then writes to the same file.
code:

```<code>import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';

void main() async{
    print("hello");
    int prio1;
    print("Title:");
     String? title1 = stdin.readLineSync();
    print("description:");
     String? des = stdin.readLineSync();

    ToDo test = new ToDo(title1, des, 0, false);
    String  test11 = jsonEncode(test);

    print(test11);
    final filename = 'vault.json';
    if(File(filename).length == 0)
    {
      new File(filename).writeAsString("["+test11+"]");
    }
    else{
      String test = await jsonDecode(filename);
      String test2 = test.substring(0, test.length - 1);
      String test3 = ","+test2 +"]";
      new File(filename).writeAsString(test3);
    }

}
</code>```

my json file "vault.json" is empty, yet I get this error:

```<code>Unhandled exception:
FormatException: Unexpected character (at character 1)
vault.json
^

#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1272:9)
#2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:937:22)
#3      _parseJson (dart:convert-patch/convert_patch.dart:40:10)
#4      JsonDecoder.convert (dart:convert/json.dart:612:36)
#5      JsonCodec.decode (dart:convert/json.dart:216:41)
#6      jsonDecode (dart:convert/json.dart:155:10)
#7      main (file:///D:/Code/dart/json/json.dart:23:27)
#8      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#9      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
</code>```

any help appreciated!

edit:added ToDo.dart in case you want to run the program

```<code>class ToDo {
    String? title,description;
    int prio;
    bool completed;

    ToDo(this.title, this.description, this.prio, this.completed);

    ToDo.fromJson(Map<String,dynamic> json):
        title = json['title'],
        description = json['description'],
        prio = json['prio'],
        completed = json['completed'];

    Map<String,dynamic> toJson() => {
        'title':title,
        'description':description,
        'prio':prio,
        'completed':completed,
    };

}
</code>```

答:
I am not exactly sure what you want to achieve but this snippets lets you read and write into that json file.

Please notice that we have to read the json from the file first with readAsLinesSync before decoding. This caused your error, since you didn't try to decode the json object (for example [{"title":"test","description":"test","prio":0,"completed":false}] but just the file name (vault.json), which of course isn't a valid json.

```<code>import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';

void main() async{
  const filename = 'vault.json';
  print('Enter title');
  String? title = stdin.readLineSync();
  print('Enter description');
  String? description = stdin.readLineSync();

  final file = File(filename);
  final fileIsEmpty = await file.length() == 0;

  if(fileIsEmpty)
  {
    // create a test ToDO
    ToDo testToDo = ToDo(title, description, 0, false);
    String  test11 = jsonEncode(testToDo);

    // write to File
    await File(filename).writeAsString(test11);
  }
  else {
    // read the ToDO from the file
    final json = File(filename).readAsLinesSync();
    final encode = jsonDecode(json.first);
    ToDo storedToDo = ToDo.fromJson(encode);
    print(storedToDo);
  }
}
</code>```

Also consider using snake case for your file names, which is best practice.

Happy coding!

Body:
Basically what the title says, simply trying to implement a condition that either writes to a an existing file or decodes the json and then writes to the same file.
code:

import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';

void main() async{
    print("hello");
    int prio1;
    print("Title:");
     String? title1 = stdin.readLineSync();
    print("description:");
     String? des = stdin.readLineSync();

    ToDo test = new ToDo(title1, des, 0, false);
    String  test11 = jsonEncode(test);

    print(test11);
    final filename = 'vault.json';
    if(File(filename).length == 0)
    {
      new File(filename).writeAsString("["+test11+"]");
    }
    else{
      String test = await jsonDecode(filename);
      String test2 = test.substring(0, test.length - 1);
      String test3 = ","+test2 +"]";
      new File(filename).writeAsString(test3);
    }

}

my json file "vault.json" is empty, yet I get this error:

Unhandled exception:
FormatException: Unexpected character (at character 1)
vault.json
^

#0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1272:9)
#2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:937:22)
#3      _parseJson (dart:convert-patch/convert_patch.dart:40:10)
#4      JsonDecoder.convert (dart:convert/json.dart:612:36)
#5      JsonCodec.decode (dart:convert/json.dart:216:41)
#6      jsonDecode (dart:convert/json.dart:155:10)
#7      main (file:///D:/Code/dart/json/json.dart:23:27)
#8      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#9      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

any help appreciated!

edit:added ToDo.dart in case you want to run the program

class ToDo {
    String? title,description;
    int prio;
    bool completed;

    ToDo(this.title, this.description, this.prio, this.completed);

    ToDo.fromJson(Map<String,dynamic> json):
        title = json['title'],
        description = json['description'],
        prio = json['prio'],
        completed = json['completed'];

    Map<String,dynamic> toJson() => {
        'title':title,
        'description':description,
        'prio':prio,
        'completed':completed,
    };

}

Body:
I am not exactly sure what you want to achieve but this snippets lets you read and write into that json file.

Please notice that we have to read the json from the file first with readAsLinesSync before decoding. This caused your error, since you didn't try to decode the json object (for example [{"title":"test","description":"test","prio":0,"completed":false}] but just the file name (vault.json), which of course isn't a valid json.

import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';

void main() async{
  const filename = 'vault.json';
  print('Enter title');
  String? title = stdin.readLineSync();
  print('Enter description');
  String? description = stdin.readLineSync();

  final file = File(filename);
  final fileIsEmpty = await file.length() == 0;

  if(fileIsEmpty)
  {
    // create a test ToDO
    ToDo testToDo = ToDo(title, description, 0, false);
    String  test11 = jsonEncode(testToDo);

    // write to File
    await File(filename).writeAsString(test11);
  }
  else {
    // read the ToDO from the file
    final json = File(filename).readAsLinesSync();
    final encode = jsonDecode(json.first);
    ToDo storedToDo = ToDo.fromJson(encode);
    print(storedToDo);
  }
}

Also consider using snake case for your file names, which is best practice.

Happy coding!


来源: stackexchange

问:
meaning of --sysroot=$SDKTARGETSYSROOT?
HAve something very puzzling(or sound strange to me). Wish to have some clearer explanation from you guys

Have been cross compiling a file using  environmental-setup-file (environment-setup-aarch64-poky-linux) from a Yocto Distribution for an arm  . I understand it is to set environment (by using source environment-setup-file)

It contains

SDKTARGETSYSROOT (I understand it is the representative minimal target where it holds the header and library file needed to cross compile the code)

PATH (somewhat like the PATH usage in your own environment but somewhat different as it is pertaining to the target)

What I find confusing is that the location of toolchain. Isnt it supposed to be found in SDKTARGETSYSROOT (The toolchain is set by others, SDKTARGETSYSROOT= /opt/fsl-imx-xwayland/4.14-sumo/environment-setup-aarch64-poky-linux ) ? I find my aarch64-poky-linux-gcc to be found in directory outside that of SDKTARGETSYSROOT  (though the gcc is found in PATH,, /opt/fsl-imx-xwayland/4.14-sumo/sysroots/x86_64-pokysdk-linux/usr/bin/aarch64-poky-linux)

Is there a rationale for doing this way? I have been coding the codes but would like to learn why this is so?

Thanks

答:
This has got to do more with the cross canadian compiler (GCC in this case) rather than Yocto, the Yocto Project wires its compiler logic  using the --sysroot argument passed to GCC:
https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html

This tells GCC to treat whats passed as --sysroot as if it was the sysroot on a typical compilation on target, e.g. usually GCC expects to find headers in /usr/include or libraries in /usr/lib , if we pass --sysroot=/foo/ then it will automatically look at /foo/usr/include and /foo/usr/lib respectively.

The toolchain scripts in the Yocto Project use --sysroot=SDKTARGETSYSROOT to pass the directory where the SDK is installed, hence it finds the proper header and libs to be able to cross compile from the SDK, for more info: https://git.yoctoproject.org/poky/tree/meta/classes/toolchain-scripts.bbclass

Now why is GCC outside that directory?, because that directory only contains files for the target architecture (hence SDKTARGETSYSROOT, SDK: for the SDK, TARGET: meant for the target arch, SYSROOT: the sysroot to be used), and GCC is not.
GCC is compiled to run in your HOST, hence it doesnt belong in that directory, it is precisely why you see the x86_64-pokysdk-linux part of the path where GCC is actually installed in, your HOST triplet is a 64 bit x86 architecture, an SDK built by poky (Yocto), and its OS is Linux.

ContentLicense: CC BY-SA 4.0

Title: meaning of --sysroot=$SDKTARGETSYSROOT?


问:
NHibernate 2 + Fluent Nhibernate medium trust
Will NHibernate 2 and\or Fluent Nhibernate work in a medium trust environment. If not are there any work-arounds?</p>

答:
Not sure about fluent NH - I assume it should - it just translates to XML.

With NH itself you will loose bytecode optimization, all your setters/constructors will need to be public. If you need to use lazy loading you will have to have your proxies generated with build (NH proxy generator).

Should you have some permissions enabled in your medium trust settings you can relax some of the restrictions.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rashack

LastEditorDisplayName: Rashack


问:
Removing the .0 from a double
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

```<code>double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);
</code>```

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86

答:
Use DecimalFormat</p>

```<code>double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Removing the .0 from a double

Body:
I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);

this work's fine up to about 1e18 then will error out because of the maximum size of a Long.
So how would I achieve this on bigger numbers like 5.43e86

Body:
Use DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));


问:
How to change `this` in a lambda function returned by a getter
I have defined a class containing a getter returning a lambda function.
I'd like to change the "this" used in the function returned, but  I did not find any way to do that. I made many tries with function.call but no matter what, I did not get the expected result. So I need help!

Here is some minimal code reproducing the problem:

```<code>class A {
    get fn() { return () => [this.name, this]; }
}
let a = new A();
a.name = "a";
let b = { name: "b" };
window.console.log(a.fn.call(b)); // How to get "b" ?
</code>```

The result is :

```<code>[
  "a",
  {
    "name": "a"
  }
]
</code>```

How to apply the returned lambda function to b ? and receive the expected result:

```<code>[
  "b",
  {
    "name": "b"
  }
]
</code>```

答:
You need to take a standard function instead of an arrow function.

class A {
    get fn() { return function () { return [this.name, this]; } }
}
let a = new A();
a.name = "a";
let b = { name: "b" };

console.log(a.fn.call(b)); // How to get "b" ?```

Body:
I have defined a class containing a getter returning a lambda function.
I'd like to change the "this" used in the function returned, but  I did not find any way to do that. I made many tries with function.call but no matter what, I did not get the expected result. So I need help!

Here is some minimal code reproducing the problem:

class A {
    get fn() { return () => [this.name, this]; }
}
let a = new A();
a.name = "a";
let b = { name: "b" };
window.console.log(a.fn.call(b)); // How to get "b" ?

The result is :

[
  "a",
  {
    "name": "a"
  }
]

How to apply the returned lambda function to b ? and receive the expected result:

[
  "b",
  {
    "name": "b"
  }
]


问:
ModuleNotFoundError: No module named 'azure.cognitiveservices.vision.customvision'
I am trying to use the microsoft azure custom vision service on a mac from Jupyter in VS Code

I have Python 3.8.3 installed.

I have done pip install azure.cognitiveservices.vision.customvision and confirmed it is there using pip show.

When I execute the command
from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient

I get the error:

ModuleNotFoundError: No module named 'azure.cognitiveservices.vision.customvision'

I have tried adding the location where the package is installed to $PATH but that does not fix the problem.

Any thoughts gratefully received! thx

答:
Whenever U get: ModuleNotFoundError, the simple solution is to install the module using

```<code>pip install (module name)
</code>```

For example, in your case try to run the following line:

```<code>!pip install azure
</code>```

The ! is to run a command in a notebook.

Body:
Whenever U get: ModuleNotFoundError, the simple solution is to install the module using

pip install (module name)

For example, in your case try to run the following line:

!pip install azure

The ! is to run a command in a notebook.


答:
Your code is too complicated. Here is how to simplify:

the arguments to the merge function should be l, the index to the start of the first slice, m the index to the second slice, r the index past the end of the second slice.

this way the slice widths are easier to compute.

extracting the slices to merge becomes trivial

and it is also simpler to determine which part of the array to call merge with: l will be an even multiple of width and m the next odd multiple.

Here is a modified version:

```<code>import random

def mergeSort(a):

    width = 1
    n = len(a)

    while (width < n):
        l = 0
        while (l + width < n):
            r = min(l + width * 2, n)
            merge(a, l, l + width, r)
            l += width * 2

        width *= 2
    return a

def merge(a, l, m, r):
    n1 = m - l
    n2 = r - m
    L = a[l : m]
    R = a[m : r]

    i = 0
    j = 0
    k = l
    while i < n1 and j < n2:
        if L[i] > R[j]:
            a[k] = R[j]
            j += 1
        else:
            a[k] = L[i]
            i += 1
        k += 1

    while i < n1:
        a[k] = L[i]
        i += 1
        k += 1

    while j < n2:
        a[k] = R[j]
        j += 1
        k += 1

def create_random_list(n):
    L = []
    for _ in range(n):
        L.append(random.randint(1,n))
    return L

a = create_random_list(100)
print("Given array is ")
print(a)

mergeSort(a)

print("Sorted array is ")
print(a)
</code>```

Output:

```<code>Given array is
[68, 78, 20, 77, 87, 68, 2, 80, 58, 49, 91, 45, 12, 38, 4, 90, 41,
 29, 68, 10, 85, 64, 41, 71, 24, 77, 99, 96, 88, 14, 58, 51, 82, 63,
 25, 44, 23, 100, 25, 26, 49, 50, 83, 55, 8, 30, 37, 78, 12, 80, 86,
 88, 86, 9, 88, 62, 58, 100, 10, 69, 62, 46, 29, 75, 12, 22, 15, 15,
 22, 95, 48, 26, 66, 55, 14, 77, 8, 68, 73, 2, 50, 86, 91, 9, 70, 11,
 3, 50, 69, 53, 79, 47, 94, 79, 16, 81, 63, 79, 47, 75]
Sorted array is
[2, 2, 3, 4, 8, 8, 9, 9, 10, 10, 11, 12, 12, 12, 14, 14, 15, 15, 16,
 20, 22, 22, 23, 24, 25, 25, 26, 26, 29, 29, 30, 37, 38, 41, 41, 44,
 45, 46, 47, 47, 48, 49, 49, 50, 50, 50, 51, 53, 55, 55, 58, 58, 58,
 62, 62, 63, 63, 64, 66, 68, 68, 68, 68, 69, 69, 70, 71, 73, 75, 75,
 77, 77, 77, 78, 78, 79, 79, 79, 80, 80, 81, 82, 83, 85, 86, 86, 86,
 87, 88, 88, 88, 90, 91, 91, 94, 95, 96, 99, 100, 100]
</code>```

Title: Mergesort Implementation gone wrong

Body:
Output not as expected

import random

def mergeSort(a):

    width = 1
    n = len(a)

    while (width < n):

        l = 0
        while (l < n):
            r = min(l + (width * 2 - 1), n - 1)
            m = (l + r) // 2

            if (width > n // 2):
                m = r - ( n % width)
            merge(a, l, m, r)
            l += width * 2

        width *= 2
    return a

def merge(a, l, m, r):
    n1 = m - l + 1
    n2 = r - m
    L = [0] * n1
    R = [0] * n2
    for i in range(0, n1):
        L[i] = a[l + i]
    for i in range(0, n2):
        R[i] = a[m + i + 1]

    i = 0
    j = 0
    k = l
    while (i < n1) and (j < n2):
        if L[i] > R[j]:
            a[k] = R[j]
            j += 1
        else:
            a[k] = L[i]
            i += 1
        k += 1

    while i < n1:
        a[k] = L[i]
        i += 1
        k += 1

    while j < n2:
        a[k] = R[j]
        j += 1
        k += 1

def create_random_list(n):
    L = []
    for _ in range(n):
        L.append(random.randint(1,n))
    return L

a = create_random_list(100)
print("Given array is ")
print(a)

mergeSort(a)

print("Sorted array is ")
print(a)```

output

Given array is
[54, 17, 12, 61, 54, 13, 42, 82, 14, 65, 72, 11, 38, 76, 75, 56, 30, 1, 48, 52, 49, 88, 62, 94, 37, 98, 99, 79, 2, 77, 16, 67, 94, 14, 11, 24, 25, 20, 55, 92, 83, 85, 99, 50, 93, 49, 91, 73, 24, 84, 68, 21, 100, 4, 54, 65, 43, 74, 43, 60, 9, 27, 68, 15, 71, 39, 19, 69, 87, 56, 63, 56, 56, 70, 1, 51, 4, 87, 84, 7, 92, 30, 97, 74, 34, 45, 89, 33, 13, 41, 14, 92, 46, 8, 28, 72, 72, 37, 34, 64]

Sorted array is
[1, 1, 2, 4, 4, 7, 8, 9, 11, 11, 12, 13, 13, 14, 14, 14, 15, 16, 17, 19, 20, 21, 24, 24, 25, 27, 28, 30, 30, 33, 34, 37, 38, 39, 41, 42, 43, 43, 45, 46, 48, 49, 49, 50, 51, 52, 54, 54, 54, 55, 56, 56, 56, 56, 60, 61, 62, 63, 65, 65, 67, 68, 68, 69, 70, 71, 72, 72, 73, 74, 74, 75, 76, 77, 79, 82, 83, 84, 84, 85, 87, 87, 88, 89, 91, 92, 92, 92, 93, 94, 94, 97, 34, 37, 64, 72, 98, 99, 99, 100]

Body:
Your code is too complicated. Here is how to simplify:

the arguments to the merge function should be l, the index to the start of the first slice, m the index to the second slice, r the index past the end of the second slice.

this way the slice widths are easier to compute.

extracting the slices to merge becomes trivial

and it is also simpler to determine which part of the array to call merge with: l will be an even multiple of width and m the next odd multiple.

Here is a modified version:

import random

def mergeSort(a):

    width = 1
    n = len(a)

    while (width < n):
        l = 0
        while (l + width < n):
            r = min(l + width * 2, n)
            merge(a, l, l + width, r)
            l += width * 2

        width *= 2
    return a

def merge(a, l, m, r):
    n1 = m - l
    n2 = r - m
    L = a[l : m]
    R = a[m : r]

    i = 0
    j = 0
    k = l
    while i < n1 and j < n2:
        if L[i] > R[j]:
            a[k] = R[j]
            j += 1
        else:
            a[k] = L[i]
            i += 1
        k += 1

    while i < n1:
        a[k] = L[i]
        i += 1
        k += 1

    while j < n2:
        a[k] = R[j]
        j += 1
        k += 1

def create_random_list(n):
    L = []
    for _ in range(n):
        L.append(random.randint(1,n))
    return L

a = create_random_list(100)
print("Given array is ")
print(a)

mergeSort(a)

print("Sorted array is ")
print(a)

Output:

Given array is
[68, 78, 20, 77, 87, 68, 2, 80, 58, 49, 91, 45, 12, 38, 4, 90, 41,
 29, 68, 10, 85, 64, 41, 71, 24, 77, 99, 96, 88, 14, 58, 51, 82, 63,
 25, 44, 23, 100, 25, 26, 49, 50, 83, 55, 8, 30, 37, 78, 12, 80, 86,
 88, 86, 9, 88, 62, 58, 100, 10, 69, 62, 46, 29, 75, 12, 22, 15, 15,
 22, 95, 48, 26, 66, 55, 14, 77, 8, 68, 73, 2, 50, 86, 91, 9, 70, 11,
 3, 50, 69, 53, 79, 47, 94, 79, 16, 81, 63, 79, 47, 75]
Sorted array is
[2, 2, 3, 4, 8, 8, 9, 9, 10, 10, 11, 12, 12, 12, 14, 14, 15, 15, 16,
 20, 22, 22, 23, 24, 25, 25, 26, 26, 29, 29, 30, 37, 38, 41, 41, 44,
 45, 46, 47, 47, 48, 49, 49, 50, 50, 50, 51, 53, 55, 55, 58, 58, 58,
 62, 62, 63, 63, 64, 66, 68, 68, 68, 68, 69, 69, 70, 71, 73, 75, 75,
 77, 77, 77, 78, 78, 79, 79, 79, 80, 80, 81, 82, 83, 85, 86, 86, 86,
 87, 88, 88, 88, 90, 91, 91, 94, 95, 96, 99, 100, 100]


问:
How can I hide/show components by touching not button but screen on React Native?
I'm learning React Native for the first time. I want to implement a function to show/hide the component by touching the screen, not a specific button.

(Please check the attached file for the example image.)

enter image description here

In this code, I've tried to make a function. if I touch the screen (<View style={style.center}>, then show/hide the renderChatGroup() and renderListMessages() included in <View style={style.footer}>. The source code is below.

In my code, it works. However, the two <View> tag is not parallel. the footer view is center View's child.

I want to make them parallel. but I couldn't find the contents about controlling another <View> tag, not a child. In this code, I used setState, then I couldn't control another the below <View>.

Of course, I tried Fragment tag, but it didn't render anything.

How could I do implement this function? Please help me!

    export default class Streamer extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isVisibleFooter: true,
        };
    }

    renderChatGroup = () => {
    const { isVisibleFooter } = this.state;
    if (isVisibleFooter) {
      return (
        <ChatInputGroup
          onPressHeart={this.onPressHeart}
          onPressSend={this.onPressSend}
          onFocus={this.onFocusChatGroup}
          onEndEditing={this.onEndEditing}
        />
      );
    }
    return null;
  };

  onPressVisible = () => {
    const { isVisibleFooter } = this.state;
    this.setState(() => ({ isVisibleFooter: !isVisibleFooter }));
  };

  render() {
      return (
        <SafeAreaView style={styles.container}>
          <SafeAreaView style={styles.contentWrapper}>
            <View style={styles.header} />
            <TouchableWithoutFeedback onPress={this.onPressVisible}>
              <View style={styles.center}>
                <View style={styles.footer}>
                  {this.renderChatGroup()}
                  {this.renderListMessages()}
                </View>
              </View>
            </TouchableWithoutFeedback>
          </SafeAreaView>
        </SafeAreaView>
      );
    }
  }```

答:
Firstly I would highly recommend you use react native with functional components and React Hooks as they alternative will soon will be deprecated.

Since onPress is not available on the View Component, you would need to replace it with TouchableWithoutFeedback as you have already done in your code.

For Showing/Hiding a view you would need to use a conditional operator.

export default class Streamer extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isVisibleFooter: true,
        };
    }

    renderChatGroup = () => {
    const { isVisibleFooter } = this.state;
    if (isVisibleFooter) {
      return (
        <ChatInputGroup
          onPressHeart={this.onPressHeart}
          onPressSend={this.onPressSend}
          onFocus={this.onFocusChatGroup}
          onEndEditing={this.onEndEditing}
        />
      );
    }
    return null;
  };

  onPressVisible = () => {
    this.setState(() => ({ isVisibleFooter: !isVisibleFooter }));
    const { isVisibleFooter } = this.state;
  };

  render() {
      return (
        <SafeAreaView style={styles.container}>
          <SafeAreaView style={styles.contentWrapper}>
            <View style={styles.header} />
            <TouchableWithoutFeedback onPress={this.onPressVisible}>
              <View style={styles.center}>
                {isVisibleFooter && <View style={styles.footer}>
                  {this.renderChatGroup()}
                  {this.renderListMessages()}
                </View>}
              </View>
            </TouchableWithoutFeedback>
          </SafeAreaView>
        </SafeAreaView>
      );
    }
  }
```
<p>Here you can see i have replaced</p>
<pre class="lang-js prettyprint-override"><code><View style={styles.footer}>
    {this.renderChatGroup()}
    {this.renderListMessages()}
</View>
</code>```

with

{isFooterVisible && <View style={styles.footer}>
    {this.renderChatGroup()}
    {this.renderListMessages()}
</View>}
```
<p>stating that to only display the <code>Footer</code> View when</p>
<pre class="lang-js prettyprint-override"><code>const isFooterVisible = true;
</code>```

Body:
Firstly I would highly recommend you use react native with functional components and React Hooks as they alternative will soon will be deprecated.

Since onPress is not available on the View Component, you would need to replace it with TouchableWithoutFeedback as you have already done in your code.

For Showing/Hiding a view you would need to use a conditional operator.

export default class Streamer extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isVisibleFooter: true,
        };
    }

    renderChatGroup = () => {
    const { isVisibleFooter } = this.state;
    if (isVisibleFooter) {
      return (
        <ChatInputGroup
          onPressHeart={this.onPressHeart}
          onPressSend={this.onPressSend}
          onFocus={this.onFocusChatGroup}
          onEndEditing={this.onEndEditing}
        />
      );
    }
    return null;
  };

  onPressVisible = () => {
    this.setState(() => ({ isVisibleFooter: !isVisibleFooter }));
    const { isVisibleFooter } = this.state;
  };

  render() {
      return (
        <SafeAreaView style={styles.container}>
          <SafeAreaView style={styles.contentWrapper}>
            <View style={styles.header} />
            <TouchableWithoutFeedback onPress={this.onPressVisible}>
              <View style={styles.center}>
                {isVisibleFooter && <View style={styles.footer}>
                  {this.renderChatGroup()}
                  {this.renderListMessages()}
                </View>}
              </View>
            </TouchableWithoutFeedback>
          </SafeAreaView>
        </SafeAreaView>
      );
    }
  }

Here you can see i have replaced

<View style={styles.footer}>
    {this.renderChatGroup()}
    {this.renderListMessages()}
</View>

with

{isFooterVisible && <View style={styles.footer}>
    {this.renderChatGroup()}
    {this.renderListMessages()}
</View>}

stating that to only display the Footer View when

const isFooterVisible = true;


问:
Creating this number pattern in Java
I am trying to create a pattern in java by using a for-loop and nested for-loop based on the user input of a positive integer.

Here is an example:

User input = 5

Output:

```<code>5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5

</code>```

This is what I have so far. I am getting a list of integers, but I cannot find out where to go from here to get a pattern such as the one above. All I am getting is "5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 "

```<code>System.out.print("Enter the value of n: ");
int n = scan.nextInt();
for (int row = 1; row <= n; row++) { //rows
    for (int col = 1; col <= n; col++) { //columns
        if (n - col + 1 <= n - row + 1 && row <= n && col <= n) { //what to print
            System.out.print(n - row + 1 + " ");
        } else if (n - col + 1 <= n - row + 1 && row <= n && col <= n) {
            System.out.print(n - row + 1 + " ");
        }
    }
}
</code>```

答:
In this code I'm mirroring the column's and after that mirroring the rows. From mirroring I mean first creating mirror of the data.

First writing data to columns(left side) and then mirroring the column hence I get the right side of the column.

After writing data to the upper rows then mirroring the upper row I get bottom row.

```<code>import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class Pattern {
    static final PrintStream out = System.out;

    public static void displayPattern(int n) {
        final int arr[][] = new int[n * 2 - 1][];

        for (int i = 0; i < arr.length; i++)
            arr[i] = new int[n * 2 - 1];

        final List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int current = n - i;
            list.add(current);
            for (int j = 0; j < list.size(); j++) {
                arr[i][j] = list.get(j);
            }
            int remainings = n - list.size();
            for (int j = list.size(), count = 0; count < remainings; j++, count++) {
                arr[i][j] = current;
            }

            //writing data to right side of the columns(mirroring columns)
            for (int j = n, count = 1; j < arr[i].length; j++, count++)
                arr[i][j] = arr[i][j - count * 2];
        }
        //writing data to bottom half of the rows(mirroring rows)
        for (int i = n, count = 1; i < n * 2 - 1; i++, count++) {
            for (int j = 0; j < n * 2 - 1; j++)
                arr[i][j] = arr[i - count * 2][j];
        }

        for (int a[] : arr) {
            for (int b : a)
                out.print(b + " ");
            out.println();
        }

    }

    public static void main(final String... $) {
        displayPattern(5);
    }
}
</code>```

Output:

```<code>5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
</code>```

Title: Creating this number pattern in Java

Body:
I am trying to create a pattern in java by using a for-loop and nested for-loop based on the user input of a positive integer.

Here is an example:

User input = 5

Output:

5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5

This is what I have so far. I am getting a list of integers, but I cannot find out where to go from here to get a pattern such as the one above. All I am getting is "5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 "

System.out.print("Enter the value of n: ");
int n = scan.nextInt();
for (int row = 1; row <= n; row++) { //rows
    for (int col = 1; col <= n; col++) { //columns
        if (n - col + 1 <= n - row + 1 && row <= n && col <= n) { //what to print
            System.out.print(n - row + 1 + " ");
        } else if (n - col + 1 <= n - row + 1 && row <= n && col <= n) {
            System.out.print(n - row + 1 + " ");
        }
    }
}

Body:
In this code I'm mirroring the column's and after that mirroring the rows. From mirroring I mean first creating mirror of the data.

First writing data to columns(left side) and then mirroring the column hence I get the right side of the column.

After writing data to the upper rows then mirroring the upper row I get bottom row.

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class Pattern {
    static final PrintStream out = System.out;

    public static void displayPattern(int n) {
        final int arr[][] = new int[n * 2 - 1][];

        for (int i = 0; i < arr.length; i++)
            arr[i] = new int[n * 2 - 1];

        final List<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int current = n - i;
            list.add(current);
            for (int j = 0; j < list.size(); j++) {
                arr[i][j] = list.get(j);
            }
            int remainings = n - list.size();
            for (int j = list.size(), count = 0; count < remainings; j++, count++) {
                arr[i][j] = current;
            }

            //writing data to right side of the columns(mirroring columns)
            for (int j = n, count = 1; j < arr[i].length; j++, count++)
                arr[i][j] = arr[i][j - count * 2];
        }
        //writing data to bottom half of the rows(mirroring rows)
        for (int i = n, count = 1; i < n * 2 - 1; i++, count++) {
            for (int j = 0; j < n * 2 - 1; j++)
                arr[i][j] = arr[i - count * 2][j];
        }

        for (int a[] : arr) {
            for (int b : a)
                out.print(b + " ");
            out.println();
        }

    }

    public static void main(final String... $) {
        displayPattern(5);
    }
}

Output:

5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5


问:
Tftp protocol implementation and difference between netascii and octect
I'm building an application that is a server that implements the tftp protocol. I'm having hard times in understand what's the difference between ASCII format and binary format (netascii and octect) in tftp, and how should I read files differently as the protocol states.

I know that an ASCII char can be rapresented with a single byte. So I don't understand what's the difference between reading in ascii mode (1 byte each character) and binary mode (1 raw byte).

I can read the file with flag ios::binary for binary mode (octet in tftp) and without it for ascii (netascii in tftp), but I really don't understand what's the difference in reading files in these two ways (I always come up with an array of bytes).

If someone can help me understand, I'll really appreciate it

The tftp protocol specification: http://www.rfc-editor.org/rfc/rfc1350.txt

The part that I don't understand is this one:

Three modes of transfer are currently supported: netascii (This is
  ascii as defined in "USA Standard Code for Information Interchange"

  [1] with the modifications specified in "Telnet Protocol

  Specification" [3].)  Note that it is 8 bit ascii.  The term

  "netascii" will be used throughout this document to mean this

  particular version of ascii.); octet (This replaces the "binary" mode
  of previous versions of this document.) raw 8 bit bytes; mail,

  netascii characters sent to a user rather than a file.  (The mail

  mode is obsolete and should not be implemented or used.)  Additional

  modes can be defined by pairs of cooperating hosts.

答:
There are two passages which can help clarify what the purpose of netascii is in RFC-1350/TFTP:

netascii (This is ascii as defined in "USA Standard Code for Information Interchange" [1] with the modifications specified in "Telnet Protocol Specification" [3].)

The "Telnet Protocol Specification" is RFC-764, and it describes the interpretation of various ASCII codes for use on the "Network Virtual Terminal".  So, netascii would follow those interpretations (which include that lines must be terminated with a CR/LF sequence).

and:

A host which receives netascii mode data must translate the data to its own format.

So a host that used EBCDIC as it's native encoding, for example, might be expected to translate netascii to that encoding, but would leave "octet" data alone.

If you're implementing the TFTP server on a Unix (or other) system that uses LF for line endings, you'd be expected to add the CR for netascii transfers (as well as convert actual CR characters in the file to CR/NUL sequences.


问:
How to use the strncpy function in the 3rd array of 2d array strings
```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char d2arr[6][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];
    memset(d3arr, NULL, sizeof(d3arr));

    strncpy(d2arr[0], d3arr[0][0], sizeof(7));
    strncpy(d2arr[1], d3arr[0][1], sizeof(7));
    strncpy(d2arr[2], d3arr[0][2], sizeof(7));
    strncpy(d2arr[3], d3arr[0][3], sizeof(7));
    strncpy(d2arr[4], d3arr[0][4], sizeof(7));

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    return 0;
}
</code>```

There is no error message, and the results do not come out, so I ask questions.
Please let me know why the string in the 2D array is not copied.

答:
The problem is here:

```<code>strncpy(d2arr[0] , d3arr[0][0] , sizeof(7) );
strncpy(d2arr[1] , d3arr[0][1] , sizeof(7) );
strncpy(d2arr[2] , d3arr[0][2] , sizeof(7) );
strncpy(d2arr[3] , d3arr[0][3] , sizeof(7) );
strncpy(d2arr[4] , d3arr[0][4] , sizeof(7) );
</code>```

The strncpy function works as under:

```<code>strncpy(destination, source, no_of_characters);
</code>```

But in your code you have swapped destination and source arrays, and as a result, your code doesn't work. Also instead of using 'sizeof(7)' you should use only '7'. Also you should use strncpy_s instead of strncpy as strncpy can be unsafe.

So after all the corrections, here's the code:

```<code>strncpy_s(d3arr[0][0], d2arr[0], 7);
strncpy_s(d3arr[0][1], d2arr[1], 7);
strncpy_s(d3arr[0][2], d2arr[2], 7);
strncpy_s(d3arr[0][3], d2arr[3], 7);
strncpy_s(d3arr[0][4], d2arr[4], 7);
</code>```

Just replace the part with strncpy functions with the above code, and you'll be good to go. Other part of the code is totally fine.

Body:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char d2arr[6][7] = {
        { 'a', 'a', 'a', 'a', 'a', 'a' },
        { 'b', 'b', 'b', 'b', 'b', 'b' },
        { 'c', 'c', 'c', 'c', 'c', 'c' },
        { 'd', 'd', 'd', 'd', 'd', 'd' },
        { 'e', 'e', 'e', 'e', 'e', 'e' },
    };
    char d3arr[6][7][7];
    memset(d3arr, NULL, sizeof(d3arr));

    strncpy(d2arr[0], d3arr[0][0], sizeof(7));
    strncpy(d2arr[1], d3arr[0][1], sizeof(7));
    strncpy(d2arr[2], d3arr[0][2], sizeof(7));
    strncpy(d2arr[3], d3arr[0][3], sizeof(7));
    strncpy(d2arr[4], d3arr[0][4], sizeof(7));

    printf("%s\n", d3arr[0][0]);
    printf("%s\n", d3arr[0][1]);
    printf("%s\n", d3arr[0][2]);
    printf("%s\n", d3arr[0][3]);
    printf("%s\n", d3arr[0][4]);

    return 0;
}

There is no error message, and the results do not come out, so I ask questions.
Please let me know why the string in the 2D array is not copied.

Body:
The problem is here:

strncpy(d2arr[0] , d3arr[0][0] , sizeof(7) );
strncpy(d2arr[1] , d3arr[0][1] , sizeof(7) );
strncpy(d2arr[2] , d3arr[0][2] , sizeof(7) );
strncpy(d2arr[3] , d3arr[0][3] , sizeof(7) );
strncpy(d2arr[4] , d3arr[0][4] , sizeof(7) );

The strncpy function works as under:

strncpy(destination, source, no_of_characters);

But in your code you have swapped destination and source arrays, and as a result, your code doesn't work. Also instead of using 'sizeof(7)' you should use only '7'. Also you should use strncpy_s instead of strncpy as strncpy can be unsafe.

So after all the corrections, here's the code:

strncpy_s(d3arr[0][0], d2arr[0], 7);
strncpy_s(d3arr[0][1], d2arr[1], 7);
strncpy_s(d3arr[0][2], d2arr[2], 7);
strncpy_s(d3arr[0][3], d2arr[3], 7);
strncpy_s(d3arr[0][4], d2arr[4], 7);

Just replace the part with strncpy functions with the above code, and you'll be good to go. Other part of the code is totally fine.


问:
how to use IF else inside Do while loop
I want to Make a game Enter ATM pin with only 5 chances if you guess the correct pin it will stop automatic, and if Chances = 0  it will stop also,

int answer, chances = 5;

```<code> do{
     Scanner scan = new Scanner(System.in);
     System.out.print("Enter your Bank ATM pin : ");
     answer= scan.nextInt();
             chances--;

 }while(chances > 0);

}
</code>```

答:
You can do something like that:

int answer, chances = 5;
boolean authorized=false
do{
     Scanner scan = new Scanner(System.in);
     System.out.print("Enter your Bank ATM pin : ");
     answer= scan.nextInt();
     if(answer.equals("ok")){
        authorized=true;
     }else{
         chances--;
     }
 }while(chances > 0 || authorized);
```

Code Safe

Title: how to use IF else inside Do while loop

Body:
I want to Make a game Enter ATM pin with only 5 chances if you guess the correct pin it will stop automatic, and if Chances = 0  it will stop also,

int answer, chances = 5;

 do{
     Scanner scan = new Scanner(System.in);
     System.out.print("Enter your Bank ATM pin : ");
     answer= scan.nextInt();
             chances--;

 }while(chances > 0);

}

Body:
You can do something like that:

int answer, chances = 5;
boolean authorized=false
do{
     Scanner scan = new Scanner(System.in);
     System.out.print("Enter your Bank ATM pin : ");
     answer= scan.nextInt();
     if(answer.equals("ok")){
        authorized=true;
     }else{
         chances--;
     }
 }while(chances > 0 || authorized);

Code Safe


问:
Moving exoplayer controller above nav bar
I have a fullscreen video, with a translucent nav bar over the video.
Example here:

Now the nav bar overlaps the player controller so I just need to move it up.
I moved the controller up by including it in my activity layout file right next to the PlayerView:

```<code>    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/activity_my_activity_video"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.google.android.exoplayer2.ui.PlayerControlView
        android:id="@+id/activity_my_activity_player_control_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</code>```

Then I adjusted the code:

```<code>//get the player controller
playerControlView = findViewById(R.id.activity_my_activity_player_control_view);

//get the player view
playerView = findViewById(R.id.activity_my_activity_video);

//create the player
player = ExoPlayerFactory.getInstance().buildExoPlayer(this);
player.setPlayWhenReady(true);
player.setRepeatMode(Player.REPEAT_MODE_OFF);
player.setMediaItem(MediaItem.fromUri(videoUrl));
player.prepare();

//set the player in the views
playerControlView.setPlayer(player);
playerView.setPlayer(player);
</code>```

The behavior is that the "activity_my_activity_player_control_view" controller shows briefly and then disappears after the activity is created.  This controller does not appear again when one touches the PlayerView

Instead the built in controller is the one that responds to the touches of playerview by appearing and disappearing.

How do I fix this?

答:
I was following the information found here:
https://exoplayer.dev/ui-components.html

Unfortunately I must have misunderstood or the article wasn't clear enough (I'm voting for the former).

Anyway since all I want to do is change the position, I found the easiest way was to just get a reference to the default controller in PlayerView by using:

```<code>findViewById(R.id.exo_controller)
</code>```

And then after that I was able to adjust margins etc to put it above the nav bar.

Body:
I have a fullscreen video, with a translucent nav bar over the video.
Example here:

Now the nav bar overlaps the player controller so I just need to move it up.
I moved the controller up by including it in my activity layout file right next to the PlayerView:

    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/activity_my_activity_video"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.google.android.exoplayer2.ui.PlayerControlView
        android:id="@+id/activity_my_activity_player_control_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

Then I adjusted the code:

//get the player controller
playerControlView = findViewById(R.id.activity_my_activity_player_control_view);

//get the player view
playerView = findViewById(R.id.activity_my_activity_video);

//create the player
player = ExoPlayerFactory.getInstance().buildExoPlayer(this);
player.setPlayWhenReady(true);
player.setRepeatMode(Player.REPEAT_MODE_OFF);
player.setMediaItem(MediaItem.fromUri(videoUrl));
player.prepare();

//set the player in the views
playerControlView.setPlayer(player);
playerView.setPlayer(player);

The behavior is that the "activity_my_activity_player_control_view" controller shows briefly and then disappears after the activity is created.  This controller does not appear again when one touches the PlayerView

Instead the built in controller is the one that responds to the touches of playerview by appearing and disappearing.

How do I fix this?

Body:
I was following the information found here:
https://exoplayer.dev/ui-components.html

Unfortunately I must have misunderstood or the article wasn't clear enough (I'm voting for the former).

Anyway since all I want to do is change the position, I found the easiest way was to just get a reference to the default controller in PlayerView by using:

findViewById(R.id.exo_controller)

And then after that I was able to adjust margins etc to put it above the nav bar.


问:
Why did the authors of psql decide to have capital U (`-U`) for the user option rather than small u (`-u`)?
It makes so much more sense to just use the small u -u option for the user option. All other connection options (-h, -p, -d) are lowercase. sudo command also uses lowercase -u for its user option. The lowercase -u option is not used for anything else either.

Then why?

答:
See here from Postgres v7.0.0 psql. There was:

-u

Makes psql prompt for the user name and password before connecting to the database.

This option is deprecated, as it is conceptually flawed.  (Prompting for a non-default user name and prompting for a password because the backend requires it are really two different things.) You are encouraged to look at the -U and -W options instead.

psql tries to maintain backwards compatibility going back a long ways. The -u option does not disappear until version 8.3. Notes for current version psql current refer to going back to version 7.4.


问:
Pandas to_sql() slow on one DataFrame but fast on others

Goal

I'm trying to use pandas DataFrame.to_sql() to send a large DataFrame (>1M rows) to an MS SQL server database.

Problem

The command is significantly slower on one particular DataFrame, taking about 130 sec to send 10,000 rows. In contrast, a similar DataFrame takes just 7 sec to send the same number of rows. The latter DataFrame actually has more columns, and more data as measured by df.memory_usage(deep=True).

Details

The SQLAlchemy engine is created via

engine = create_engine('mssql+pyodbc://@<server>/<db>?driver=ODBC+Driver+17+for+SQL+Server', fast_executemany=True)

The to_sql() call is as follows:
df[i:i+chunksize].to_sql(table, conn, index=False, if_exists='replace')
where chunksize = 10000.

I've attempted to locate the bottleneck via cProfile, but this only revealed that nearly all of the time is spent in pyodbc.Cursor.executemany.

Any tips for debugging would be appreciated!

答:
Cause

The performance difference is due to an issue in pyodbc where passing None values to SQL Server INSERT statements when using the fast_executemany=True option results in slow downs.

Solution

We can pack the values as JSON and use OPENJSON (supported on SQL Server 2016+) instead of fast_executemany. This solution resulted in a 30x performance improvement in my application! Here's a self-contained example, based on the documentation here, but adapted for  pandas users.

import pandas as pd
from sqlalchemy import create_engine

df = pd.DataFrame({'First Name': ['Homer', 'Ned'], 'Last Name': ['Simpson', 'Flanders']})
rows_as_json = df.to_json(orient='records')

server = '<server name>'
db = '<database name>'
table = '
'
engine = create_engine(f'mssql+pyodbc://<user>:<password>@{server}/{db}')

sql = f'''
INSERT INTO {table} ([First Name], [Last Name])
SELECT [First Name], [Last Name] FROM
    OPENJSON(?)
    WITH (
        [First Name] nvarchar(50) '$."First Name"',
        [Last Name] nvarchar(50) '$."Last Name"'
    )
'''

cursor = engine.raw_connection().cursor()
cursor.execute(sql, rows_as_json)
cursor.commit()
```

Alternative Workarounds

Export data to CSV and use an external tool to complete the transfer (for example, the bcp utility).

Artificially replace values that are converted to None to a non-empty filler value, add a helper column to indicate which rows were changed, complete the operation as normal via to_sql(), then reset the filler values to Null via a separate query based on the helper column.

Acknowledgement

Many thanks to @GordThompson for pointing me to the solution!

Body:
Cause

The performance difference is due to an issue in pyodbc where passing None values to SQL Server INSERT statements when using the fast_executemany=True option results in slow downs.

Solution

We can pack the values as JSON and use OPENJSON (supported on SQL Server 2016+) instead of fast_executemany. This solution resulted in a 30x performance improvement in my application! Here's a self-contained example, based on the documentation here, but adapted for  pandas users.

import pandas as pd
from sqlalchemy import create_engine

df = pd.DataFrame({'First Name': ['Homer', 'Ned'], 'Last Name': ['Simpson', 'Flanders']})
rows_as_json = df.to_json(orient='records')

server = '<server name>'
db = '<database name>'
table = '<table name>'
engine = create_engine(f'mssql+pyodbc://<user>:<password>@{server}/{db}')

sql = f'''
INSERT INTO {table} ([First Name], [Last Name])
SELECT [First Name], [Last Name] FROM
    OPENJSON(?)
    WITH (
        [First Name] nvarchar(50) '$."First Name"',
        [Last Name] nvarchar(50) '$."Last Name"'
    )
'''

cursor = engine.raw_connection().cursor()
cursor.execute(sql, rows_as_json)
cursor.commit()

Alternative Workarounds

Export data to CSV and use an external tool to complete the transfer (for example, the bcp utility).

Artificially replace values that are converted to None to a non-empty filler value, add a helper column to indicate which rows were changed, complete the operation as normal via to_sql(), then reset the filler values to Null via a separate query based on the helper column.

Acknowledgement

Many thanks to @GordThompson for pointing me to the solution!


问:
How to safely use a REST API?
I am not a native speaker and can't think of a better title for this question. Feel free to edit it or suggest a better one.

I am trying to use woocommerce's REST API to update an order status. Currently, when an order is paid via direct bank transfer, a google sheet will be updated with the order ID and amount. I am trying to capture the order ID and update the corresponding order using the API. The simplest way I can think of is to execute something like myurl.com/myPHP.php?order_id=xxx when a new row is added to the google sheet. But the problem is, anyone can execute this php file and update the order status accidentally or maliciously. How to avoid this? What is the proper way to use the REST API to update order status?

答:
WooCommerce has its REST API endpoints. The endpoint responsible for updating an order's data is protected: you can not use it if you are not authenticated.

There are a few built-in auth methods in WooCommerce REST API; you can learn more about them in the API reference:
https://woocommerce.github.io/woocommerce-rest-api-docs/#authentication

In other words, if you won't provide the API credentials to users that may possibly abuse your API, you'll be fine.

Title: How to safely use a REST API?


问:
How to add item in redux with dictionary type in react typescript
I am using react-redux with typescript. I am importing a JSON file in my redux slice for an initial value. Now, I want to perform a crud operation on a dictionary. I want to add item only in the required key, for that what will be the type structure and how do I perform the operation?

my external JSON contains employee data with respect to the department. department as a key and employees as an array of objects. my structure looks like below:

```<code>{
  "0": [{...},{...},{...}],
  "1": [{...},{...},{...}],
  "2": [{...},{...},{...}],
}
</code>```

My slice code looks like this:

```<code>type employeeType = {
    id: number,
    name: string,
    age: number,
    DOB: number
}

type departments = {
    [departmentNo: string]: employeeType[];
}

const initialState:departments = require("./data.json");

export const employeeReducer = (state: departments = initialState, action: any) => {
    switch (action.type){
        case "ADD_EMPLOYEE": {
            return ({})
        }
        default: {
            return state
        }
    }
}
</code>```

答:
Think about what information you need in order to make the correct modification to state.  Your state is keyed by department number, so in order to add a new employee you will need to know which department you are adding them to.  You also need to know all the details of the employee object.  Your action.payload might look like this:

```<code>interface AddEmployeePayload {
    departmentNo: string;
    employee: EmployeeType;
}
</code>```

I highly recommend creating your reducer with Redux Toolkit so that you can use a simple push operation instead of dealing with immutable nested updates.

It's up to you how you want to handle cases where the departmentNo doesn't match an existing array on your state object.  Throw an error?  Create a new array?

```<code>import { createSlice, PayloadAction } from '@reduxjs/toolkit';

const employeeSlice = createSlice({
  name: 'employees',
  initialState,
  reducers: {
    addEmployee: (state, action: PayloadAction<AddEmployeePayload>) => {
      // Get the data from our action.
      const { departmentNo, employee } = action.payload;
      // Access the existing array of employees in this department.
      const employeeArray = state[departmentNo];
      if (employeeArray) {
        // Add this employee to the array.
        employeeArray.push(employee);
      } else {
        // Warn about potential invalid ids.
        console.warn(`Unknown department number ${departmentNo}.`);
        // Create a new department array with just this employee in it.
        state[departmentNo] = [employee];
      }
    }
  }
})

export const employeeReducer = employeeSlice.reducer;

// action creator function
export const { addEmployee } = employeeSlice.actions;
</code>```

Complete Code

Body:
I am using react-redux with typescript. I am importing a JSON file in my redux slice for an initial value. Now, I want to perform a crud operation on a dictionary. I want to add item only in the required key, for that what will be the type structure and how do I perform the operation?

my external JSON contains employee data with respect to the department. department as a key and employees as an array of objects. my structure looks like below:

{
  "0": [{...},{...},{...}],
  "1": [{...},{...},{...}],
  "2": [{...},{...},{...}],
}

My slice code looks like this:

type employeeType = {
    id: number,
    name: string,
    age: number,
    DOB: number
}

type departments = {
    [departmentNo: string]: employeeType[];
}

const initialState:departments = require("./data.json");

export const employeeReducer = (state: departments = initialState, action: any) => {
    switch (action.type){
        case "ADD_EMPLOYEE": {
            return ({})
        }
        default: {
            return state
        }
    }
}

Body:
Think about what information you need in order to make the correct modification to state.  Your state is keyed by department number, so in order to add a new employee you will need to know which department you are adding them to.  You also need to know all the details of the employee object.  Your action.payload might look like this:

interface AddEmployeePayload {
    departmentNo: string;
    employee: EmployeeType;
}

I highly recommend creating your reducer with Redux Toolkit so that you can use a simple push operation instead of dealing with immutable nested updates.

It's up to you how you want to handle cases where the departmentNo doesn't match an existing array on your state object.  Throw an error?  Create a new array?

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

const employeeSlice = createSlice({
  name: 'employees',
  initialState,
  reducers: {
    addEmployee: (state, action: PayloadAction<AddEmployeePayload>) => {
      // Get the data from our action.
      const { departmentNo, employee } = action.payload;
      // Access the existing array of employees in this department.
      const employeeArray = state[departmentNo];
      if (employeeArray) {
        // Add this employee to the array.
        employeeArray.push(employee);
      } else {
        // Warn about potential invalid ids.
        console.warn(`Unknown department number ${departmentNo}.`);
        // Create a new department array with just this employee in it.
        state[departmentNo] = [employee];
      }
    }
  }
})

export const employeeReducer = employeeSlice.reducer;

// action creator function
export const { addEmployee } = employeeSlice.actions;

Complete Code


问:
How can I guarantee all unit tests pass before committing?
We've had problems recently where developers commit code to SVN that doesn't pass unit tests, fails to compile on all platforms, or even fails to compile on their own platform. While this is all picked up by our CI server (Cruise Control), and we've instituted processes to try to stop it from happening, we'd really like to be able to stop the rogue commits from happening in the first place.

Based on a few other questions around here, it seems to be a Bad Idea™ to force this as a pre-commit hook on the server side mostly due to the length of time required to build + run the tests. I did some Googling and found this (all devs use TortoiseSVN):

http://cf-bill.blogspot.com/2010/03/pre-commit-force-unit-tests-without.html

Which would solve at least two of the problems (it wouldn't build on Unix), but it doesn't reject the commit if it fails. So my questions:

Is there a way to make a pre-commit hook in TortoiseSVN cause the commit to fail?

Is there a better way to do what I'm trying to do in general?

答: The best thing to do is to work to improve the culture of your team, so that each developer feels enough of a commitment to the process that they'd be ashamed to check in without making sure it works properly, in whatever ways you've all agreed.</p>


问:
I want my Assembly Code to takes user input and outputs it along with other text but the output isn't correct
My code works but the output isn't just right because when I enter the name, the output becomes this; "What is your member name? Welcome to the club, Bob!!!!!!!!!!!!!!!!!!, enjoy the party." with the "!!!!!!" at the end of the name. What am I doing wrong?

Here is my assembly code:

```<code>section .data
prompt:       db      "What is your member name? "
prompt_len:   equ     $-prompt
greet1:        db      "Welcome to the club, "
greet1_len:    equ     $-greet1
greet2:        db      ", enjoy the party."
greet2_len:    equ     $-greet2

inputbuffer_len:   equ    256
inputbuffer:       times inputbuffer_len  db '!'

STDIN:        equ     0
STDOUT:       equ     1
SYS_READ:     equ     0
SYS_WRITE:    equ     1
SYS_EXIT:     equ     60

section .text

global _start
 _start:
    mov     rdx,    prompt_len      ;output prompt
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    prompt
    syscall

    mov     rax,    SYS_READ ;user input here
    mov     rdi,    STDIN
    mov     rsi,    inputbuffer
    mov     rdx,    inputbuffer_len
    syscall

    mov     rdx,    greet1_len        ; output "Welcome to the club, "
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    greet1
    syscall
    mov     rdx,    rax            ;output user's inputted name
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    inputbuffer
    syscall

    mov     rdx,    greet2_len         ; output ", enjoy the party."
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    greet2
    syscall

    mov     rax,    SYS_EXIT
    mov     rdi,    0
    syscall
</code>```

答:
The length of Bob!!!!!!!!!!!!!!!!!! is the length of Welcome to the club, .
This is no coincidence.
Following the write(2) system call rax contains the number of successfully written Bytes.
(This might be less than the desired number of Bytes as the manual page describes.)

Like David C. Rankin commented you will need to mind the return value of read(2).
On success, read(2) returns the number of Bytes read in rax.
However, you are overwriting this value for and with the intervening write(2) system call.
Store and recall somewhere the number of successfully read Bytes (e. g. push/pop) and you’re good.

PS:
You could save one write(2) system call by rearranging the buffer to follow after greet_1.
Then you could write(2) rax + greet1_len Bytes at once.
But one problem at a time.

Body:
My code works but the output isn't just right because when I enter the name, the output becomes this; "What is your member name? Welcome to the club, Bob!!!!!!!!!!!!!!!!!!, enjoy the party." with the "!!!!!!" at the end of the name. What am I doing wrong?

Here is my assembly code:

section .data
prompt:       db      "What is your member name? "
prompt_len:   equ     $-prompt
greet1:        db      "Welcome to the club, "
greet1_len:    equ     $-greet1
greet2:        db      ", enjoy the party."
greet2_len:    equ     $-greet2

inputbuffer_len:   equ    256
inputbuffer:       times inputbuffer_len  db '!'

STDIN:        equ     0
STDOUT:       equ     1
SYS_READ:     equ     0
SYS_WRITE:    equ     1
SYS_EXIT:     equ     60

section .text

global _start
 _start:
    mov     rdx,    prompt_len      ;output prompt
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    prompt
    syscall

    mov     rax,    SYS_READ ;user input here
    mov     rdi,    STDIN
    mov     rsi,    inputbuffer
    mov     rdx,    inputbuffer_len
    syscall

    mov     rdx,    greet1_len        ; output "Welcome to the club, "
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    greet1
    syscall
    mov     rdx,    rax            ;output user's inputted name
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    inputbuffer
    syscall

    mov     rdx,    greet2_len         ; output ", enjoy the party."
    mov     rax,    SYS_WRITE
    mov     rdi,    STDOUT
    mov     rsi,    greet2
    syscall

    mov     rax,    SYS_EXIT
    mov     rdi,    0
    syscall


问:
Why is a carry need in CLRS problem 2.1-4 adding two binary array?
CLRS is the book Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein.

Problem:

Consider the problem of adding two n-bit binary integers,
stored in two n element arrays A and B.
The sum of the two integers should be stored in binary
form in an (n + 1) element array C.

Why is carry needed in the correct solution?

My solution:

```<code>def AddBinary(A,B):
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    for i in range(n):
        C[i] = (A[i] + B[i]) % 2
    return C
</code>```

correct solution:

```<code>def AddBinary(A,B):
    carry = 0
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    for i in range(n):
        C[i] = (A[i] + B[i]+carry) % 2
        carry = (A[i] + B[i]+carry) // 2
    C[n] = carry
    return C
</code>```

答:
You're asking about the basic nature of performing addition place by place in whatever base.  If you can recall how we were taught decimal (base 10) addition early on, we were told to carry the "overflow" to the next digit, right?  The code needs to do the same thing.  The carry is a critical part of the operation.

Here's a simple way to see this.  Consider adding two 2-digit binary numbers:

```<code>01 + 01 = 10   # (1 + 1) % 2 == 0 + carry, (0 + 0 + carry) % 2 == 1
</code>```

or in decimal, 1 + 1 = 2.  Now apply your logic that ignores the carry:

```<code>01 + 01 = 00   # (1 + 1) % 2 == 0, (0 + 0) % 2 == 0
</code>```

so here, 1 + 1 = 0.  That clearly isn't correct.  In this trivial example, the carry produces the entirety of the resulting value.

Body:
CLRS is the book Introduction to Algorithms by Cormen, Leiserson, Rivest, and Stein.

Problem:

Consider the problem of adding two n-bit binary integers,
stored in two n element arrays A and B.
The sum of the two integers should be stored in binary
form in an (n + 1) element array C.

Why is carry needed in the correct solution?

My solution:

def AddBinary(A,B):
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    for i in range(n):
        C[i] = (A[i] + B[i]) % 2
    return C

correct solution:

def AddBinary(A,B):
    carry = 0
    n = max(len(A),len(B))
    C = [0 for i in range(n+1)]
    for i in range(n):
        C[i] = (A[i] + B[i]+carry) % 2
        carry = (A[i] + B[i]+carry) // 2
    C[n] = carry
    return C

Body:
You're asking about the basic nature of performing addition place by place in whatever base.  If you can recall how we were taught decimal (base 10) addition early on, we were told to carry the "overflow" to the next digit, right?  The code needs to do the same thing.  The carry is a critical part of the operation.

Here's a simple way to see this.  Consider adding two 2-digit binary numbers:

01 + 01 = 10   # (1 + 1) % 2 == 0 + carry, (0 + 0 + carry) % 2 == 1

or in decimal, 1 + 1 = 2.  Now apply your logic that ignores the carry:

01 + 01 = 00   # (1 + 1) % 2 == 0, (0 + 0) % 2 == 0

so here, 1 + 1 = 0.  That clearly isn't correct.  In this trivial example, the carry produces the entirety of the resulting value.