问:
How do I fix "No pubspec.yaml file found" in flutter?
I am using Windows 10 with VS Code, although I also tested it on PowerShell, and both produced the same result:

After creating a new flutter program, before editing anything, I tried to run it on my phone, as the Tutorial Says, but I get an error saying "No pubspec.yaml file found". I thought that the issue must be that the default new app setup having an issue, so I used the "flutter_gallery" example. However, this had the exact same issue. I have reinstalled flutter, installed dart 2 on its own, deleted .pub-cache, but nothing works. I tried Googling the issue, but I couldn't find anything.

EDIT: I am running the commands from the root directory of the flutter project, where the pubspec.yaml file is, but I still get an error. The full error message is:

```<code>Error: No pubspec.yaml file found.
This command should be run from the root of your Flutter project.
Do not run this command from the root of your git clone of Flutter.
</code>```

here is the result of running dir from the root of the project:

```<code>Mode                LastWriteTime         Length Name
----                -------------         ------ ----
da---l       2018-04-11   3:45 PM                .idea
da---l       2018-04-11   3:45 PM                android
da---l       2018-04-11   3:45 PM                ios
da---l       2018-04-11   4:19 PM                lib
da---l       2018-04-11   3:45 PM                test
-a---l       2018-04-11   3:45 PM            120 .gitignore
-a---l       2018-04-11   3:45 PM            292 .metadata
-a---l       2018-04-11   3:45 PM           5425 .packages
-a---l       2018-04-11   3:45 PM            851 hello_world.iml
-a---l       2018-04-11   3:45 PM           1412 hello_world_android.iml
-a---l       2018-04-11   3:59 PM           8882 pubspec.lock
-a---l       2018-04-11   3:59 PM            358 pubspec.yaml
-a---l       2018-04-11   3:45 PM            160 README.md
</code>```

UPDATE: I still don't know what caused the problem, but when I reinstalled flutter for Beta 3, it finally worked.

答: Possible that you are running flutter commands from a different directory. Go to project directory and try running flutter commands from there.</p>

Body:
I am using Windows 10 with VS Code, although I also tested it on PowerShell, and both produced the same result:

After creating a new flutter program, before editing anything, I tried to run it on my phone, as the Tutorial Says, but I get an error saying "No pubspec.yaml file found". I thought that the issue must be that the default new app setup having an issue, so I used the "flutter_gallery" example. However, this had the exact same issue. I have reinstalled flutter, installed dart 2 on its own, deleted .pub-cache, but nothing works. I tried Googling the issue, but I couldn't find anything.

EDIT: I am running the commands from the root directory of the flutter project, where the pubspec.yaml file is, but I still get an error. The full error message is:

Error: No pubspec.yaml file found.
This command should be run from the root of your Flutter project.
Do not run this command from the root of your git clone of Flutter.

here is the result of running dir from the root of the project:

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
da---l       2018-04-11   3:45 PM                .idea
da---l       2018-04-11   3:45 PM                android
da---l       2018-04-11   3:45 PM                ios
da---l       2018-04-11   4:19 PM                lib
da---l       2018-04-11   3:45 PM                test
-a---l       2018-04-11   3:45 PM            120 .gitignore
-a---l       2018-04-11   3:45 PM            292 .metadata
-a---l       2018-04-11   3:45 PM           5425 .packages
-a---l       2018-04-11   3:45 PM            851 hello_world.iml
-a---l       2018-04-11   3:45 PM           1412 hello_world_android.iml
-a---l       2018-04-11   3:59 PM           8882 pubspec.lock
-a---l       2018-04-11   3:59 PM            358 pubspec.yaml
-a---l       2018-04-11   3:45 PM            160 README.md

UPDATE: I still don't know what caused the problem, but when I reinstalled flutter for Beta 3, it finally worked.


来源: stackexchange

问:
python how do I paste non alphanumeric string in a excel cell
I want to put the below formula in one of the excel cells (A18), so that it links to a file and the excel performs some indirect vlookup function etc(which is not part of my problem here).

Problem is am struggling to paste it using python code. It should be pasted exactly in the below format else it wont work for me. How can I solve this problem?

```<code>="'W:\XYZ\ABC\DEF\"
</code>```

Below is what I have tried and it didn't work for me

```<code>xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(filepath, None, False)
ws = wb.sheets['TT1']
ws.Range('A18').value = '=' + '"' + "'W:\\XYZ\\ABC\\DEF\\"
</code>```

Below is the error message I'm getting

```<code>Traceback (most recent call last):
  File "C:/Users/ABC/PycharmProjects/PA/excel_copyTab.py", line 126, in <module>
    pastelink()
  File "C:/Users/ABC/PycharmProjects/PA/excel_copyTab.py", line 121, in pastelink
    ws.Range('A18').value = '=' + '"' + "'W:\\XYZ\\ABC\\DEF\\"
  File "C:\Users\ABC\Anaconda3\envs\PA36\lib\site-packages\win32com\client\dynamic.py", line 581, in __setattr__
    raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))
AttributeError: Property 'Range.value' can not be set.
</code>```

答:
Try this:-</p>

```<code>ws.Range('A18').value = '=' + '''"W:\XYZ\ABC\DEF\\"'''
FileName=ws.Range('A18').value+ws.Range('B10').value
print(FileName)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to put the below formula in one of the excel cells (A18), so that it links to a file and the excel performs some indirect vlookup function etc(which is not part of my problem here).

Problem is am struggling to paste it using python code. It should be pasted exactly in the below format else it wont work for me. How can I solve this problem?

="'W:\XYZ\ABC\DEF\"

Below is what I have tried and it didn't work for me

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(filepath, None, False)
ws = wb.sheets['TT1']
ws.Range('A18').value = '=' + '"' + "'W:\\XYZ\\ABC\\DEF\\"

Below is the error message I'm getting

Traceback (most recent call last):
  File "C:/Users/ABC/PycharmProjects/PA/excel_copyTab.py", line 126, in <module>
    pastelink()
  File "C:/Users/ABC/PycharmProjects/PA/excel_copyTab.py", line 121, in pastelink
    ws.Range('A18').value = '=' + '"' + "'W:\\XYZ\\ABC\\DEF\\"
  File "C:\Users\ABC\Anaconda3\envs\PA36\lib\site-packages\win32com\client\dynamic.py", line 581, in __setattr__
    raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))
AttributeError: Property 'Range.value' can not be set.

Body:
Try this:-

ws.Range('A18').value = '=' + '''"W:\XYZ\ABC\DEF\\"'''
FileName=ws.Range('A18').value+ws.Range('B10').value
print(FileName)


问:
React Native: Removed App Permission in FB caused Login Failed: You can't use Facebook to log into this app or website
I'm using React Native 0.61.5 with react-native-fbsdk 2.0.0. Facebook app is Live and configured.

The problem is with the Facebook Login when the permission is removed, facebook cannot re-authorise the Facebook Login anymore and keep displaying error in the facebook app.

error message with Facebook App already signed-in and try to use facebook login

Above was just one of the test case. Prior to "Removing" the app permission in Facebook, the facebook login seems to be fine.

This is the basic RN code for Facebook Login

```<code><LoginButton
  onLoginFinished={
    (error, result) => {
      if (error) {
        console.log("login has error: " + result.error);
      } else if (result.isCancelled) {
        console.log("login is cancelled.");
      } else {
        AccessToken.getCurrentAccessToken().then(
          (data) => {
            console.log(data.accessToken.toString())
          }
        )
      }
    }
  }
  onLogoutFinished={() => console.log("logout.")}/>
</code>```

Any of you have any clue or solution?

I'm expecting that the facebook login will re-authorize again but it's not.

答:
Please try adding permissions to the LoginButton like this. So that login button will look for the permissions too. Let me know if facebook re autorize for you..

```<code> <LoginButton
      permissions={["email", "user_friends", "public_profile"]}
      onLoginFinished={this._onFacebookLoginFinished.bind(this)}
      onLogoutFinished={this._onFacebookLogoutFinished.bind(this)}
    />
</code>```

Body:
I'm using React Native 0.61.5 with react-native-fbsdk 2.0.0. Facebook app is Live and configured.

The problem is with the Facebook Login when the permission is removed, facebook cannot re-authorise the Facebook Login anymore and keep displaying error in the facebook app.

error message with Facebook App already signed-in and try to use facebook login

Above was just one of the test case. Prior to "Removing" the app permission in Facebook, the facebook login seems to be fine.

This is the basic RN code for Facebook Login

<LoginButton
  onLoginFinished={
    (error, result) => {
      if (error) {
        console.log("login has error: " + result.error);
      } else if (result.isCancelled) {
        console.log("login is cancelled.");
      } else {
        AccessToken.getCurrentAccessToken().then(
          (data) => {
            console.log(data.accessToken.toString())
          }
        )
      }
    }
  }
  onLogoutFinished={() => console.log("logout.")}/>

Any of you have any clue or solution?

I'm expecting that the facebook login will re-authorize again but it's not.

Body:
Please try adding permissions to the LoginButton like this. So that login button will look for the permissions too. Let me know if facebook re autorize for you..

 <LoginButton
      permissions={["email", "user_friends", "public_profile"]}
      onLoginFinished={this._onFacebookLoginFinished.bind(this)}
      onLogoutFinished={this._onFacebookLogoutFinished.bind(this)}
    />


问:
Getting filenames in the right alphanumerical order
I'm having trouble with this command (suspect it's bash related, and not program specific)

```<code>montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 ./*.bluemap.jpg /media/
</code>```

The problem is that it starts with the file 100002.bluemap.jpg, not the lowest  number which is 2016.bluemap.jpg

All numbers don't exist, for example the next after 2016 is 6438, 6685,9879

Is there anyway to get it to do the job correctly, the right order?

Or do I need to create some list or something?

I'm little lost..

答:
Sort the filenames using GNU sort and read the list into an array, then expand it in the montage invocation.

```<code>readarray -d '' -t files < <(printf '%s\0' ./*.bluemap.jpg | sort -z -t/ -k2n)
montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 "${files[@]}" /media/
</code>```

See:

Bash Builtin Commands § readarray,

sort invocation (GNU coreutils).

Body:
I'm having trouble with this command (suspect it's bash related, and not program specific)

montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 ./*.bluemap.jpg /media/

The problem is that it starts with the file 100002.bluemap.jpg, not the lowest  number which is 2016.bluemap.jpg

All numbers don't exist, for example the next after 2016 is 6438, 6685,9879

Is there anyway to get it to do the job correctly, the right order?

Or do I need to create some list or something?

I'm little lost..

Body:
Sort the filenames using GNU sort and read the list into an array, then expand it in the montage invocation.

readarray -d '' -t files < <(printf '%s\0' ./*.bluemap.jpg | sort -z -t/ -k2n)
montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 "${files[@]}" /media/

See:

Bash Builtin Commands § readarray,

sort invocation (GNU coreutils).


问:
Download bootstrapper exe path in msi
I would like to assign a property path to the bootstrapper exe.

I've seen a few posts that show you can do it this way:

```<code><MsiPackage Id="MainPackage" SourceFile"...\Installer.msi" ...>
    <MsiProperty Name='CONFIGFILELOCATION' Value='[WixBundleOriginalSource]'/>
</MsiPackage>
</code>```

But all the ways I found to download it in the product don't work.

I'm not sure if I create veriable with value [WixBundleOriginalSource] returns the path, because writing it to the txt file in the custom interface returns me [WixBundleOrginalSource] instead of the path.

I was trying use in custom action:

```<code>AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location
</code>```

答:
Ok I found solution:

```<code><Property Id="CONFIGFILELOCATION"\>
<SetProperty Id="CONFIGFILELOCATION" Value="[CONFIGFILELOCATION]" Before="AppSearch">
     CONFIGFILELOCATION=""
</SetProperty>
</code>```

I don't understand how value works in the end, because if you can do something else, it also works.

Title: Download bootstrapper exe path in msi

Body:
I would like to assign a property path to the bootstrapper exe.

I've seen a few posts that show you can do it this way:

<MsiPackage Id="MainPackage" SourceFile"...\Installer.msi" ...>
    <MsiProperty Name='CONFIGFILELOCATION' Value='[WixBundleOriginalSource]'/>
</MsiPackage>

But all the ways I found to download it in the product don't work.

I'm not sure if I create veriable with value [WixBundleOriginalSource] returns the path, because writing it to the txt file in the custom interface returns me [WixBundleOrginalSource] instead of the path.

I was trying use in custom action:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location

Body:
Ok I found solution:

<Property Id="CONFIGFILELOCATION"\>
<SetProperty Id="CONFIGFILELOCATION" Value="[CONFIGFILELOCATION]" Before="AppSearch">
     CONFIGFILELOCATION=""
</SetProperty>

I don't understand how value works in the end, because if you can do something else, it also works.


问:
function name in json response - not working
I am trying to send a function in JSON response and tried to alert that function in js. Below is the code.

JS:

```<code>$('input').keyup(function(){
    $.ajax({
        type: "POST",
        url: "sample.php",
        dataType : 'json',
        data: 'val='+$('input').val(),
        success: function(response){

         var json = transport.responseText.evalJSON();
         alert(json.function()); // => **should alert 'foo bar' - but not**
        }
    });
});
</code>```

PHP:

```<code><?php
// Our sample array
$foo = array(
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

/* $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}
*/
// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

/* This echoes the following string:
{
  "string":"bar",
  "function":function(){return "foo bar";}
}
*/
?>
</code>```

what am I doing wrong in the above? Any help is appreciated.

答:
A function is not a valid data type in JSON. What you can do is to send a function expression as string:

```<code>{
  "string": "bar",
  "function":"function(){return \"foo bar\";}"
}
</code>```

And then use eval:

```<code>var f = eval(response['function']);
</code>```

But I would not recommend doing so. It is horrible, complex, not easy to understand or to maintain. It is basically the worst you can do.

What problem are you trying to solve with that?

If you have to send JavaScript from the server, then do so (don't return JSON), and use script as dataType.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send a function in JSON response and tried to alert that function in js. Below is the code.

JS:

$('input').keyup(function(){
    $.ajax({
        type: "POST",
        url: "sample.php",
        dataType : 'json',
        data: 'val='+$('input').val(),
        success: function(response){

         var json = transport.responseText.evalJSON();
         alert(json.function()); // => **should alert 'foo bar' - but not**
        }
    });
});

PHP:

<?php
// Our sample array
$foo = array(
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

/* $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}
*/
// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

/* This echoes the following string:
{
  "string":"bar",
  "function":function(){return "foo bar";}
}
*/
?>

what am I doing wrong in the above? Any help is appreciated.

Body:
A function is not a valid data type in JSON. What you can do is to send a function expression as string:

{
  "string": "bar",
  "function":"function(){return \"foo bar\";}"
}

And then use eval:

var f = eval(response['function']);

But I would not recommend doing so. It is horrible, complex, not easy to understand or to maintain. It is basically the worst you can do.

What problem are you trying to solve with that?

If you have to send JavaScript from the server, then do so (don't return JSON), and use script as dataType.


问:
PHP custom sorting: Manual sorting an array based on specified keys
I have an array that looks like

```<code>$array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'city' => ['value' => 'Dubai'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'zip_code' => ['value' => 12345],
    'city_id' => ['value' => 22],
    //...
];
</code>```

I would like to sort the array so that the keys country_id, region, region_id, city, city_id occur serially while preserving the position of others.

Expected Output

```<code> $array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'city' => ['value' => 'Dubai'],
    'city_id' => ['value' => 22],
    'zip_code' => ['value' => 12345],
    //...
];
</code>```

I have tried as:

Trial #1

```<code>uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (isset($order[$a]) && isset($order[$b])) {
    return $order[$a] - $order[$b];
  } else {
    return 0;
  }
});

var_dump($array);
</code>```

Trial #2

```<code>uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (!isset($order[$a]) && !isset($order[$b])) {
    return 0;
  } elseif (!isset($order[$a])) {
    return 1;
  } elseif (!isset($order[$b])) {
    return -1;
  } else {
    return $order[$a] - $order[$b];

  }
});

var_dump($array);
</code>```

But the rest of the orders are not maintained anymore.
So I want those custom fields to appear in the same order without breaking the positions of others. For example, name should appear first, etc.

答:
You're quite close in your implementation, but you have to consider the case in your comparison function where only one of your wanted keys are present and not any of the others. If you return 0 in that case, they'll be mangled within the other keys in your array (since their position in that case is considered to be equal).

Since you also want the sequence of existing keys to be kept, and the other "extracted" keys to be inserted after country_id, you can keep a reference to the original sort order and use that to resolve the sort order in relation to country_id for other fields (and between other fields to keep the current sort order)

By handling those two special cases to explicitly sort the keys you want to occur after each other by themselves, you get a result that satisfies your requirement:

```<code>$order = ['country_id' => 1, 'region' => 2, 'region_id' => 3, 'city' => 4, 'city_id' => 5];
$preset_order = array_flip(array_keys($array));

uksort($array, function ($a, $b) use ($order, $preset_order) {
  if (isset($order[$a]) && isset($order[$b])) {
    return $order[$a] - $order[$b];
  } else if (isset($order[$a])) {
    return $preset_order['country_id'] - $preset_order[$b];
  } else if (isset($order[$b])) {
    return $preset_order[$a] - $preset_order['country_id'];
  } else {
    return $preset_order[$a] - $preset_order[$b];
  }
});
</code>```

Outputs:

```<code>array(8) {
  'name' =>
  array(1) {
    'value' =>
    string(6) "Raj KB"
  }
  'street' =>
  array(1) {
    'value' =>
    string(10) "Street ABC"
  }
  'country_id' =>
  array(1) {
    'value' =>
    string(3) "UAE"
  }
  'region' =>
  array(1) {
    'value' =>
    string(3) "DXB"
  }
  'region_id' =>
  array(1) {
    'value' =>
    int(11)
  }
  'city' =>
  array(1) {
    'value' =>
    string(5) "Dubai"
  }
  'city_id' =>
  array(1) {
    'value' =>
    int(22)
  }
  'zip_code' =>
  array(1) {
    'value' =>
    int(12345)
  }
}
</code>```

Body:
I have an array that looks like

$array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'city' => ['value' => 'Dubai'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'zip_code' => ['value' => 12345],
    'city_id' => ['value' => 22],
    //...
];

I would like to sort the array so that the keys country_id, region, region_id, city, city_id occur serially while preserving the position of others.

Expected Output

 $array = [
    //...
    'name' => ['value' => 'Raj KB'],
    'street' => ['value' => 'Street ABC'],
    'country_id' => ['value' => 'UAE'],
    'region' => ['value' => 'DXB'],
    'region_id' => ['value' => 11],
    'city' => ['value' => 'Dubai'],
    'city_id' => ['value' => 22],
    'zip_code' => ['value' => 12345],
    //...
];

I have tried as:

Trial #1

uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (isset($order[$a]) && isset($order[$b])) {
    return $order[$a] - $order[$b];
  } else {
    return 0;
  }
});

var_dump($array);

Trial #2

uksort($array, function ($a, $b) {

  $order = ['country_id' => 0, 'region' => 1, 'region_id' => 2, 'city' => 3, 'city_id' => 4];
  if (!isset($order[$a]) && !isset($order[$b])) {
    return 0;
  } elseif (!isset($order[$a])) {
    return 1;
  } elseif (!isset($order[$b])) {
    return -1;
  } else {
    return $order[$a] - $order[$b];

  }
});

var_dump($array);

But the rest of the orders are not maintained anymore.
So I want those custom fields to appear in the same order without breaking the positions of others. For example, name should appear first, etc.

Body:
You're quite close in your implementation, but you have to consider the case in your comparison function where only one of your wanted keys are present and not any of the others. If you return 0 in that case, they'll be mangled within the other keys in your array (since their position in that case is considered to be equal).

Since you also want the sequence of existing keys to be kept, and the other "extracted" keys to be inserted after country_id, you can keep a reference to the original sort order and use that to resolve the sort order in relation to country_id for other fields (and between other fields to keep the current sort order)

By handling those two special cases to explicitly sort the keys you want to occur after each other by themselves, you get a result that satisfies your requirement:

$order = ['country_id' => 1, 'region' => 2, 'region_id' => 3, 'city' => 4, 'city_id' => 5];
$preset_order = array_flip(array_keys($array));

uksort($array, function ($a, $b) use ($order, $preset_order) {
  if (isset($order[$a]) && isset($order[$b])) {
    return $order[$a] - $order[$b];
  } else if (isset($order[$a])) {
    return $preset_order['country_id'] - $preset_order[$b];
  } else if (isset($order[$b])) {
    return $preset_order[$a] - $preset_order['country_id'];
  } else {
    return $preset_order[$a] - $preset_order[$b];
  }
});

Outputs:

array(8) {
  'name' =>
  array(1) {
    'value' =>
    string(6) "Raj KB"
  }
  'street' =>
  array(1) {
    'value' =>
    string(10) "Street ABC"
  }
  'country_id' =>
  array(1) {
    'value' =>
    string(3) "UAE"
  }
  'region' =>
  array(1) {
    'value' =>
    string(3) "DXB"
  }
  'region_id' =>
  array(1) {
    'value' =>
    int(11)
  }
  'city' =>
  array(1) {
    'value' =>
    string(5) "Dubai"
  }
  'city_id' =>
  array(1) {
    'value' =>
    int(22)
  }
  'zip_code' =>
  array(1) {
    'value' =>
    int(12345)
  }
}


问:
Rails Routing to Unknown Pages is Messing Up With ActiveStorage Image Path
I searched for every code that I can find here in stackoverflow on how you actually can redirect the pages that doesn't exist or unknown to a 404 page.

For instance you visited this page  http://localhost:3000/thispageisnull since the page doesn't exist it will automatically redirect you to the default 404 custom page I created.

So far here's what I did. On my errors_controller.rb file I place this code:

```<code>def show_404
      render "404", status: 404
    end
</code>```

And then on my routes.rb file, I place this code:

```<code>match '*path', via: :all, to: 'errors#show_404'
</code>```

This basically works for me as it redirects all of the unknown pages to 404 page. However, it seems it's messing up with the ActiveStorage images path.

Whenever I am placing these codes and redirecting every page that doesn't exist to 404, it's always making my ActiveStorage images broken. As in like this image: https://imgur.com/OCrWQLQ

And if I remove these piece of codes about the 404 redirection, it always turn back to normal images.

What is the best way to do a redirection to 404 page w/o affecting the ActiveStorage images?

答:
You can try doing something like this which might help, in your routes.rb change the line like this:

```<code>match '*path', via: :all, to: 'errors#show_404', constraints: lambda { |req|
    req.path.exclude? 'rails/active_storage'
}
</code>```

So it will exclude that path and let the application show the images. Please change the path as per your requirement (I think it should be rails/active_storage only)

Body:
I searched for every code that I can find here in stackoverflow on how you actually can redirect the pages that doesn't exist or unknown to a 404 page.

For instance you visited this page  http://localhost:3000/thispageisnull since the page doesn't exist it will automatically redirect you to the default 404 custom page I created.

So far here's what I did. On my errors_controller.rb file I place this code:

def show_404
      render "404", status: 404
    end

And then on my routes.rb file, I place this code:

match '*path', via: :all, to: 'errors#show_404'

This basically works for me as it redirects all of the unknown pages to 404 page. However, it seems it's messing up with the ActiveStorage images path.

Whenever I am placing these codes and redirecting every page that doesn't exist to 404, it's always making my ActiveStorage images broken. As in like this image: https://imgur.com/OCrWQLQ

And if I remove these piece of codes about the 404 redirection, it always turn back to normal images.

What is the best way to do a redirection to 404 page w/o affecting the ActiveStorage images?

Body:
You can try doing something like this which might help, in your routes.rb change the line like this:

match '*path', via: :all, to: 'errors#show_404', constraints: lambda { |req|
    req.path.exclude? 'rails/active_storage'
}

So it will exclude that path and let the application show the images. Please change the path as per your requirement (I think it should be rails/active_storage only)


问:
Get rootDir inside beforeSend function in Symfony to intercept Sentry event
I have a service who intercepts the events of Sentry. I'm using a function called beforeSend.

I would to load a json file who contains the data to scrub or to keep. It's a service and I build my constructor with a similar way than others, but the "$this" context doesn't exist when I'm in the debugger in this function.

The kernel is in the Global variables, but I think it's not a good idea... I only would to get the root dir and it's all, but I don't find how to do this in this class...  The constructor seems useless.

Someone could help me with a similar experience ?

EDIT :

Service :

```<code>namespace App\Services;

use Sentry\Event;
use Symfony\Component\HttpKernel\KernelInterface;

class SentryBeforeSendService
{
private static $rootDir;

public function __construct(KernelInterface $kernel)
{
    self::$rootDir = $kernel->getRootDir();
}

/**
 * Scrubs the value of all TARGET_PARAMETERS
 * in the event's request.
 *
 * @param Event $event
 *
 * @return Event
 */
public function beforeSend(Event $event)
{
    $rootDir = self::$rootDir;
    $event->setRequest(self::scrubRequest($event->getRequest(), $rootDir));
    try {
        $composerData = json_decode(file_get_contents($rootDir.'/../composer.json'), true);
        $version      = $composerData['version'];
        $event->setRelease($version);
    } catch (\Exception $e) {
        //do nothing
    }

    return $event;
}

/**
 * Scrubs GET and POST parameters
 *
 * @param array $request
 *
 * @return array
 */
private static function scrubRequest(array $request, $rootDir)
{
    // DO SOMETHING WITH $rootDir to scrub data with external file
}}
</code>```

services.yml :

```<code> app.service.sentry_before_send:
     class: 'App\Services\SentryBeforeSendService'
     arguments: ['@kernel']
</code>```

config_prod.yml :

```<code>sentry:
    dsn: "%sentry_dsn%"
    options:
        environment: "%sentry_environment%"
        # release: '%env(VERSION)%' #overridden from composer.json version in SentryBeforeSendService::beforeSend
        before_send: 'App\Services\SentryBeforeSendService::beforeSend'
</code>```

But it seems the construct never happened.

Thank you very much.

答:
I was unable to inject a parameter, but I found a way to get the project_root from my method. Half victory ...

config_prod.yml:

```<code>sentry:
    dsn: "%sentry_dsn%"
    options:
        environment: "%sentry_environment%"
        # release: '%env(VERSION)%' #overridden from composer.json version in SentryBeforeSendService::beforeSend
        before_send: 'App\Services\SentryBeforeSendService::beforeSend'
        project_root: '%kernel.project_dir%'
</code>```

Service :

```<code><?php

namespace App\Services;

use Sentry\Event;
use Sentry\State\Hub;

class SentryBeforeSendService
{
private static $projectRoot;

/**
 * Scrubs the value of all TARGET_PARAMETERS
 * in the event's request.
 *
 * @param Event $event
 *
 * @return Event
 */
public function beforeSend(Event $event)
{
    $sentryClient      = Hub::getCurrent()->getClient();
    self::$projectRoot = $sentryClient->getOptions()->getProjectRoot();
    $event->setRequest(self::scrubRequest($event->getRequest()));
    try {
        $composerData = json_decode(file_get_contents(self::$projectRoot.'/composer.json'), true);
        $version      = $composerData['version'];
        $event->setRelease($version);
    } catch (\Exception $e) {
        //do nothing
    }

    return $event;
}}
</code>```

Hope it'll help someone else.

Thank you for answers.

Body:
I have a service who intercepts the events of Sentry. I'm using a function called beforeSend.

I would to load a json file who contains the data to scrub or to keep. It's a service and I build my constructor with a similar way than others, but the "$this" context doesn't exist when I'm in the debugger in this function.

The kernel is in the Global variables, but I think it's not a good idea... I only would to get the root dir and it's all, but I don't find how to do this in this class...  The constructor seems useless.

Someone could help me with a similar experience ?

EDIT :

Service :

namespace App\Services;

use Sentry\Event;
use Symfony\Component\HttpKernel\KernelInterface;

class SentryBeforeSendService
{
private static $rootDir;

public function __construct(KernelInterface $kernel)
{
    self::$rootDir = $kernel->getRootDir();
}

/**
 * Scrubs the value of all TARGET_PARAMETERS
 * in the event's request.
 *
 * @param Event $event
 *
 * @return Event
 */
public function beforeSend(Event $event)
{
    $rootDir = self::$rootDir;
    $event->setRequest(self::scrubRequest($event->getRequest(), $rootDir));
    try {
        $composerData = json_decode(file_get_contents($rootDir.'/../composer.json'), true);
        $version      = $composerData['version'];
        $event->setRelease($version);
    } catch (\Exception $e) {
        //do nothing
    }

    return $event;
}

/**
 * Scrubs GET and POST parameters
 *
 * @param array $request
 *
 * @return array
 */
private static function scrubRequest(array $request, $rootDir)
{
    // DO SOMETHING WITH $rootDir to scrub data with external file
}}

services.yml :

 app.service.sentry_before_send:
     class: 'App\Services\SentryBeforeSendService'
     arguments: ['@kernel']

config_prod.yml :

sentry:
    dsn: "%sentry_dsn%"
    options:
        environment: "%sentry_environment%"
        # release: '%env(VERSION)%' #overridden from composer.json version in SentryBeforeSendService::beforeSend
        before_send: 'App\Services\SentryBeforeSendService::beforeSend'

But it seems the construct never happened.

Thank you very much.

Body:
I was unable to inject a parameter, but I found a way to get the project_root from my method. Half victory ...

config_prod.yml:

sentry:
    dsn: "%sentry_dsn%"
    options:
        environment: "%sentry_environment%"
        # release: '%env(VERSION)%' #overridden from composer.json version in SentryBeforeSendService::beforeSend
        before_send: 'App\Services\SentryBeforeSendService::beforeSend'
        project_root: '%kernel.project_dir%'

Service :

<?php

namespace App\Services;

use Sentry\Event;
use Sentry\State\Hub;

class SentryBeforeSendService
{
private static $projectRoot;

/**
 * Scrubs the value of all TARGET_PARAMETERS
 * in the event's request.
 *
 * @param Event $event
 *
 * @return Event
 */
public function beforeSend(Event $event)
{
    $sentryClient      = Hub::getCurrent()->getClient();
    self::$projectRoot = $sentryClient->getOptions()->getProjectRoot();
    $event->setRequest(self::scrubRequest($event->getRequest()));
    try {
        $composerData = json_decode(file_get_contents(self::$projectRoot.'/composer.json'), true);
        $version      = $composerData['version'];
        $event->setRelease($version);
    } catch (\Exception $e) {
        //do nothing
    }

    return $event;
}}

Hope it'll help someone else.

Thank you for answers.


问:
Fixing the 'Use of unassigned local variable' with a null assignment. Why?
With a piece of code like this, the compiler complains on c.MyProperty:

```<code>MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // "Use of unassigned local variable 'c'".
</code>```

Yet it doesn't complain if you assign a null to c in initialization:

```<code>MyClass c = null;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // no complains this time.
</code>```

So, why does this work?  If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?

答:
When you assign null to the variable you're telling the compiler to back off because you know better than him so he should not complain about this.

This is probably due to the fact that assigning null is considered to imply an explicit action by the developer.

Body:
With a piece of code like this, the compiler complains on c.MyProperty:

MyClass c;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // "Use of unassigned local variable 'c'".

Yet it doesn't complain if you assign a null to c in initialization:

MyClass c = null;

try { throw new Exception(); }
catch (Exception) { }

c.MyProperty = 2; // no complains this time.

So, why does this work?  If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?


问:
Angular 9 with RxJs - combining 2 observables results in data but async pipe always sees a null result
I have 2 observables that return data from Firebase, and no matter what type of combination operator I use (forkJoin, CombineLatest etc) the async pipe does not receive the data.

I have an AuthService, with a method that initialises the user from a Firebase realtime database:

```<code>  private initUser(firebaseUser: firebase.User) {
    const myUser: User = {account: {}, profile: {}};
    const userId = `US_${firebaseUser.uid}`;

    const accountSnapshot: Observable<UserAccount> = this.db
      .object(`/users/accounts/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserAccount>;

    const profileSnapshot: Observable<UserProfile> = this.db
      .object(`/users/profiles/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserProfile>;

    forkJoin([accountSnapshot, profileSnapshot])
      .subscribe((result: [UserAccount, UserProfile]) => {
        if (result) {
          myUser.account = result[0];
          myUser.profile = result[1];
          this.setCurrentUser(myUser);
        }
      });
  }
</code>```

CurrentUser is set up as a subject with getter/setter:

```<code>  private currentUser = new Subject<User>();

  public get getCurrentUser(): Observable<User> {
    return this.currentUser.asObservable();
  }

  public setCurrentUser(user: User): void {
    this.currentUser.next(user);
  }
</code>```

In the consuming component:

```<code>  currentUser$: Observable<User>;
  user: User;

  ngOnInit(): void {
    this.currentUser$ = this.authService.getCurrentUser;
    this.currentUser$.subscribe(user => {
      this.user = user;
    });
  }
</code>```

and in the template:

```<code><p>Email: {{ ((currentUser$ | async)?.account).email }}</p>. <- ** DOES NOT WORK **
<p>Email: {{ (user?.account).email }}</p> <- ** DOES WORK **
</code>```

Now, here is the strange part. If I change the initUser method to NOT combine the observables from firebase, but to get them separately (and set the users profile and account as separate operations), then async works. Like this:

```<code>accountSnapshot.subscribe((account: UserAccount) => {
  if (account) {
    myUser.account = account;
    this.setCurrentUser(myUser);
  }
});
profileSnapshot.subscribe((profile: UserProfile) => {
  if (profile) {
    myUser.profile = profile;
    this.setCurrentUser(myUser);
  }
});
</code>```

then the async pipe works.

I have tried changing the forkJoin to CombineLatest and zip. I've also tried removing the pipe(first()) but the async pipe never works.

Why is this?

Is there something wrong with async or with my code, or maybe my understanding of how async works...?

答:
It's because the Subject fires before your view is ready. You should change it to a ReplaySubject so the latest value(s) get replayed on subscription.

```<code>private currentUser = new ReplaySubject<User>(1);
</code>```

(out of scope of question)

Besides that, it seems a bit odd to use a nested subscribe like you have in your initUser. To me you can simplify your code to the following:

```<code>private readonly initUser$ = new Subject<firebase.User>();

readonly currentUser$: Observable<User> = this.initUser$.pipe(
  map((user) => `US_${user.uid}`),
  switchMap((userId) => combineLatest([
    this.db.object<UserAccount>(`/users/accounts/${userId}`).valueChanges(),
    this.db.object<UserProfile>(`/users/profiles/${userId}`).valueChanges()
  ])),
  map(([ account, profile ]) => ({ account, profile } as User)),
  shareReplay(1)
);

private initUser(firebaseUser: firebase.User) {
  this.initUser$.next(firebaseUser);
}
</code>```

In your consuming component you can then just use the service currentUser$ observable to get the user details

Body:
I have 2 observables that return data from Firebase, and no matter what type of combination operator I use (forkJoin, CombineLatest etc) the async pipe does not receive the data.

I have an AuthService, with a method that initialises the user from a Firebase realtime database:

  private initUser(firebaseUser: firebase.User) {
    const myUser: User = {account: {}, profile: {}};
    const userId = `US_${firebaseUser.uid}`;

    const accountSnapshot: Observable<UserAccount> = this.db
      .object(`/users/accounts/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserAccount>;

    const profileSnapshot: Observable<UserProfile> = this.db
      .object(`/users/profiles/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserProfile>;

    forkJoin([accountSnapshot, profileSnapshot])
      .subscribe((result: [UserAccount, UserProfile]) => {
        if (result) {
          myUser.account = result[0];
          myUser.profile = result[1];
          this.setCurrentUser(myUser);
        }
      });
  }

CurrentUser is set up as a subject with getter/setter:

  private currentUser = new Subject<User>();

  public get getCurrentUser(): Observable<User> {
    return this.currentUser.asObservable();
  }

  public setCurrentUser(user: User): void {
    this.currentUser.next(user);
  }

In the consuming component:

  currentUser$: Observable<User>;
  user: User;

  ngOnInit(): void {
    this.currentUser$ = this.authService.getCurrentUser;
    this.currentUser$.subscribe(user => {
      this.user = user;
    });
  }

and in the template:

Email: {{ ((currentUser$ | async)?.account).email }}
. <- ** DOES NOT WORK **

Email: {{ (user?.account).email }}
 <- ** DOES WORK **

Now, here is the strange part. If I change the initUser method to NOT combine the observables from firebase, but to get them separately (and set the users profile and account as separate operations), then async works. Like this:

accountSnapshot.subscribe((account: UserAccount) => {
  if (account) {
    myUser.account = account;
    this.setCurrentUser(myUser);
  }
});
profileSnapshot.subscribe((profile: UserProfile) => {
  if (profile) {
    myUser.profile = profile;
    this.setCurrentUser(myUser);
  }
});

then the async pipe works.

I have tried changing the forkJoin to CombineLatest and zip. I've also tried removing the pipe(first()) but the async pipe never works.

Why is this?

Is there something wrong with async or with my code, or maybe my understanding of how async works...?

Body:
It's because the Subject fires before your view is ready. You should change it to a ReplaySubject so the latest value(s) get replayed on subscription.

private currentUser = new ReplaySubject<User>(1);

(out of scope of question)

Besides that, it seems a bit odd to use a nested subscribe like you have in your initUser. To me you can simplify your code to the following:

private readonly initUser$ = new Subject<firebase.User>();

readonly currentUser$: Observable<User> = this.initUser$.pipe(
  map((user) => `US_${user.uid}`),
  switchMap((userId) => combineLatest([
    this.db.object<UserAccount>(`/users/accounts/${userId}`).valueChanges(),
    this.db.object<UserProfile>(`/users/profiles/${userId}`).valueChanges()
  ])),
  map(([ account, profile ]) => ({ account, profile } as User)),
  shareReplay(1)
);

private initUser(firebaseUser: firebase.User) {
  this.initUser$.next(firebaseUser);
}

In your consuming component you can then just use the service currentUser$ observable to get the user details


问:
Adding an ID tag to a post title (Wordpress)
I've been trying for a while to find a way to add an ID tag to a post title by placing a function in a child theme's functions.php file.

I've tried the code below which works well for including an ID for any h1 to h6's that don't have an ID (& leave any that do alone) INSIDE the post content - but I can't find a way to add an ID to the actual displayed post title?

```<code>function auto_id_headings( $content ) {

    $content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
        if ( ! stripos( $matches[0], 'id=' ) ) :
            $matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
        endif;
        return $matches[0];
    }, $content );

    return $content;

}
add_filter( 'the_content', 'auto_id_headings' );
</code>```

I was thinking it was as simple as changing the_content in the "add_filter" part of the code to the_title but that hasn't worked! FYI the page I'm trying to do this on is here: https://www.futureproofpromotions.com/reaction-form/

Can anybody help?

I've included a screenshot of the page's chrome developer tools explaining what I'm trying to achieve below:

答:
hook the_content return all post content (include HTML), but hook the_title return you value from post_title field (wp_post table).
So if you want to add tag id to id or class DOM element you need make changes in your child theme:
1. copy single.php (or another page template where you need make changes) in your child theme
2. find the place with the_title() function
3. change h1 class (add your function)</p>

Body:
I've been trying for a while to find a way to add an ID tag to a post title by placing a function in a child theme's functions.php file.

I've tried the code below which works well for including an ID for any h1 to h6's that don't have an ID (& leave any that do alone) INSIDE the post content - but I can't find a way to add an ID to the actual displayed post title?

function auto_id_headings( $content ) {

    $content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
        if ( ! stripos( $matches[0], 'id=' ) ) :
            $matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
        endif;
        return $matches[0];
    }, $content );

    return $content;

}
add_filter( 'the_content', 'auto_id_headings' );

I was thinking it was as simple as changing the_content in the "add_filter" part of the code to the_title but that hasn't worked! FYI the page I'm trying to do this on is here: https://www.futureproofpromotions.com/reaction-form/

Can anybody help?

I've included a screenshot of the page's chrome developer tools explaining what I'm trying to achieve below:


问:
How to find minimum sum of elements in a matrix python
How do I compute the minimum sum of elements in a matrix python?
for example:

```<code>z =
np.array([[1, 2, 3],

 [3, 2, 5],

 [2, 4, 4]])
</code>```

The minimum sum of the element is : 1+2+2 = 5

I tried:

```<code>def calculate(a):
    sum = 0
    for i in range(len(a)):
        sum += np.sum(a[i])

    return sum
</code>```

but it gives me 26 instead of 5

答:
You could apply function to find minimum value for each row and sum after that.

```<code>import numpy as np
z = np.array([[1, 2, 3],
             [3, 2, 5],
             [2, 4, 4]])

np.apply_along_axis(np.min,-1,z).sum()
</code>```

How this works? First you define the function. Finding the minimum value, in this case. Second you define the axis you wish to find you values. See full description in documentation below. Lasly I run .sum() to sum up all the elements. For studying purposes I suggest running only

```<code>np.apply_along_axis(np.min,-1,z)
</code>```

see more on Numpy documentation

Body:
How do I compute the minimum sum of elements in a matrix python?
for example:

z =
np.array([[1, 2, 3],

 [3, 2, 5],

 [2, 4, 4]])

The minimum sum of the element is : 1+2+2 = 5

I tried:

def calculate(a):
    sum = 0
    for i in range(len(a)):
        sum += np.sum(a[i])

    return sum

but it gives me 26 instead of 5

Body:
You could apply function to find minimum value for each row and sum after that.

import numpy as np
z = np.array([[1, 2, 3],
             [3, 2, 5],
             [2, 4, 4]])

np.apply_along_axis(np.min,-1,z).sum()

How this works? First you define the function. Finding the minimum value, in this case. Second you define the axis you wish to find you values. See full description in documentation below. Lasly I run .sum() to sum up all the elements. For studying purposes I suggest running only

np.apply_along_axis(np.min,-1,z)

see more on Numpy documentation


问:
Why req.session set in one route, not available in another route call?
I am using Express "express": "~4.13.1" and "express-session": "^1.11.3".
I have set my server like this :

app.js :

```<code>var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var routes = require('./routes/index');
var users = require('./routes/users');
app = express();

// view engine setup
var engines = require('consolidate');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', engines.mustache);
app.set('view engine', 'html');

 // uncomment after placing your favicon in /public
 //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
 app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
      extended: false
 }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

//Using express-session in app with secret key
 app.use(session({
secret: 'mapdcs',
resave: true,
saveUninitialized: true,
cookie: {
    path: '/',
    httpOnly: true,
    secure: false,
    maxAge: null
}
}));

app.use('/', routes);

app.use('/api/users', users);
</code>```

index.js :

```<code>  // First call
  router.post('/adduser', function(req, res, next) {
    req.session.username = red.body.username;
    req.session.save();
    console.log('>>Session data From Add users');
    console.log(req.session); //I got the username session here
  }
  // Second call
  router.post('/check_auth', function(req, res, next) {
     console.log('>> Session data From check_auth');
     console.log(req.session); //Am not getting session here.
  }
</code>```

Am trying to solve this issue since last two days. Can any one help in this please. Thanks in advance.

答: I changed the axios call and set withCredential to true to solve the problem.

Body:
I am using Express "express": "~4.13.1" and "express-session": "^1.11.3".
I have set my server like this :

app.js :

var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var routes = require('./routes/index');
var users = require('./routes/users');
app = express();

// view engine setup
var engines = require('consolidate');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', engines.mustache);
app.set('view engine', 'html');

 // uncomment after placing your favicon in /public
 //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
 app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
      extended: false
 }));
 app.use(cookieParser());
 app.use(express.static(path.join(__dirname, 'public')));

//Using express-session in app with secret key
 app.use(session({
secret: 'mapdcs',
resave: true,
saveUninitialized: true,
cookie: {
    path: '/',
    httpOnly: true,
    secure: false,
    maxAge: null
}
}));

app.use('/', routes);

app.use('/api/users', users);

index.js :

  // First call
  router.post('/adduser', function(req, res, next) {
    req.session.username = red.body.username;
    req.session.save();
    console.log('>>Session data From Add users');
    console.log(req.session); //I got the username session here
  }
  // Second call
  router.post('/check_auth', function(req, res, next) {
     console.log('>> Session data From check_auth');
     console.log(req.session); //Am not getting session here.
  }

Am trying to solve this issue since last two days. Can any one help in this please. Thanks in advance.


问:
to much rerendering in react after using socket io
am doing something similar to omegle, this is some of my code, look at the useEffect functions.

```<code>const Messanger =(props)=>{
let socket = props.socket;
let intro;
const myId = socket.id;
const [readOnly,setReadOnly] = useState(true);
const [messages,setMessages]=useState([]);
const [stranger_name,setStranger_name] = useState(null);
const [disconnected,setDisconnected] = useState(false);
const [room,setRoom] = useState(null);
let messageRef = React.createRef();
let messagesEnd =React.createRef();

</code>```

when the server find a match bettwen two users, it connects them together in one room and then , it sends to both of them a joinRoom socket request to inform the front that they are connected

```<code>

useEffect(()=>{

  socket.once("joinRoom",(data)=>{
    setDisconnected(false);

  setMessages([]);
  setStranger_name(data.name);
  setRoom(data.room);
   setReadOnly(false);
  console.log("JOING ROOM")
});

},[stranger_name])
</code>```

when user receiver a message, this script will be triggerd

```<code>useEffect(()=>{
  socket.once('messageToClient',(data)=>{
    setMessages([...messages,{message:data.message,id:data.id}])
    });
    scrollToBottom();
},[messages])

</code>```

and here before rendering i console log some text to see how many times i render

```<code>console.log('render')

return (DOM)
</code>```

the main issue is that each time i disconnect with user that am chating with, and start again, the DOM re-render to many times , for example the console.log code get triggerd 4 times when message received , and when i start to chat with another user, the console.log('render') function gets triggert 8 times and so on

答:
you are essentially creating an infinite loop by resubscribing to the socket event when the messages changes, causing setMessages to be triggered multiple times, which causes your hook to resubscribe etc.etc.

the following is a temp. fix but not the complete answer as you should handle socket messeges outside of your component, store them in redux and then consume them.

```<code>useEffect(()=>{
  socket.once('messageToClient',(data)=>{
    setMessages((prevMessages)=>[...prevMessages,{message:data.message,id:data.id}])
    });
    scrollToBottom();
},[])
</code>```

Body:
am doing something similar to omegle, this is some of my code, look at the useEffect functions.

const Messanger =(props)=>{
let socket = props.socket;
let intro;
const myId = socket.id;
const [readOnly,setReadOnly] = useState(true);
const [messages,setMessages]=useState([]);
const [stranger_name,setStranger_name] = useState(null);
const [disconnected,setDisconnected] = useState(false);
const [room,setRoom] = useState(null);
let messageRef = React.createRef();
let messagesEnd =React.createRef();

when the server find a match bettwen two users, it connects them together in one room and then , it sends to both of them a joinRoom socket request to inform the front that they are connected

useEffect(()=>{

  socket.once("joinRoom",(data)=>{
    setDisconnected(false);

  setMessages([]);
  setStranger_name(data.name);
  setRoom(data.room);
   setReadOnly(false);
  console.log("JOING ROOM")
});

},[stranger_name])

when user receiver a message, this script will be triggerd

useEffect(()=>{
  socket.once('messageToClient',(data)=>{
    setMessages([...messages,{message:data.message,id:data.id}])
    });
    scrollToBottom();
},[messages])

and here before rendering i console log some text to see how many times i render

console.log('render')

return (DOM)

the main issue is that each time i disconnect with user that am chating with, and start again, the DOM re-render to many times , for example the console.log code get triggerd 4 times when message received , and when i start to chat with another user, the console.log('render') function gets triggert 8 times and so on

Body:
you are essentially creating an infinite loop by resubscribing to the socket event when the messages changes, causing setMessages to be triggered multiple times, which causes your hook to resubscribe etc.etc.

the following is a temp. fix but not the complete answer as you should handle socket messeges outside of your component, store them in redux and then consume them.

useEffect(()=>{
  socket.once('messageToClient',(data)=>{
    setMessages((prevMessages)=>[...prevMessages,{message:data.message,id:data.id}])
    });
    scrollToBottom();
},[])


答:
JSON doesn't have any representation for functions. It's a data notation. Even if you trick PHP into sending a function (as you appear to be trying to do), a proper JSON deserializer on the client will throw an exception (ideally). Some very naive ones that rely on eval may pass the function through, but at that point, you're not using JSON, you're using JavaScript.

If you want to send back code, you need to send back JavaScript.

Separately, on this line:

```<code>alert(json.function());
</code>```

...you have a syntax error. function is a reserved word in JavaScript. You can't use it as a property name literal. If you create a property with the name "function" (which you can, but probably shouldn't), to access it you have to use the string notation for accessing properties:

```<code>alert(json["function"]());
</code>```

See also Gaby's answer, you seem to have mixed some Prototype code (evalJSON) into things.

Title: function name in json response - not working

Body:
I am trying to send a function in JSON response and tried to alert that function in js. Below is the code.

JS:

$('input').keyup(function(){
    $.ajax({
        type: "POST",
        url: "sample.php",
        dataType : 'json',
        data: 'val='+$('input').val(),
        success: function(response){

         var json = transport.responseText.evalJSON();
         alert(json.function()); // => **should alert 'foo bar' - but not**
        }
    });
});

PHP:

<?php
// Our sample array
$foo = array(
  'string'  => 'bar',
  'function'=> 'function(){return "foo bar";}'
);
$value_arr = array();
$replace_keys = array();
foreach($foo as $key => &$value){
  // Look for values starting with 'function('
  if(strpos($value, 'function(')===0){
    // Store function string.
    $value_arr[] = $value;
    // Replace function string in $foo with a 'unique' special key.
    $value = '%' . $key . '%';
    // Later on, we'll look for the value, and replace it.
    $replace_keys[] = '"' . $value . '"';
  }
}

// Now encode the array to json format
$json = json_encode($foo);

/* $json looks like:
{
  "number":1,
  "float":1.5,
  "array":[1,2],
  "string":"bar",
  "function":"%function%"
}
*/
// Replace the special keys with the original string.
$json = str_replace($replace_keys, $value_arr, $json);

// Send to to the client
echo $json;

/* This echoes the following string:
{
  "string":"bar",
  "function":function(){return "foo bar";}
}
*/
?>

what am I doing wrong in the above? Any help is appreciated.

Body:
JSON doesn't have any representation for functions. It's a data notation. Even if you trick PHP into sending a function (as you appear to be trying to do), a proper JSON deserializer on the client will throw an exception (ideally). Some very naive ones that rely on eval may pass the function through, but at that point, you're not using JSON, you're using JavaScript.

If you want to send back code, you need to send back JavaScript.

Separately, on this line:

alert(json.function());

...you have a syntax error. function is a reserved word in JavaScript. You can't use it as a property name literal. If you create a property with the name "function" (which you can, but probably shouldn't), to access it you have to use the string notation for accessing properties:

alert(json["function"]());

See also Gaby's answer, you seem to have mixed some Prototype code (evalJSON) into things.


问:
Setting varibable to saved value always gets true
I am working on a desktop application with electron, which means, that I am using javascript and other web tools. In this bit of code, I am trying to read a boolean from localStorage and writing it to the checked attribute of an HTML-checkbox:
devtools = document.getElementById('dev-tools-checkbox');
console.log('The saved value: ' + localStorage.getItem('devtools'));
devtools.checked = localStorage.getItem('devtools');

The strange thing is, that no matter what the console shows the logged value as, the checkbox always gets set to true. When reversing the input like this
devtools.checked = !localStorage.getItem('devtools');
the value is always false. I have checked that the right value is set, and the logged value is correct.

When I set the following: devtools.checked = false; it correctly sets the value to false. Same with devtools.checked = true.

Any clue as to where the always true value is coming from would be greatly appreciated. If you need any more information, just ask.

Thanks in advance

答:
According to the MDN Documentation on localStorage.setItem (), you can only store elements of the type DOMString inside any Storage a User Agent (aka browser) offers. Thus, what you are retrieving is a string and since the HTML attribute checked on a checkbox does not need any input, it will be checked nonetheless.

Take this checkbox for example:

<input type="checkbox" checked="false" />```
</div>
</div>
</p>

<p>Although the <code>checked</code> attribute is set to <code>false</code>, the checkbox is checked. Thus, you need to first convert your string value you're retrieving from <code>localStorage</code> to a boolean. This can be done by using the following code:</p>

<pre class="lang-js prettyprint-override"><code>devtools = document.getElementById ('dev-tools-checkbox');
console.log ('The saved value: ' + localStorage.getItem('devtools'));
devtools.checked = localStorage.getItem('devtools') === "true";
</code>```

Body:
According to the MDN Documentation on localStorage.setItem (), you can only store elements of the type DOMString inside any Storage a User Agent (aka browser) offers. Thus, what you are retrieving is a string and since the HTML attribute checked on a checkbox does not need any input, it will be checked nonetheless.

Take this checkbox for example:

<input type="checkbox" checked="false" />

Although the checked attribute is set to false, the checkbox is checked. Thus, you need to first convert your string value you're retrieving from localStorage to a boolean. This can be done by using the following code:

devtools = document.getElementById ('dev-tools-checkbox');
console.log ('The saved value: ' + localStorage.getItem('devtools'));
devtools.checked = localStorage.getItem('devtools') === "true";


问:
POST http://localhost:3000/login/aa/aa 404 (Not Found)
I have an angular app and a nodejs backend server. I want to get data from my backend but when I try to connect to it with Angular HTTPClient, it says: POST http://localhost:3000/login/aa/aa 404 (Not Found).However, when I put the link manually into the browser, it works perfectly fine. Here is some code:

service.ts

```<code>addUser(user: IUser): Observable<IUser> {
        return this.httpClient.post<IUser>(`http://localhost:3000/login/${user.email}/${user.passwort}`, user, {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
            })
        })
            .pipe(catchError(this.handleError));
    }
</code>```

index.js

```<code>var mysql = require('mysql');
var express = require('express');
var app = express();

const port = process.env.PORT || 3000;
[...]
app.get('/login/:email/:pw',function(req,res) {
  res.setHeader('Content-Type', 'application/json');
  var passwort = new Passwort(''+req.params.pw);
  passwort.comparePasswort();
  con.query("SELECT u.Email, u.Hash FROM User u WHERE u.Email LIKE "+ "'" + req.params.email+ "'", function(err, result ){
    if(err) throw err;
    console.log(result)
    res.send("test")
  })

});
</code>```

Thanks for every answer and for your time!

答:
In backed you declared a get method and from frontend you are calling post. your code in service should be :- </p>

```<code>addUser(user: IUser): Observable<IUser> {
        return this.httpClient.get<IUser>(`http://localhost:3000/login/${user.email}/${user.passwort}`, {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
            })
        })
            .pipe(catchError(this.handleError));
    }
</code>```

Body:
I have an angular app and a nodejs backend server. I want to get data from my backend but when I try to connect to it with Angular HTTPClient, it says: POST http://localhost:3000/login/aa/aa 404 (Not Found).However, when I put the link manually into the browser, it works perfectly fine. Here is some code:

service.ts

addUser(user: IUser): Observable<IUser> {
        return this.httpClient.post<IUser>(`http://localhost:3000/login/${user.email}/${user.passwort}`, user, {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
            })
        })
            .pipe(catchError(this.handleError));
    }

index.js

var mysql = require('mysql');
var express = require('express');
var app = express();

const port = process.env.PORT || 3000;
[...]
app.get('/login/:email/:pw',function(req,res) {
  res.setHeader('Content-Type', 'application/json');
  var passwort = new Passwort(''+req.params.pw);
  passwort.comparePasswort();
  con.query("SELECT u.Email, u.Hash FROM User u WHERE u.Email LIKE "+ "'" + req.params.email+ "'", function(err, result ){
    if(err) throw err;
    console.log(result)
    res.send("test")
  })

});

Thanks for every answer and for your time!

Body:
In backed you declared a get method and from frontend you are calling post. your code in service should be :-

addUser(user: IUser): Observable<IUser> {
        return this.httpClient.get<IUser>(`http://localhost:3000/login/${user.email}/${user.passwort}`, {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
            })
        })
            .pipe(catchError(this.handleError));
    }


问:
How to pass command line arguments to a PowerShell script invoked by a doskey
I have a caller.cmd file which has a DOSKEY set like this:

```<code>DOSKEY startnow=call powershell getscalled.ps1
</code>```

Now the script getscalled.ps1 has two switch parameters defined in parameter sets like this:

```<code>param(
    [Parameter(Mandatory=$false,ParameterSetName='first')]
    [switch]$thisIsFirst,
    [Parameter(Mandatory=$false,ParameterSetName='second')]
    [switch]$thisIsSecond
)
</code>```

So, only one of the two parameters can be provided at a time. I want the parameter to be provided from the command line itself using the DOSKEY that I have set up. Something like:

```<code>startnow -thisIsFirst
</code>```

Any help on how to achieve this?
Thanks!

答:
Create macro like this(so use $1 $2... for parameters);

```<code>DOSKEY startnow=script.ps1 $1
</code>```

So, you could call;

```<code>startnow -thisIsFirst
</code>```

Body:
I have a caller.cmd file which has a DOSKEY set like this:

DOSKEY startnow=call powershell getscalled.ps1

Now the script getscalled.ps1 has two switch parameters defined in parameter sets like this:

param(
    [Parameter(Mandatory=$false,ParameterSetName='first')]
    [switch]$thisIsFirst,
    [Parameter(Mandatory=$false,ParameterSetName='second')]
    [switch]$thisIsSecond
)

So, only one of the two parameters can be provided at a time. I want the parameter to be provided from the command line itself using the DOSKEY that I have set up. Something like:

startnow -thisIsFirst

Any help on how to achieve this?
Thanks!

Body:
Create macro like this(so use $1 $2... for parameters);

DOSKEY startnow=script.ps1 $1

So, you could call;

startnow -thisIsFirst


问:
How to change condition from a while loop
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :

```<code>book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
</code>```

When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.

What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?

Appreciate any help.

Thanks and Regards

Sachin

答:
if you whant to keep ypur code use:
another condintion to tell the loop that the completed have been updated and quit it!</p>

```<code>book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")

        if completed == "yes":
            completed = completed
            break
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
    option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")
</code>```

Body:
I am trying to create a reading list, using 2 functions - one to add books and another to display books. The add books function need to execute till such time user confirms that the update is completed. Following is the code :

book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
        option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

When I execute this code, the While loop ignores the completed condition and keeps asking for adding more books even though the user confirms updated completed.

What is wrong ? I understand that I am trying to update completed inside the loop, and that may be the reason. What are the options ?

Appreciate any help.

Thanks and Regards

Sachin

Body:
if you whant to keep ypur code use:
another condintion to tell the loop that the completed have been updated and quit it!

book_list = []

def add_books(books):
    book_record = {}
    completed = "no"
    while completed == "no":
        title = input("Enter title : ")
        author = input("Enter author : ")
        year = input("Enter year of publication : ")
        book_record.update({"title": title, "author": author, "year_publ": year})
        books.append(book_record)
        print(books)
        completed = input("update completed ? yes/no")

        if completed == "yes":
            completed = completed
            break
    return books

def display_books(books):
    for book in books:
        title = book["title"]
        author = book["author"]
        year = book["year_publ"]
        print(f"{title}, {author}, {year}")

option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")

while option != "q" :
    if option == "a":
        book_list = add_books(book_list)
    elif option == "d":
        display_books(book_list)
    else:
        print("Invalid Option")
    option = input("Enter 'a' to add and 'd' to display the books or 'q' to quit :")


答:
before using /:email you need to subscribe this particular element

```<code>    const mongoose = require("mongoose");
    const User = mongoose.model("User");

    const userParams = (req, res, next, email) => {
      User.findOne({email:email})
        .then((user)=> {
          if (!user) {
            return res.sendStatus(404);
          }
          req.user = user;
          return next();
        })
        .catch(next);
    };

    module.exports = userParams;
</code>```

then use that in express router by typing

```<code>router.param("email", userParams);
</code>```

this way your router will get to know what the params you are trying to send

Title: POST http://localhost:3000/login/aa/aa 404 (Not Found)

Body:
before using /:email you need to subscribe this particular element

    const mongoose = require("mongoose");
    const User = mongoose.model("User");

    const userParams = (req, res, next, email) => {
      User.findOne({email:email})
        .then((user)=> {
          if (!user) {
            return res.sendStatus(404);
          }
          req.user = user;
          return next();
        })
        .catch(next);
    };

    module.exports = userParams;

then use that in express router by typing

router.param("email", userParams);

this way your router will get to know what the params you are trying to send


问:
Search for every value from one array in another array in Javascript
Please, I need your help.
I have array of a date range:

```<code>dateRange = [1 Jun 2020, 2 Jun 2020, 3 Jun 2020, 4 Jun 2020, 5 Jun 2020];
</code>```

and an array of offers:

```<code>offers = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
{DeskUID: "B211B5", Day: 3 Jun 2020}
{DeskUID: "B211B5", Day: 4 Jun 2020}
]
</code>```

How to create a result array where will be just offers from offers array which have entries for every single day in the dateRange array?

```<code>result = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
]
</code>```

The solution has to work in IE11 - no arrow functions,...

EDIT:
If I have offers array like the below, your function gives me wrong results.

```<code>dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020']

offers = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '1 Jun 2020'}
    {DeskUID: "B211A15", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

result = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

expected result = [
    {DeskUID: "B201A15", Day: '1 Jun 2020'}
    {DeskUID: "B201A15", Day: '2 Jun 2020'}
    {DeskUID: "B201A15", Day: '3 Jun 2020'}
    ]
</code>```

答:
Do you want something like this ?

var dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020', '4 Jun 2020', '5 Jun 2020'];
var offers = [{DeskUID: "B200B3", Day: '1 Jun 2020'},{DeskUID: "B200B3", Day: '2 Jun 2020'},{DeskUID: "B200B3", Day: '3 Jun 2020'},{DeskUID: "B200B3", Day: '4 Jun 2020'},{DeskUID: "B200B3", Day: '5 Jun 2020'},{DeskUID: "B211B5", Day: '3 Jun 2020'},{DeskUID: "B211B5", Day: '4 Jun 2020'}];

var result = dateRange.map(function(date){
  return offers.find(function(offer){
      return new Date(offer.Day).getTime() == new Date(date).getTime();
  })
});

console.log(result);```
</div>
</div>
</p>

<p><strong>UPDATE</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020', '4 Jun 2020', '5 Jun 2020'];
var offers = [{DeskUID: "B200B3", Day: '1 Jun 2020'},{DeskUID: "B200B3", Day: '2 Jun 2020'},{DeskUID: "B200B3", Day: '3 Jun 2020'},{DeskUID: "B200B3", Day: '4 Jun 2020'},{DeskUID: "B200B3", Day: '5 Jun 2020'},{DeskUID: "B211B5", Day: '3 Jun 2020'},{DeskUID: "B211B5", Day: '4 Jun 2020'}];

var result = Object.values(offers.reduce((acc, elem)=>{
 acc[elem.DeskUID] = acc[elem.DeskUID] || [];
 acc[elem.DeskUID].push(elem);
 return acc;
},{})).filter(elem=>elem.length == dateRange.length)[0];

console.log(result);</code>```

Body:
Please, I need your help.
I have array of a date range:

dateRange = [1 Jun 2020, 2 Jun 2020, 3 Jun 2020, 4 Jun 2020, 5 Jun 2020];

and an array of offers:

offers = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
{DeskUID: "B211B5", Day: 3 Jun 2020}
{DeskUID: "B211B5", Day: 4 Jun 2020}
]

How to create a result array where will be just offers from offers array which have entries for every single day in the dateRange array?

result = [
{DeskUID: "B200B3", Day: 1 Jun 2020}
{DeskUID: "B200B3", Day: 2 Jun 2020}
{DeskUID: "B200B3", Day: 3 Jun 2020}
{DeskUID: "B200B3", Day: 4 Jun 2020}
{DeskUID: "B200B3", Day: 5 Jun 2020}
]

The solution has to work in IE11 - no arrow functions,...

EDIT:
If I have offers array like the below, your function gives me wrong results.

dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020']

offers = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '1 Jun 2020'}
    {DeskUID: "B211A15", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

result = [
    {DeskUID: "B201A10", Day: '1 Jun 2020'}
    {DeskUID: "B201A10", Day: '2 Jun 2020'}
    {DeskUID: "B211A15", Day: '3 Jun 2020'}
    ]

expected result = [
    {DeskUID: "B201A15", Day: '1 Jun 2020'}
    {DeskUID: "B201A15", Day: '2 Jun 2020'}
    {DeskUID: "B201A15", Day: '3 Jun 2020'}
    ]

Body:
Do you want something like this ?

var dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020', '4 Jun 2020', '5 Jun 2020'];
var offers = [{DeskUID: "B200B3", Day: '1 Jun 2020'},{DeskUID: "B200B3", Day: '2 Jun 2020'},{DeskUID: "B200B3", Day: '3 Jun 2020'},{DeskUID: "B200B3", Day: '4 Jun 2020'},{DeskUID: "B200B3", Day: '5 Jun 2020'},{DeskUID: "B211B5", Day: '3 Jun 2020'},{DeskUID: "B211B5", Day: '4 Jun 2020'}];

var result = dateRange.map(function(date){
  return offers.find(function(offer){
      return new Date(offer.Day).getTime() == new Date(date).getTime();
  })
});

console.log(result);

UPDATE

var dateRange = ['1 Jun 2020', '2 Jun 2020', '3 Jun 2020', '4 Jun 2020', '5 Jun 2020'];
var offers = [{DeskUID: "B200B3", Day: '1 Jun 2020'},{DeskUID: "B200B3", Day: '2 Jun 2020'},{DeskUID: "B200B3", Day: '3 Jun 2020'},{DeskUID: "B200B3", Day: '4 Jun 2020'},{DeskUID: "B200B3", Day: '5 Jun 2020'},{DeskUID: "B211B5", Day: '3 Jun 2020'},{DeskUID: "B211B5", Day: '4 Jun 2020'}];

var result = Object.values(offers.reduce((acc, elem)=>{
 acc[elem.DeskUID] = acc[elem.DeskUID] || [];
 acc[elem.DeskUID].push(elem);
 return acc;
},{})).filter(elem=>elem.length == dateRange.length)[0];

console.log(result);


问:
Oracle sql combination
I have table with this result (just for example, actually it has more records):

```<code>31.3.2020   A  1
30.4.2020   A  2
31.3.2020   B  1
30.4.2020   C  3
</code>```

Is possible to add there empty missing values by sql?
In this case:

```<code>30.4.2020   B  0
31.3.2020   C  0
</code>```

Thanks

答:
You can use anti join and NOT EXISTS as follows:

```<code>SQL> with your_data (col1, col2, col3) as
  2  (select to_date('31.3.2020','dd.mm.rrrr'),   'A',  1 from dual union all
  3  select to_date('30.4.2020','dd.mm.rrrr'),   'A',  2 from dual union all
  4  select to_date('31.3.2020','dd.mm.rrrr'),   'B',  1 from dual union all
  5  select to_date('30.4.2020','dd.mm.rrrr'),   'C',  3 from dual)
  6  -- your query starts from here
  7  select distinct t1.col1, t2.col2, 0 as col3
  8  from your_data t1 join your_data t2 on t1.col1 <> t2.col1
  9  where not exists
 10  (select 1 from your_data t where t2.col2 = t.col2 and t1.col1 = t.col1)
 11  order by t1.col1, t2.col2;

COL1      C       COL3
--------- - ----------
31-MAR-20 C          0
30-APR-20 B          0

SQL>
</code>```

Then UNION it with your data.

Title: Oracle sql combination

Body:
I have table with this result (just for example, actually it has more records):

31.3.2020   A  1
30.4.2020   A  2
31.3.2020   B  1
30.4.2020   C  3

Is possible to add there empty missing values by sql?
In this case:

30.4.2020   B  0
31.3.2020   C  0

Thanks

Body:
You can use anti join and NOT EXISTS as follows:

SQL> with your_data (col1, col2, col3) as
  2  (select to_date('31.3.2020','dd.mm.rrrr'),   'A',  1 from dual union all
  3  select to_date('30.4.2020','dd.mm.rrrr'),   'A',  2 from dual union all
  4  select to_date('31.3.2020','dd.mm.rrrr'),   'B',  1 from dual union all
  5  select to_date('30.4.2020','dd.mm.rrrr'),   'C',  3 from dual)
  6  -- your query starts from here
  7  select distinct t1.col1, t2.col2, 0 as col3
  8  from your_data t1 join your_data t2 on t1.col1 <> t2.col1
  9  where not exists
 10  (select 1 from your_data t where t2.col2 = t.col2 and t1.col1 = t.col1)
 11  order by t1.col1, t2.col2;

COL1      C       COL3
--------- - ----------
31-MAR-20 C          0
30-APR-20 B          0

SQL>

Then UNION it with your data.


答:
In your index.js file, you are creating a handler for a GET request (which is the default request sent by your browser while accessing your webpage)

But in your service.ts file you are trying to send a post request to the server which is not handled, so the simple solution would be to replace the line

```<code>return this.httpClient.post<IUser> `http://localhost:3000/login/${user.email}/${user.passwort}`, user, {
</code>```

with:

```<code>return this.httpClient.get<IUser> `http://localhost:3000/login/${user.email}/${user.passwort}`, user, {
</code>```

For more info you can read this: https://angular.io/guide/http

Body:
In your index.js file, you are creating a handler for a GET request (which is the default request sent by your browser while accessing your webpage)

But in your service.ts file you are trying to send a post request to the server which is not handled, so the simple solution would be to replace the line

return this.httpClient.post<IUser> `http://localhost:3000/login/${user.email}/${user.passwort}`, user, {

with:

return this.httpClient.get<IUser> `http://localhost:3000/login/${user.email}/${user.passwort}`, user, {

For more info you can read this: https://angular.io/guide/http


问:
Object is not extensible error when creating new attribute for array of objects
I have a function that needs to extend a javascript array, including a new attribute called selected:

```<code>export const initSelect = (data) => {

    let newData = data.concat();
    newData.map((item) => {
        item.selected = false;
    })

    return newData;
}
</code>```

data is a ReactJS state value (comes from this.state.data when calling the function), but this didn't seem to be a problem as newData is a new copy of data array...

I'm getting the following error:

```<code>TypeError: Cannot add property selected, object is not extensible
</code>```

答:
```<code>data = JSON.parse(JSON.stringify(data));
</code>```

Body:
I have a function that needs to extend a javascript array, including a new attribute called selected:

export const initSelect = (data) => {

    let newData = data.concat();
    newData.map((item) => {
        item.selected = false;
    })

    return newData;
}

data is a ReactJS state value (comes from this.state.data when calling the function), but this didn't seem to be a problem as newData is a new copy of data array...

I'm getting the following error:

TypeError: Cannot add property selected, object is not extensible


问:
Database Library/ORM mapper without configuration
I'm currently planning an application that does work on an object relational database. The work is simple: just fetch data, analyse it, display it to the user and write back some changes. To support a wide range of databases I'm currently searching for access library that meets all (or at least some) of the following requirements (sorted by importance):

Java or Python. I'm using Jython, so both is possible but I would prefer Python over Java

Return metadata about the database. I need to be able to fetch a list of all tables and their schema. Ideally, this information is given back as objects.

ability to fetch a record from multiple tables using a

complete runtime configuration from code. I don't want something that need i.e. a mapping configuration in some XML file.

some kind of ORM mapping. I could live without it, but it would be nice to have. I would be totally okay if I get a bunch of objects with data in them and had to do the rest by reflection.

What is the best library for such a task (given that at least one exists ;) ).

答: You could use SQLAlchemy which uses zxJDBC on Jython. Django can also run on Jython, so that's another option. Both let you use Python to declare your models. Django's ORM is a bit less verbose, while SQLAlchemy is arguably more powerful, and tends to offer finer control. There is also a nice declarative wrapper for working with SQLAlchemy called Elixir.</p>