问:
populating map globally
I have declared the following   map globally and trying to populate globally.

```<code>   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));
</code>```

it is showing error like error C2143: syntax error : missing ';' before '.' at line2.

1 Am I doing something wrong

2. why can't we initialize the map globally.

答:
Only declarations and definitions can be in global scope, and the call to map::insert() is not one of them.

Since you're using >> in templates, your compiler must be new enough for C++0x support.

Try the C++0x initializer syntax then:

```<code>typedef std::map<unsigned short, std::pair<char,std::string>> DeviceTypeList;
DeviceTypeList g_DeviceTypeList = {
              {(unsigned short)SINGLE_CELL_CAMERA, {'B',"Single Cell Camera"}}
           };
</code>```

test: https://ideone.com/t4MAZ

Although the diagnostic suggests it is MSVS, which doesn't have C++0x initializers as of 2010, so try the boost initializer syntax instead:

```<code>typedef std::map<unsigned short, std::pair<char,std::string> > DeviceTypeList;
DeviceTypeList g_DeviceTypeList =
           boost::assign::map_list_of((unsigned short)SINGLE_CELL_CAMERA,
                                       std::make_pair('B',"Single Cell Camera"));
</code>```

test: https://ideone.com/KB0vV

Title: populating map globally

Body:
I have declared the following   map globally and trying to populate globally.

   1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList;
   2: DeviceTypeList g_DeviceTypeList;
   3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA,
   std::make_pair('B',"Single Cell Camera")));

it is showing error like error C2143: syntax error : missing ';' before '.' at line2.

1 Am I doing something wrong

2. why can't we initialize the map globally.

Body:
Only declarations and definitions can be in global scope, and the call to map::insert() is not one of them.

Since you're using >> in templates, your compiler must be new enough for C++0x support.

Try the C++0x initializer syntax then:

typedef std::map<unsigned short, std::pair<char,std::string>> DeviceTypeList;
DeviceTypeList g_DeviceTypeList = {
              {(unsigned short)SINGLE_CELL_CAMERA, {'B',"Single Cell Camera"}}
           };

test: https://ideone.com/t4MAZ

Although the diagnostic suggests it is MSVS, which doesn't have C++0x initializers as of 2010, so try the boost initializer syntax instead:

typedef std::map<unsigned short, std::pair<char,std::string> > DeviceTypeList;
DeviceTypeList g_DeviceTypeList =
           boost::assign::map_list_of((unsigned short)SINGLE_CELL_CAMERA,
                                       std::make_pair('B',"Single Cell Camera"));

test: https://ideone.com/KB0vV


来源: stackexchange

问:
How to separate one column from a DataFrame in Python / Jupyter?
I'm trying to the convert the below DataFrame into Series:

The columns "Emerging Markets" and "Event Driven" are of interest to me. So, I create a new DataFrame by using the code below:

```<code>columns = ['Emerging Markets','Event Driven'] #Indicate which columns I want to use
TargetData = Hedgefunds[columns]
</code>```

But now I want to create two series, one for "Emerging Markets" and one for "Event Driven" but I'm can't figure out how to do it. I used the code below (same logic as above) but it does not work:

```<code>Emerging_Markets_Column = ['Emerging Markets']
EM = TargetData['Emerging_Markets-Column']
</code>```

What would be the best way to go about separating the columns from each other?

答:
Why dont you use the first dataframe as reference and try .</p>

```<code>EM = Hedgefunds['Emerging Markets']
ED = Hedgefunds['Event Driven']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to the convert the below DataFrame into Series:

The columns "Emerging Markets" and "Event Driven" are of interest to me. So, I create a new DataFrame by using the code below:

columns = ['Emerging Markets','Event Driven'] #Indicate which columns I want to use
TargetData = Hedgefunds[columns]

But now I want to create two series, one for "Emerging Markets" and one for "Event Driven" but I'm can't figure out how to do it. I used the code below (same logic as above) but it does not work:

Emerging_Markets_Column = ['Emerging Markets']
EM = TargetData['Emerging_Markets-Column']

What would be the best way to go about separating the columns from each other?

Body:
Why dont you use the first dataframe as reference and try .

EM = Hedgefunds['Emerging Markets']
ED = Hedgefunds['Event Driven']


问:
Second dropdown list is empty
The first dropdown should select all the semester data, and it works. For the second dropdown, it is supposed to select all the student_prg data but it doesn't work (dropdown list empty).

Is there any method to make it work? Please let me if there is any other way to make both the dropdown work.

config.php

```<code><?php

define('DBINFO','mysql:host=localhost;dbname=marketing_system');
define('DBUSER','root');
define('DBPASS','');

$conn = mysqli_connect("localhost","root","","marketing_system");

?>
</code>```

testreport.php

```<code><div class="modal-body">
        <div class="form-group">
              <label for="title">Select Semester:</label>
              <select name="semester" class="form-control">
                  <option value="">--- Select Semester ---</option>

                  <?php
                    require('../setting/config.php');
                      $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
                      $do = mysqli_query($conn, $query);
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].'">'.$row['semester'].'</option>';
                      }
                  ?>
              </select>
          </div>
          <div class="form-group">
              <label for="title">Select Programme:</label>
              <select name="prg" class="form-control">
                <option value="">--- Select Programme ---</option>

                <?php
                require('../setting/config.php');
                      $query2 = "SELECT DISTINCT student_prg FROM marketing_data ORDER BY student_prg DESC";
                      $do = mysqli_query($conn, $query2);
                      var_dump($do); die();
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].'">'.$row['student_prg'].'</option>';
                      }
                ?>
              </select>
          </div>
</code>```

Database

```<code>mysql> describe marketing_data;
+---------------+------------------+------+-----+---------+--------------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+--------------------+
| student_matric| varchar(10) unsigned | NO   | PRI | NULL    | auto_increment |
| student_prg   | text unsigned        | YES  |     | NULL    |                |
| semester      | varchar(10)          | YES  |     | NULL    |                |
| intake_year   | int(10)              | YES  |     | NULL    |                |
| student_city  | text                 | YES  |     | NULL    |                |
| city_lat      | varchar(20)          | YES  |     | NULL    |                |
| city_long     | varchar(20)          | YES  |     | NULL    |                |
| student_state | text                 | YES  |     | NULL    |                |
| state_code    | varchar(100)         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+--------------------+
</code>```

答:
You are calling

```<code>require('../setting/config.php')
</code>```

twice, which is unnecessary and also will cause an issue. Remove that and your problem will be solved.

Title: Second dropdown list is empty

Body:
The first dropdown should select all the semester data, and it works. For the second dropdown, it is supposed to select all the student_prg data but it doesn't work (dropdown list empty).

Is there any method to make it work? Please let me if there is any other way to make both the dropdown work.

config.php

<?php

define('DBINFO','mysql:host=localhost;dbname=marketing_system');
define('DBUSER','root');
define('DBPASS','');

$conn = mysqli_connect("localhost","root","","marketing_system");

?>

testreport.php

              Select Semester:
              <select name="semester" class="form-control">
                  <option value="">--- Select Semester ---</option>

                  <?php
                    require('../setting/config.php');
                      $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
                      $do = mysqli_query($conn, $query);
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].'">'.$row['semester'].'</option>';
                      }
                  ?>
              </select>

              Select Programme:
              <select name="prg" class="form-control">
                <option value="">--- Select Programme ---</option>

                <?php
                require('../setting/config.php');
                      $query2 = "SELECT DISTINCT student_prg FROM marketing_data ORDER BY student_prg DESC";
                      $do = mysqli_query($conn, $query2);
                      var_dump($do); die();
                      while($row = mysqli_fetch_array($do)){
                          echo '<option value="'.$row['student_matric'].'">'.$row['student_prg'].'</option>';
                      }
                ?>
              </select>

Database

mysql> describe marketing_data;
+---------------+------------------+------+-----+---------+--------------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+--------------------+
| student_matric| varchar(10) unsigned | NO   | PRI | NULL    | auto_increment |
| student_prg   | text unsigned        | YES  |     | NULL    |                |
| semester      | varchar(10)          | YES  |     | NULL    |                |
| intake_year   | int(10)              | YES  |     | NULL    |                |
| student_city  | text                 | YES  |     | NULL    |                |
| city_lat      | varchar(20)          | YES  |     | NULL    |                |
| city_long     | varchar(20)          | YES  |     | NULL    |                |
| student_state | text                 | YES  |     | NULL    |                |
| state_code    | varchar(100)         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+--------------------+

Body:
You are calling

require('../setting/config.php')

twice, which is unnecessary and also will cause an issue. Remove that and your problem will be solved.


问:
Is it necessary to create reducer for every action?
I'm new to React and Redux, I'm currently struggling with the concept when to create an action and when the action should call the reducer.

Let's say i want to do a post req to send my data to backend, i created an action and called axios in it, and then despatched the action. Do I need a Reducer Here..?

Any help is welcomed.

答: We create an action when we need to modify our state for example, get user information, modify, delete value, and for our state to be updated we need to use our reducer.</p>


问:
Python doesn't run properly on Visual Studio Code
I downloaded Visual Studio Code and installed Python following the instructions at https://code.visualstudio.com/docs/python/python-tutorial.

As I chose the Python extension in Visual Studio Code, an installation started, but it told me afterwards that the system install is not supported. Therefore I installed it with Homebrew.

First of all, I seem do not have the green 'run'-button displayed in the installation tutorial above. There I only can run code with right click and 'Run Selection/Line in Python Terminal'.

A simple print('Hello, World!') seems to run properly, but when I try to run a program with more than one line (i.e., more than one instruction) I get multiple error messages that I did not get while using Anaconda before.

For context: I am currently learning to program using Python and follow the book 'Automate the boring stuff with Python'.

The code I try to run is:

```<code>#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)
</code>```

For clarification:
Traceback (most recent call last): File "/Users/XXX/Desktop/Python Projects/Ex.py", line 7, in <module> import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip'
is the error I get.

I just want to use Visual Studio Code properly and I am really not sure why it isn't working or what I did wrong while installing it. (For example, why am I missing the green 'run'-button?!)

答:
For displaying a green play button, you have to install the Python extension in Visual Studio Code.

You have made an error. When I ran it I got it. You have to place sys.exit() after enter or on the next line:

```<code>sys.exit()
</code>```

Body:
I downloaded Visual Studio Code and installed Python following the instructions at https://code.visualstudio.com/docs/python/python-tutorial.

As I chose the Python extension in Visual Studio Code, an installation started, but it told me afterwards that the system install is not supported. Therefore I installed it with Homebrew.

First of all, I seem do not have the green 'run'-button displayed in the installation tutorial above. There I only can run code with right click and 'Run Selection/Line in Python Terminal'.

A simple print('Hello, World!') seems to run properly, but when I try to run a program with more than one line (i.e., more than one instruction) I get multiple error messages that I did not get while using Anaconda before.

For context: I am currently learning to program using Python and follow the book 'Automate the boring stuff with Python'.

The code I try to run is:

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}

import sys, pyperclip

if len(sys.argv) < 2:
    print('Usage: py mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

For clarification:
Traceback (most recent call last): File "/Users/XXX/Desktop/Python Projects/Ex.py", line 7, in <module> import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip'
is the error I get.

I just want to use Visual Studio Code properly and I am really not sure why it isn't working or what I did wrong while installing it. (For example, why am I missing the green 'run'-button?!)

Body:
For displaying a green play button, you have to install the Python extension in Visual Studio Code.

You have made an error. When I ran it I got it. You have to place sys.exit() after enter or on the next line:

sys.exit()


问:
importing 3d models into babylon when using react
I have been using babylonjs within a reactjs environment and so far it's very good. However i've been having trouble loading 3d models into the canvas. I've managed to load models into a non-react environment but not the react environment.

You can see a simple example of my current code below.

```<code>import React from 'react'
import {useEffect, useState, useRef} from 'react'

import path from 'path'

import * as BABYLON from '@babylonjs/core'
import 'babylonjs-loaders'
import SceneComponent from 'babylonjs-hook'; // ^^ point to file we created above or 'babylonjs-hook' NPM.
import SceneComp from '../components/babylonComponent'

const MyPage = () =>{
    var box = undefined
    var page = "landing"

    //this configures the scene
    const onSceneReady = (scene) =>{

        scene.clearColor = BABYLON.Color3.Black()

        //create and position free camera
        var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 5, -10), scene)

        //this targets the camera to scene of origin
        const canvas = scene.getEngine().getRenderingCanvas()

        //attatch camera to canvas
        camera.attachControl(canvas, true)

        //this creates a light aiming 0,1,0 - to the sky (non - mesh)
        var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,1,0), scene)

        //default intensity is 1, let's dim the light a small amount
        light.intensity = 0.7

        var myModel = BABYLON.SceneLoader.Append("./3dAssetts/untitled-scene-babylon/", "untitled-scene.babylon", scene, function(meshes){

        })
        return scene
    }

    //this funciton will run on every frame render
    const onRender = (scene) =>{

    }

    return(
        <div>
            <div style={canvasStyler}>
                <SceneComp antialias onSceneReady={onSceneReady} onRender={onRender} id='my-canvas' />
            </div>
        </div>
    )
}
const menuButton= {
    color:'black',
    textDecoration:'none',
  }

const canvasStyler ={
    position:'absolute',
    width:'100%',
    top:'0px',
    zIndex:'-1'
}

export default MyPage
</code>```

The canvas and the page loads fine but the 3d model does not and I am getting the following error.

Unable to load from ./3dAssetts/untitled-scene-babylon/untitled-scene.babylon: importScene of undefined from undefined version: undefined, exporter version: undefinedimportScene has failed JSON parse

Unable to work out what i'm doing wrong, anybody got any ideas?

答:
I have managed to get .babylon 3d model files imported using the following

I created an assets folder within the create-react-app /public folder.

I then put my .babylon file within this folder and called it in the import mesh code using the following.

```<code>var car = BABYLON.SceneLoader.Append("./assets/", "carModel.babylon", scene, function(meshes){
        })
</code>```

However i'm still having problems loading other object file types such as .gltf and .OBJ

for further info see the following useful link

https://www.html5gamedevs.com/topic/40304-trouble-loading-assets-in-react/

Body:
I have been using babylonjs within a reactjs environment and so far it's very good. However i've been having trouble loading 3d models into the canvas. I've managed to load models into a non-react environment but not the react environment.

You can see a simple example of my current code below.

import React from 'react'
import {useEffect, useState, useRef} from 'react'

import path from 'path'

import * as BABYLON from '@babylonjs/core'
import 'babylonjs-loaders'
import SceneComponent from 'babylonjs-hook'; // ^^ point to file we created above or 'babylonjs-hook' NPM.
import SceneComp from '../components/babylonComponent'

const MyPage = () =>{
    var box = undefined
    var page = "landing"

    //this configures the scene
    const onSceneReady = (scene) =>{

        scene.clearColor = BABYLON.Color3.Black()

        //create and position free camera
        var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 5, -10), scene)

        //this targets the camera to scene of origin
        const canvas = scene.getEngine().getRenderingCanvas()

        //attatch camera to canvas
        camera.attachControl(canvas, true)

        //this creates a light aiming 0,1,0 - to the sky (non - mesh)
        var light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,1,0), scene)

        //default intensity is 1, let's dim the light a small amount
        light.intensity = 0.7

        var myModel = BABYLON.SceneLoader.Append("./3dAssetts/untitled-scene-babylon/", "untitled-scene.babylon", scene, function(meshes){

        })
        return scene
    }

    //this funciton will run on every frame render
    const onRender = (scene) =>{

    }

    return(

                <SceneComp antialias onSceneReady={onSceneReady} onRender={onRender} id='my-canvas' />

    )
}
const menuButton= {
    color:'black',
    textDecoration:'none',
  }

const canvasStyler ={
    position:'absolute',
    width:'100%',
    top:'0px',
    zIndex:'-1'
}

export default MyPage

The canvas and the page loads fine but the 3d model does not and I am getting the following error.

Unable to load from ./3dAssetts/untitled-scene-babylon/untitled-scene.babylon: importScene of undefined from undefined version: undefined, exporter version: undefinedimportScene has failed JSON parse

Unable to work out what i'm doing wrong, anybody got any ideas?

Body:
I have managed to get .babylon 3d model files imported using the following

I created an assets folder within the create-react-app /public folder.

I then put my .babylon file within this folder and called it in the import mesh code using the following.

var car = BABYLON.SceneLoader.Append("./assets/", "carModel.babylon", scene, function(meshes){
        })

However i'm still having problems loading other object file types such as .gltf and .OBJ

for further info see the following useful link

https://www.html5gamedevs.com/topic/40304-trouble-loading-assets-in-react/


问:
Failed loading english.pickle with nltk.data.load
When trying to load the punkt tokenizer...

```<code>import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
</code>```

...a LookupError was raised:

```<code>> LookupError:
>     *********************************************************************
> Resource 'tokenizers/punkt/english.pickle' not found.  Please use the NLTK Downloader to obtain the resource: nltk.download().   Searched in:
>         - 'C:\\Users\\Martinos/nltk_data'
>         - 'C:\\nltk_data'
>         - 'D:\\nltk_data'
>         - 'E:\\nltk_data'
>         - 'E:\\Python26\\nltk_data'
>         - 'E:\\Python26\\lib\\nltk_data'
>         - 'C:\\Users\\Martinos\\AppData\\Roaming\\nltk_data'
>     **********************************************************************
</code>```

答:
I had similar issue when using an assigned folder for multiple downloads, and I had to append the data path manually:

single download, can be achived as followed (works)

```<code>import os as _os
from nltk.corpus import stopwords
from nltk import download as nltk_download

nltk_download('stopwords', download_dir=_os.path.join(get_project_root_path(), 'temp'), raise_on_error=True)

stop_words: list = stopwords.words('english')

</code>```

This code works, meaning that nltk remembers the download path passed in the download fuction. On the other nads if I download a subsequent package I get similar error as described by user:

Multiple downloads raise an error:

```<code>import os as _os

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

from nltk import download as nltk_download

nltk_download(['stopwords', 'punkt'], download_dir=_os.path.join(get_project_root_path(), 'temp'), raise_on_error=True)

print(stopwords.words('english'))
print(word_tokenize("I am trying to find the download path 99."))

</code>```

Error:

Resource punkt not found.
  Please use the NLTK Downloader to obtain the resource:

import nltk
  nltk.download('punkt')

Now if I append the ntlk data path with my download path, it works:

```<code>import os as _os

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

from nltk import download as nltk_download
from nltk.data import path as nltk_path

nltk_path.append( _os.path.join(get_project_root_path(), 'temp'))

nltk_download(['stopwords', 'punkt'], download_dir=_os.path.join(get_project_root_path(), 'temp'), raise_on_error=True)

print(stopwords.words('english'))
print(word_tokenize("I am trying to find the download path 99."))

</code>```

This works... Not sure why works in one case but not the other, but error message seems to imply that it doesn't check into the download folder the second time.
NB: using windows8.1/python3.7/nltk3.5

ContentLicense: CC BY-SA 3.0

Body:
When trying to load the punkt tokenizer...

import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')

...a LookupError was raised:

> LookupError:
>     *********************************************************************
> Resource 'tokenizers/punkt/english.pickle' not found.  Please use the NLTK Downloader to obtain the resource: nltk.download().   Searched in:
>         - 'C:\\Users\\Martinos/nltk_data'
>         - 'C:\\nltk_data'
>         - 'D:\\nltk_data'
>         - 'E:\\nltk_data'
>         - 'E:\\Python26\\nltk_data'
>         - 'E:\\Python26\\lib\\nltk_data'
>         - 'C:\\Users\\Martinos\\AppData\\Roaming\\nltk_data'
>     **********************************************************************

Body:
I had similar issue when using an assigned folder for multiple downloads, and I had to append the data path manually:

single download, can be achived as followed (works)

import os as _os
from nltk.corpus import stopwords
from nltk import download as nltk_download

nltk_download('stopwords', download_dir=_os.path.join(get_project_root_path(), 'temp'), raise_on_error=True)

stop_words: list = stopwords.words('english')

This code works, meaning that nltk remembers the download path passed in the download fuction. On the other nads if I download a subsequent package I get similar error as described by user:

Multiple downloads raise an error:

import os as _os

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

from nltk import download as nltk_download

nltk_download(['stopwords', 'punkt'], download_dir=_os.path.join(get_project_root_path(), 'temp'), raise_on_error=True)

print(stopwords.words('english'))
print(word_tokenize("I am trying to find the download path 99."))

Error:

Resource punkt not found.
  Please use the NLTK Downloader to obtain the resource:

import nltk
  nltk.download('punkt')

Now if I append the ntlk data path with my download path, it works:

import os as _os

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

from nltk import download as nltk_download
from nltk.data import path as nltk_path

nltk_path.append( _os.path.join(get_project_root_path(), 'temp'))

nltk_download(['stopwords', 'punkt'], download_dir=_os.path.join(get_project_root_path(), 'temp'), raise_on_error=True)

print(stopwords.words('english'))
print(word_tokenize("I am trying to find the download path 99."))

This works... Not sure why works in one case but not the other, but error message seems to imply that it doesn't check into the download folder the second time.
NB: using windows8.1/python3.7/nltk3.5


问:
woocommerce related products 2 column issues for mobile
Morning all,

I can't seem to get my Woocommerce related products to show in a 2 column, side by side format. When viewed on mobile device

You will see on this page that the related products are one after another, id like 2 side by side before a new row starts. https://ruggedasylum.com/product/solo-smoke-free-fire-pit/

Can someone assist me with how this is achieved, please?

I have tried this so far but it only makes smaller and continues to place 1 product on each line. It also moved the 'Related Products' title across to the left instead of centered.

```<code>@media screen and (max-width: 767px){
.woocommerce .related.products {
width: 50% !important;
}}
</code>```

I have gone onto W3 Schools and the CSS code they suggest for side by side in a responsive view doesn't seem to make a difference, less so than the code above.

please note I am happy with the way it is currently looking on the desktop version of the page.

I look forward to your input, a very grateful Ryan :)

答:
```<code>  @media screen and (max-width: 767px){

   .related.products ul.products li.product {
    flex: 0 1 auto;
    width: 45%;

  }
}
</code>```

that should do the trick but you might want to adjust %
for more info on flexbox, u can visit this https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
Morning all,

I can't seem to get my Woocommerce related products to show in a 2 column, side by side format. When viewed on mobile device

You will see on this page that the related products are one after another, id like 2 side by side before a new row starts. https://ruggedasylum.com/product/solo-smoke-free-fire-pit/

Can someone assist me with how this is achieved, please?

I have tried this so far but it only makes smaller and continues to place 1 product on each line. It also moved the 'Related Products' title across to the left instead of centered.

@media screen and (max-width: 767px){
.woocommerce .related.products {
width: 50% !important;
}}

I have gone onto W3 Schools and the CSS code they suggest for side by side in a responsive view doesn't seem to make a difference, less so than the code above.

please note I am happy with the way it is currently looking on the desktop version of the page.

I look forward to your input, a very grateful Ryan :)

Body:
  @media screen and (max-width: 767px){

   .related.products ul.products li.product {
    flex: 0 1 auto;
    width: 45%;

  }
}

that should do the trick but you might want to adjust %
for more info on flexbox, u can visit this https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
I am facing problem will installing webpack by npm install webpack?
npm ERR! Unexpected end of JSON input while parsing near '...pes/node":"^12.6.9","'

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Dubey\AppData\Roaming\npm-cache_logs\2020-05-30T08_45_02_091Z-debug.log

Please help me to get over this error.

答:
"Unexpected end of JSON input while parsing near" happens when you have a syntactically wrong package.json.

Try to copy paste your package.json file (all the file) here.

This tool will report any errors with your file if you have any.


问:
Remove spaces from right and left (TRIM) all selected columns
I have went through some documentations and as it states SELECT TRIM('') FROM something; can be used to trim strings.

I have SQL command to get the table:

```<code>"select NRO,SNAME,NAMEA,NAMEB,ADDRESS,POSTS,POSTN,POSTTP,COMPANY,COUNTRY,BID from COMPANY where ACTIVE = '1' AND NRO Like '7%'"
</code>```

So I have tried to use:

```<code>"select TRIM(NRO),TRIM(SNAME),TRIM(NAMEA),TRIM(NAMEB),TRIM(ADDRESS),TRIM(POSTS),TRIM(POSTN),TRIM(POSTTP),TRIM(COMPANY),TRIM(COUNTRY),TRIM(BID) from COMPANY where ACTIVE = '1' AND NRO Like '7%'"
</code>```

but this is throwing an error. What is the proper way of using TRIM in this case?
I need to remove spaces from left and right but leave them in between if there are any.

Error message:

Client Interface][LNA][PSQL][SQL Engine]Error in expression: TRIM (
  NRO )  ERROR [HY000] [PSQL][ODBC Client Interface][LNA][PSQL][SQL
  Engine][Data Record Manager]Invalid user-defined or scalar function.'

答:
You can use LTRIM and RTRIM functions which removes starting and ending spaces for the SQL Server prior to 2017.

So, your query becomes:

```<code> select RTRIM(LTRIM(NRO)),
    RTRIM(LTRIM(SNAME),
    RTRIM(LTRIM(NAMEA)),
    RTRIM(LTRIM(NAMEB)),
    RTRIM(LTRIM(ADDRESS)),
    RTRIM(LTRIM(POSTS)),
    RTRIM(LTRIM(POSTN)),
    RTRIM(LTRIM(POSTTP)),
    RTRIM(LTRIM(COMPANY)),
    RTRIM(LTRIM(COUNTRY)),
    RTRIM(LTRIM(BID))
from COMPANY where ACTIVE = '1' AND NRO Like '7%'
</code>```

For the SQL Server 2017 and later you can use TRIM function as Dale K suggested.

Body:
I have went through some documentations and as it states SELECT TRIM('') FROM something; can be used to trim strings.

I have SQL command to get the table:

"select NRO,SNAME,NAMEA,NAMEB,ADDRESS,POSTS,POSTN,POSTTP,COMPANY,COUNTRY,BID from COMPANY where ACTIVE = '1' AND NRO Like '7%'"

So I have tried to use:

"select TRIM(NRO),TRIM(SNAME),TRIM(NAMEA),TRIM(NAMEB),TRIM(ADDRESS),TRIM(POSTS),TRIM(POSTN),TRIM(POSTTP),TRIM(COMPANY),TRIM(COUNTRY),TRIM(BID) from COMPANY where ACTIVE = '1' AND NRO Like '7%'"

but this is throwing an error. What is the proper way of using TRIM in this case?
I need to remove spaces from left and right but leave them in between if there are any.

Error message:

Client Interface][LNA][PSQL][SQL Engine]Error in expression: TRIM (
  NRO )  ERROR [HY000] [PSQL][ODBC Client Interface][LNA][PSQL][SQL
  Engine][Data Record Manager]Invalid user-defined or scalar function.'

Body:
You can use LTRIM and RTRIM functions which removes starting and ending spaces for the SQL Server prior to 2017.

So, your query becomes:

 select RTRIM(LTRIM(NRO)),
    RTRIM(LTRIM(SNAME),
    RTRIM(LTRIM(NAMEA)),
    RTRIM(LTRIM(NAMEB)),
    RTRIM(LTRIM(ADDRESS)),
    RTRIM(LTRIM(POSTS)),
    RTRIM(LTRIM(POSTN)),
    RTRIM(LTRIM(POSTTP)),
    RTRIM(LTRIM(COMPANY)),
    RTRIM(LTRIM(COUNTRY)),
    RTRIM(LTRIM(BID))
from COMPANY where ACTIVE = '1' AND NRO Like '7%'

For the SQL Server 2017 and later you can use TRIM function as Dale K suggested.


问:
How to check the values of checkpoints?
How can we check that the checkpoint is restored correctly and how we can check the values of the weights in checkpoints. I am working in tensorflow 2.</p>

答: assuming you have a tf.keras.Model object called model, you can call model.layers[0].get_weights() to get the weights of the first layer.

Title: How to check the values of checkpoints?


问:
Where in object file does the code of function "main" starts?
I have an object file of a C program which prints hello world, just for the question.
I am trying to understand using readelf utility or gdb or hexedit(I can't figure which tool is a correct one) where in the file does the code of function "main" starts.

I know using readelf that symbol _start & main occurs and the address where it is mapped in a virtual memory. Moreover, I also know what the size of .text section and the of coruse where entry point specified, i.e the address which the same of text section.

The question is - Where in the file does the code of function "main" starts? I tought that is the entry point and the offset of the text section but how I understand it the sections data, bss, rodata should be ran before main and it appears after section text in readelf.

Also I tought we should sum the size all the lines till main in symbol table, but I am not sure at all if it is correct.

Additional question which follow up this one is if I want to replace main function with NOP instrcutres or plant one ret instruction in my object file. how can I know the offset where I can do it using hexedit.

答:
So, let's go through it step by step.

Start with this C file:

```<code>#include <stdio.h>

void printit()
{
    puts("Hello world!");
}

int main(void)
{
    printit();
    return 0;
}
</code>```

As the comments look like you are on x86, compile it as 32-bit non-PIE executable like this:

```<code>$ gcc -m32 -no-pie  -o test test.c
</code>```

The -m32 option is needed, because I am working at a x86-64 machine. As you already know, you can get the virtual memory address of main using readelf, objdump or nm, for example like this:

```<code>$ nm test | grep -w main
0804918d T main
</code>```

Obviously, 804918d can not be an offset in the file that is just 15 kB big. You need to find the mapping between virtual memory addresses and file offsets. In a typical ELF file, the mapping is included twice. Once in a detailed form for linkers (as object files are also ELF files) and debuggers, and a second time in a condensed form that is used by the kernel for loading programs. The detailed form is the list of sections, consisting of section headers, and you can view it like this (the output is shortened a bit, to make the answer more readable):

```<code>$ readelf --section-headers test
There are 29 section headers, starting at offset 0x3748:

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
[...]
  [11] .init             PROGBITS        08049000 001000 000020 00  AX  0   0  4
  [12] .plt              PROGBITS        08049020 001020 000030 04  AX  0   0 16
  [13] .text             PROGBITS        08049050 001050 0001c1 00  AX  0   0 16
  [14] .fini             PROGBITS        08049214 001214 000014 00  AX  0   0  4
  [15] .rodata           PROGBITS        0804a000 002000 000015 00   A  0   0  4
[...]
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
  L (link order), O (extra OS processing required), G (group), T (TLS),
  C (compressed), x (unknown), o (OS specific), E (exclude),
  p (processor specific)

</code>```

Here you find that the .text section starts at (virtual) address 08049050 and has a size of 1c1 bytes, so it ends at address 08049211. The address of main, 804918d is in this range, so you know main is a member of the text section. If you subtract the base of the text section from the address of main, you find that main is 13d bytes into the text section. The section listing also contains the file offset where the data for the text section starts. It's 1050, so the first byte of main is at offset 0x1050 + 0x13d == 0x118d.

You can do the same calculation using program headers:

```<code>$ readelf --program-headers test
[...]
Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x08048034 0x08048034 0x00160 0x00160 R   0x4
  INTERP         0x000194 0x08048194 0x08048194 0x00013 0x00013 R   0x1
      [Requesting program interpreter: /lib/ld-linux.so.2]
  LOAD           0x000000 0x08048000 0x08048000 0x002e8 0x002e8 R   0x1000
  LOAD           0x001000 0x08049000 0x08049000 0x00228 0x00228 R E 0x1000
  LOAD           0x002000 0x0804a000 0x0804a000 0x0019c 0x0019c R   0x1000
  LOAD           0x002f0c 0x0804bf0c 0x0804bf0c 0x00110 0x00114 RW  0x1000
[...]
</code>```

The second load line tells you that the area 08049000 (VirtAddr) to 08049228 (VirtAddr + MemSiz) is readable and executable, and loaded from offset 1000 in the file. So again you can calculate that the address of main is 18d bytes into this load area, so it has to reside at offset 0x118d inside the executable. Let's test that:

```<code>$ ./test
Hello world!
$ echo -ne '\xc3' | dd of=test conv=notrunc bs=1 count=1 seek=$((0x118d))
1+0 records in
1+0 records out
1 byte copied, 0.0116672 s, 0.1 kB/s
$ ./test
$
</code>```

Overwriting the first byte of main with 0xc3, the opcode for return (near) on x86, causes the program to not output anything anymore.

Body:
So, let's go through it step by step.

Start with this C file:

#include <stdio.h>

void printit()
{
    puts("Hello world!");
}

int main(void)
{
    printit();
    return 0;
}

As the comments look like you are on x86, compile it as 32-bit non-PIE executable like this:

$ gcc -m32 -no-pie  -o test test.c

The -m32 option is needed, because I am working at a x86-64 machine. As you already know, you can get the virtual memory address of main using readelf, objdump or nm, for example like this:

$ nm test | grep -w main
0804918d T main

Obviously, 804918d can not be an offset in the file that is just 15 kB big. You need to find the mapping between virtual memory addresses and file offsets. In a typical ELF file, the mapping is included twice. Once in a detailed form for linkers (as object files are also ELF files) and debuggers, and a second time in a condensed form that is used by the kernel for loading programs. The detailed form is the list of sections, consisting of section headers, and you can view it like this (the output is shortened a bit, to make the answer more readable):

$ readelf --section-headers test
There are 29 section headers, starting at offset 0x3748:

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
[...]
  [11] .init             PROGBITS        08049000 001000 000020 00  AX  0   0  4
  [12] .plt              PROGBITS        08049020 001020 000030 04  AX  0   0 16
  [13] .text             PROGBITS        08049050 001050 0001c1 00  AX  0   0 16
  [14] .fini             PROGBITS        08049214 001214 000014 00  AX  0   0  4
  [15] .rodata           PROGBITS        0804a000 002000 000015 00   A  0   0  4
[...]
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
  L (link order), O (extra OS processing required), G (group), T (TLS),
  C (compressed), x (unknown), o (OS specific), E (exclude),
  p (processor specific)

Here you find that the .text section starts at (virtual) address 08049050 and has a size of 1c1 bytes, so it ends at address 08049211. The address of main, 804918d is in this range, so you know main is a member of the text section. If you subtract the base of the text section from the address of main, you find that main is 13d bytes into the text section. The section listing also contains the file offset where the data for the text section starts. It's 1050, so the first byte of main is at offset 0x1050 + 0x13d == 0x118d.

You can do the same calculation using program headers:

$ readelf --program-headers test
[...]
Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x08048034 0x08048034 0x00160 0x00160 R   0x4
  INTERP         0x000194 0x08048194 0x08048194 0x00013 0x00013 R   0x1
      [Requesting program interpreter: /lib/ld-linux.so.2]
  LOAD           0x000000 0x08048000 0x08048000 0x002e8 0x002e8 R   0x1000
  LOAD           0x001000 0x08049000 0x08049000 0x00228 0x00228 R E 0x1000
  LOAD           0x002000 0x0804a000 0x0804a000 0x0019c 0x0019c R   0x1000
  LOAD           0x002f0c 0x0804bf0c 0x0804bf0c 0x00110 0x00114 RW  0x1000
[...]

The second load line tells you that the area 08049000 (VirtAddr) to 08049228 (VirtAddr + MemSiz) is readable and executable, and loaded from offset 1000 in the file. So again you can calculate that the address of main is 18d bytes into this load area, so it has to reside at offset 0x118d inside the executable. Let's test that:

$ ./test
Hello world!
$ echo -ne '\xc3' | dd of=test conv=notrunc bs=1 count=1 seek=$((0x118d))
1+0 records in
1+0 records out
1 byte copied, 0.0116672 s, 0.1 kB/s
$ ./test
$

Overwriting the first byte of main with 0xc3, the opcode for return (near) on x86, causes the program to not output anything anymore.


问:
Why I am getting a different sum if invoked with different number of threads in parallel?
This is just an extension of the following question I asked:

Why can't I reach 100% CPU utilization with my parallel tasks code?

```<code> private static int SumParallel()
        {
            var intList = Enumerable.Range(1, 1000_000_000);
            int count = intList.Count();
            int threads = 6;
            List<Task<int>> l = new List<Task<int>>(threads);
            for(int i = 1; i <= threads; i++)
            {
                int skip = ((i - 1) * count) / threads;
                int take = count / threads;
                l.Add(GetSum(intList, skip, take));
            }
            Task.WaitAll(l.ToArray());
            return l.Sum(t => t.Result);
        }

private static Task<int> GetSum(IEnumerable<int> list, int skip, int take)
        {
            return Task.Run(() =>
             {
                 int temp = 0;
                 foreach(int n in list.Skip(skip).Take(take))
                 {
                     if (n % 2 == 0)
                         temp -= n;
                     else
                     {
                         temp += n;
                     }
                 }

                 Console.WriteLine(temp + " " + Task.CurrentId);
                 return temp;
             });
        }
</code>```

If I modify the number of tasks working in parallel, I get a different sum.

Why is this so?

答:
It's because of this line:

```<code>int skip = ((i - 1) * count) / threads;
int take = count / threads;
</code>```

consider threads = 3 and count = 10
It can't cover all of your list. Based on thread count you get different roundings in take and skip and sometimes they can't cover all items in the list.

You maybe should change it this way:

```<code>for(int i = 1; i <= threads; i++)
{
    int skip = ((i - 1) * count) / threads;
    int take = count / threads;

    if(i == threads)
        take = threads - skip;

    l.Add(GetSum(intList, skip, take));
}
</code>```

Body:
This is just an extension of the following question I asked:

Why can't I reach 100% CPU utilization with my parallel tasks code?

 private static int SumParallel()
        {
            var intList = Enumerable.Range(1, 1000_000_000);
            int count = intList.Count();
            int threads = 6;
            List<Task<int>> l = new List<Task<int>>(threads);
            for(int i = 1; i <= threads; i++)
            {
                int skip = ((i - 1) * count) / threads;
                int take = count / threads;
                l.Add(GetSum(intList, skip, take));
            }
            Task.WaitAll(l.ToArray());
            return l.Sum(t => t.Result);
        }

private static Task<int> GetSum(IEnumerable<int> list, int skip, int take)
        {
            return Task.Run(() =>
             {
                 int temp = 0;
                 foreach(int n in list.Skip(skip).Take(take))
                 {
                     if (n % 2 == 0)
                         temp -= n;
                     else
                     {
                         temp += n;
                     }
                 }

                 Console.WriteLine(temp + " " + Task.CurrentId);
                 return temp;
             });
        }

If I modify the number of tasks working in parallel, I get a different sum.

Why is this so?

Body:
It's because of this line:

int skip = ((i - 1) * count) / threads;
int take = count / threads;

consider threads = 3 and count = 10
It can't cover all of your list. Based on thread count you get different roundings in take and skip and sometimes they can't cover all items in the list.

You maybe should change it this way:

for(int i = 1; i <= threads; i++)
{
    int skip = ((i - 1) * count) / threads;
    int take = count / threads;

    if(i == threads)
        take = threads - skip;

    l.Add(GetSum(intList, skip, take));
}


问:
Perl Regex: Need help on a way to split string into groups matching a pattern
I need to split this string to an array:

```<code>$string = "9583526578','9583636523','9673522574','9183556528','9983023378";
</code>```

Here's how I want my array to look like after splitting:

```<code>@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]
</code>```

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

答:
This should be a reasonably close fit to your desired behavior:</p>

```<code>my @foo;
push @foo, [ $1, $2 // () ] while $string =~ / (\d+) (?: \D+ (\d+) ) ? /gx;
</code>```

Body:
I need to split this string to an array:

$string = "9583526578','9583636523','9673522574','9183556528','9983023378";

Here's how I want my array to look like after splitting:

@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

Body:
This should be a reasonably close fit to your desired behavior:

my @foo;
push @foo, [ $1, $2 // () ] while $string =~ / (\d+) (?: \D+ (\d+) ) ? /gx;


问:
How to run test perl script as cgi script with httpd?
I'm trying to follow this tutorial and run sample script under cgi.

Below are steps which I did:

1) Made sample script

```<code>$ cat > test.pl <<EOF
> #!/usr/bin/perl
> print "Content-type: text/html\n\n";
> print "Hello, World.";
EOF
</code>```

2) run httpd docker container and mounted created script as volume in cgi-bin directory:

```<code>$ docker run --name cgi_test --rm -p 3000:80 -v $(pwd)/test.pl:/usr/local/apache2/cgi-bin/test.pl httpd
</code>```

3) check if CGI module is enabled:

```<code>$ docker exec -it cgi_test cat /usr/local/apache2/conf/httpd.conf | grep modules/mod_cgid.so
    #LoadModule cgi_module modules/mod_cgid.so
</code>```

CGI module was turned out so I enabled it:

```<code>$ docker exec -it cgi_test sed -i 's,#\(LoadModule cgid_module modules/mod_cgid.so\),\1,g' /usr/local/apache2/conf/httpd.conf

</code>```

4) Checked ScriptAlias directive and enabling of alias_module :

```<code>$ docker exec -it cgi_test cat /usr/local/apache2/conf/httpd.conf | grep "ScriptAlias /cgi-bin/"
    ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/"
$ docker exec -it cgi_test httpd -M | grep -e cgid -e alias
 cgid_module (shared)
 alias_module (shared)

</code>```

It was ok

5) Checked exec permissions:

```<code>$ docker exec -it cgi_test ls -la /usr/local/apache2/cgi-bin/test.pl
-rwxr-xr-x 1 1000 1000 76 Mar 20 12:41 /usr/local/apache2/cgi-bin/test.pl
</code>```

It was ok

6) Restarted httpd in docker container:

```<code>$ docker kill --signal="USR1" cgi_test

</code>```

But when I to to http://localhost:3000/cgi-bin/test.pl I see 503 Service Unavailable and this error in log:

```<code>[Wed Mar 20 19:03:02.323430 2019] [cgid:error] [pid 1446:tid 139952364902144] (22)Invalid argument: [client 172.17.0.1:34328] AH01257: unable to connect to cgi daemon after multiple tries: /usr/local/apache2/cgi-bin/test.pl
</code>```

What else I need to do to run script ?

答:
To run a script under CGI you don't need to change any file in the official httpd Docker image.

Make sure that your script is executable with a chmod +x test.pl and pass to the server program the -c option with the configuration directive to load the CGI module, as described in the following command:

```<code>docker run \
  -it \
  --rm \
  -p 127.0.0.1:8080:80 \
  -v $(pwd)/test.pl:/usr/local/apache2/cgi-bin/test.pl \
  httpd:alpine \
  httpd-foreground -c "LoadModule cgid_module modules/mod_cgid.so"
</code>```

Some explanations:

Alpine variant image is used because it's smaller than the default Debian based image and it's more than enough for our purposes

httpd-foreground script is available in all official httpd images and it allows to execute Apache HTTP Server in foreground mode (it's equivalent to httpd -D FOREGROUND)

publish option -p contains also the loopback IP address to prevent access to this test server from the outside

Body:
I'm trying to follow this tutorial and run sample script under cgi.

Below are steps which I did:

1) Made sample script

$ cat > test.pl <<EOF
> #!/usr/bin/perl
> print "Content-type: text/html\n\n";
> print "Hello, World.";
EOF

2) run httpd docker container and mounted created script as volume in cgi-bin directory:

$ docker run --name cgi_test --rm -p 3000:80 -v $(pwd)/test.pl:/usr/local/apache2/cgi-bin/test.pl httpd

3) check if CGI module is enabled:

$ docker exec -it cgi_test cat /usr/local/apache2/conf/httpd.conf | grep modules/mod_cgid.so
    #LoadModule cgi_module modules/mod_cgid.so

CGI module was turned out so I enabled it:

$ docker exec -it cgi_test sed -i 's,#\(LoadModule cgid_module modules/mod_cgid.so\),\1,g' /usr/local/apache2/conf/httpd.conf

4) Checked ScriptAlias directive and enabling of alias_module :

$ docker exec -it cgi_test cat /usr/local/apache2/conf/httpd.conf | grep "ScriptAlias /cgi-bin/"
    ScriptAlias /cgi-bin/ "/usr/local/apache2/cgi-bin/"
$ docker exec -it cgi_test httpd -M | grep -e cgid -e alias
 cgid_module (shared)
 alias_module (shared)

It was ok

5) Checked exec permissions:

$ docker exec -it cgi_test ls -la /usr/local/apache2/cgi-bin/test.pl
-rwxr-xr-x 1 1000 1000 76 Mar 20 12:41 /usr/local/apache2/cgi-bin/test.pl

It was ok

6) Restarted httpd in docker container:

$ docker kill --signal="USR1" cgi_test

But when I to to http://localhost:3000/cgi-bin/test.pl I see 503 Service Unavailable and this error in log:

[Wed Mar 20 19:03:02.323430 2019] [cgid:error] [pid 1446:tid 139952364902144] (22)Invalid argument: [client 172.17.0.1:34328] AH01257: unable to connect to cgi daemon after multiple tries: /usr/local/apache2/cgi-bin/test.pl

What else I need to do to run script ?

Body:
To run a script under CGI you don't need to change any file in the official httpd Docker image.

Make sure that your script is executable with a chmod +x test.pl and pass to the server program the -c option with the configuration directive to load the CGI module, as described in the following command:

docker run \
  -it \
  --rm \
  -p 127.0.0.1:8080:80 \
  -v $(pwd)/test.pl:/usr/local/apache2/cgi-bin/test.pl \
  httpd:alpine \
  httpd-foreground -c "LoadModule cgid_module modules/mod_cgid.so"

Some explanations:

Alpine variant image is used because it's smaller than the default Debian based image and it's more than enough for our purposes

httpd-foreground script is available in all official httpd images and it allows to execute Apache HTTP Server in foreground mode (it's equivalent to httpd -D FOREGROUND)

publish option -p contains also the loopback IP address to prevent access to this test server from the outside


问:
Compare API response against itself
I am trying to:

Poll a public API every 5 seconds

Store the resulting JSON in a variable

Store the next query to this same API in a second variable

Compare the first variable to the second

Print the second variable if it is different from the first

Else: Print the phrase: 'The objects are the same' if they haven't changed

Unfortunately, the comparison part appears to fail. I am realizing that this implementation is probably lacking the appropriate variable scoping but I can't put my finger on it. Any advice would be highly appreciated.

```<code>  data: {
    chatters: {
        viewers: {
        },
    },
  },
};

//prints out pretty JSON
function prettyJSON(obj) {
  console.log(JSON.stringify(obj, null, 2));
}

// Gets Users from Twitch API endpoint via axios request
const getUsers = async () => {
  try {
    return await axios.get("http://tmi.twitch.tv/group/user/sixteenbitninja/chatters");
  } catch (error) {
    console.error(error);
  }
};

//Intended to display
const displayViewers = async (previousResponse) => {
  const usersInChannel = await getUsers();
  if (usersInChannel.data.chatters.viewers === previousResponse){
      console.log("The objects are the same");
  } else {
      if (usersInChannel.data.chatters) {
            prettyJSON(usersInChannel.data.chatters.viewers);
            const previousResponse = usersInChannel.data.chatters.viewers;
            console.log(previousResponse);
            intervalFunction(previousResponse);
        }
   }

};

// polls display function every 5 seconds
const interval = setInterval(function () {
    // Calls Display Function
    displayViewers()
}, 5000);```
```

答:
The issue is that you are using equality operator === on objects. two objects are equal if they have the same reference. While you want to know if they are identical. Check this:

console.log({} === {})```
</div>
</div>
</p>

<p>For your usecase you might want to store stringified version of the <code>previousResponse</code> and compare it with stringified version of the new object (<code>usersInChannel.data.chatters.viewers</code>) like:</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>    console.log(JSON.stringify({}) === JSON.stringify({}))</code>```

Note: There can be issues with this approach too, if the order of property changes in the response. In which case, you'd have to check individual properties within the response objects.

Title: Compare API response against itself

Body:
I am trying to:

Poll a public API every 5 seconds

Store the resulting JSON in a variable

Store the next query to this same API in a second variable

Compare the first variable to the second

Print the second variable if it is different from the first

Else: Print the phrase: 'The objects are the same' if they haven't changed

Unfortunately, the comparison part appears to fail. I am realizing that this implementation is probably lacking the appropriate variable scoping but I can't put my finger on it. Any advice would be highly appreciated.

  data: {
    chatters: {
        viewers: {
        },
    },
  },
};

//prints out pretty JSON
function prettyJSON(obj) {
  console.log(JSON.stringify(obj, null, 2));
}

// Gets Users from Twitch API endpoint via axios request
const getUsers = async () => {
  try {
    return await axios.get("http://tmi.twitch.tv/group/user/sixteenbitninja/chatters");
  } catch (error) {
    console.error(error);
  }
};

//Intended to display
const displayViewers = async (previousResponse) => {
  const usersInChannel = await getUsers();
  if (usersInChannel.data.chatters.viewers === previousResponse){
      console.log("The objects are the same");
  } else {
      if (usersInChannel.data.chatters) {
            prettyJSON(usersInChannel.data.chatters.viewers);
            const previousResponse = usersInChannel.data.chatters.viewers;
            console.log(previousResponse);
            intervalFunction(previousResponse);
        }
   }

};

// polls display function every 5 seconds
const interval = setInterval(function () {
    // Calls Display Function
    displayViewers()
}, 5000);```

Body:
The issue is that you are using equality operator === on objects. two objects are equal if they have the same reference. While you want to know if they are identical. Check this:

console.log({} === {})

For your usecase you might want to store stringified version of the previousResponse and compare it with stringified version of the new object (usersInChannel.data.chatters.viewers) like:

    console.log(JSON.stringify({}) === JSON.stringify({}))

Note: There can be issues with this approach too, if the order of property changes in the response. In which case, you'd have to check individual properties within the response objects.


问:
How to Enable deprecate methods warning in gradle
When I build a project with gradle I'm unable to see any warning about deprecated methods, only the errors are shown.

How do I have to set build.gradle to show also all deprecations warning(without prevent the build completion)?

答:
Add this line to gradle.properties:

```<code>org.gradle.warning.mode=all
</code>```

Source: https://docs.gradle.org/6.1/userguide/build_environment.html#sec:gradle_configuration_properties

Body:
Add this line to gradle.properties:

org.gradle.warning.mode=all

Source: https://docs.gradle.org/6.1/userguide/build_environment.html#sec:gradle_configuration_properties


问:
How to drop some parts of a text in a column
I know that this question must have been addressed but I don't seem to find the answer.
I have a column in my dataframe and I want to drop some parts of a string from a specified character. The string is 'WD-2020-04-115R:WD-2020-03-111'. I want everything gone starting from R such that I remain with WD-2020-04-115. For any string in my column without an R in it, I want to keep it</p>

Body:
Try:

data_array = ['WD-2020-04-115R:WD-2020-03-111', 'WD-2020-05-10582', 'WD-2020-05-10575', 'WD-2020-05-10576','WD-2020-05-10574', 'WD-2020-05-10571R:WD-2020-03-10563', 'WD-2020-05-10577', 'WD-2020-04-10571R:WD-2020-03-10562']
for data in data_array:
    t = data.find('R')
    if t < 0:
        dropped = data
    else:
        dropped = data[:t]
    print(dropped)
    #You can either print, append to an array or write to a file


问:
an added value of array of request disappears in Laravel Controller
the user id is existed Before doing create. so it causes an error in the first one.
I made it the other way. the second one below works correctly.
I would like to know why the first one is wrong and it's gone.

```<code>//Error
    public function store(ContactRequest $request)
    {
        $request->user_id = $request->user()->id;
        Log::debug($request->user()->id);
        Log::debug($request);
        Contact::create($request->all());
    }
</code>```

//OK

```<code>    public function store(ContactRequest $request,Contact $contact)
    {

        $request->user_id = $request->user()->id;

        $contact->title = $request->title;
        $contact->body = $request->body;
        $contact->user_id = $request->user()->id;
        $contact->save();
    }
</code>```

```<code>the log of the first one is here.
What happened to the user_id!?
</code>```

```<code>[2020-05-30 15:59:10] local.DEBUG: 59
[2020-05-30 15:59:10] local.DEBUG: array (
  '_token' => 'gGWuxW6C2JRSCYDuCAC9HauynGclKQEQB7qUh6Rw',
  'title' => 'TITLE',
  'body' => 'MESSAGE',
  'action' => 'SEND',
)
</code>```

Contact is model class.
ContactRequest is here.

```<code>class ContactRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'title' => 'required|max:100',
            'body' => 'required|max:1000'
        ];
    }
    public function attributes() {
        return [
            'title' => 'title',
            'body' => 'CONTENTS'
        ];
    }
}
</code>```

答:
What if you do this:

```<code>Auth::user() - >contact($request->all()) - >save() ;
</code>```

Or also as an experiment:

```<code>$contact = new Contact($request->all()) ;
$contact->user_id = Auth::user() - >id;
$contact->save() ;
</code>```

Actually the second snippet will surely work. The first one I did not test though it looks nice. :)

Body:
the user id is existed Before doing create. so it causes an error in the first one.
I made it the other way. the second one below works correctly.
I would like to know why the first one is wrong and it's gone.

//Error
    public function store(ContactRequest $request)
    {
        $request->user_id = $request->user()->id;
        Log::debug($request->user()->id);
        Log::debug($request);
        Contact::create($request->all());
    }

//OK

    public function store(ContactRequest $request,Contact $contact)
    {

        $request->user_id = $request->user()->id;

        $contact->title = $request->title;
        $contact->body = $request->body;
        $contact->user_id = $request->user()->id;
        $contact->save();
    }

the log of the first one is here.
What happened to the user_id!?

[2020-05-30 15:59:10] local.DEBUG: 59
[2020-05-30 15:59:10] local.DEBUG: array (
  '_token' => 'gGWuxW6C2JRSCYDuCAC9HauynGclKQEQB7qUh6Rw',
  'title' => 'TITLE',
  'body' => 'MESSAGE',
  'action' => 'SEND',
)

Contact is model class.
ContactRequest is here.

class ContactRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'title' => 'required|max:100',
            'body' => 'required|max:1000'
        ];
    }
    public function attributes() {
        return [
            'title' => 'title',
            'body' => 'CONTENTS'
        ];
    }
}

Body:
What if you do this:

Auth::user() - >contact($request->all()) - >save() ;

Or also as an experiment:

$contact = new Contact($request->all()) ;
$contact->user_id = Auth::user() - >id;
$contact->save() ;

Actually the second snippet will surely work. The first one I did not test though it looks nice. :)


问:
laravel 7 edit old value not selected form
hello i use this code for select category in edit form and it is not work!
this line not work

```<code><option value="{{$category->id}}" {{ old('parent')  ? 'selected' : '' }} >
</code>```

and use this but two code not worked!

```<code> {{ in_array($category->id ,$category->child()->pluck('id')->toArray()) ? 'selected': ''}}
</code>```

my code is

```<code> <option value="0"{{$category->parent == '0' ? 'selected': ''}}>دسته اصلی</option>
@foreach(\App\Category::all() as $category)
<option value="{{$category->id}}"  {{ in_array($category->id ,$category->child()->pluck('id')->toArray()) ? 'selected': ''}}>
 @if($category->parent== 0)
 {{$category->name}}
 @else
-- {{$category->name}}
 @endif
</option>
@endforeach
</code>```

and my model category this

```<code>  public function child()
{
    return $this->hasMany(Category::class, 'parent', 'id');
}

public function get_parent()
{
    return $this->hasOne(Category::class,'id','parent');
}
</code>```

答:
You need to do it this way

```<code><option value="{{ $category->id }}" {{ old('parent') == $category->id ? 'selected' : '' }} >
</code>```

But suppose if you have all categories and a category with edit record also, means you have come to edit page with a single category and you want that to be selected by default then.

```<code><option value="{{ $category->id }}" @isset($cat) {{ $cat->id == $category->id ? 'selected' : '' }} @endisset >
</code>```

In this case $cat is a single category for edit and $category is your looping through all categories in dropdown.

UPDATED CODE

```<code> <select name="parent" id="parent">
     <option value="0"{{$category->parent == '0' ? 'selected': ''}}>دسته اصلی</option>
     @foreach(\App\Category::all() as $category_loop)
        <option value="{{$category->id}}"
          @isset($category) {{ $category->parent == $category_loop->id ? 'selected' : '' }} @endisset>
          @if($category_loop->parent== 0)
             {{$category_loop->name}}
          @else
          -- {{$category_loop->name}}
          @endif
        </option>
     @endforeach
 </select>
</code>```

Body:
hello i use this code for select category in edit form and it is not work!
this line not work

<option value="{{$category->id}}" {{ old('parent')  ? 'selected' : '' }} >

and use this but two code not worked!

 {{ in_array($category->id ,$category->child()->pluck('id')->toArray()) ? 'selected': ''}}

my code is

 <option value="0"{{$category->parent == '0' ? 'selected': ''}}>دسته اصلی</option>
@foreach(\App\Category::all() as $category)
<option value="{{$category->id}}"  {{ in_array($category->id ,$category->child()->pluck('id')->toArray()) ? 'selected': ''}}>
 @if($category->parent== 0)
 {{$category->name}}
 @else
-- {{$category->name}}
 @endif
</option>
@endforeach

and my model category this

  public function child()
{
    return $this->hasMany(Category::class, 'parent', 'id');
}

public function get_parent()
{
    return $this->hasOne(Category::class,'id','parent');
}

Body:
You need to do it this way

<option value="{{ $category->id }}" {{ old('parent') == $category->id ? 'selected' : '' }} >

But suppose if you have all categories and a category with edit record also, means you have come to edit page with a single category and you want that to be selected by default then.

<option value="{{ $category->id }}" @isset($cat) {{ $cat->id == $category->id ? 'selected' : '' }} @endisset >

In this case $cat is a single category for edit and $category is your looping through all categories in dropdown.

UPDATED CODE

 <select name="parent" id="parent">
     <option value="0"{{$category->parent == '0' ? 'selected': ''}}>دسته اصلی</option>
     @foreach(\App\Category::all() as $category_loop)
        <option value="{{$category->id}}"
          @isset($category) {{ $category->parent == $category_loop->id ? 'selected' : '' }} @endisset>
          @if($category_loop->parent== 0)
             {{$category_loop->name}}
          @else
          -- {{$category_loop->name}}
          @endif
        </option>
     @endforeach
 </select>


问:
C++ Cross Platform MP3 Decoder?
I have searched high and low, and cannot find any decent MP3 decoders =/

I need one that will compile under gcc/linux.

The closest thing i could find was libmad, which has no documentation at all, and the only example I could find was the one on their home page, which is really complicated.

Does anyone know where I can find one?

答:
Have you looked at Lame?

Looking at its command-line page, I can see at least a few options that look promising, such as --decode and --mp3input. That would hint that the underlying library has the ability to do what you need, I would imagine. Whether or not it has nice, well-encapsulated C++ functions for decoding mp3s is another story.

As correctly noted in the comments, you should carefully examine the licensing and patent agreements.

Title: C++ Cross Platform MP3 Decoder?


问:
Handshake error in client (OS Error: TLSV1_ALERT_PROTOCOL_VERSION(tls_record.cc:586) in flutter app when trying to do a post/get request
I have Node.js rest APIs, which I am using in my flutter app to do requests accordingly, but when I tried to do the same I am getting an exception that is:

```<code>Exception has occurred.
HandshakeException (HandshakeException: Handshake error in client (OS Error: TLSV1_ALERT_PROTOCOL_VERSION(tls_record.cc:586)))
</code>```

I am doing the request with the http client like:

```<code>import 'package:http/http.dart' as http;
const _baseUrl = https://domain.in/api/

http.Response response = await http.post(
      _baseUrl + 'user/login',
      body: json.encode(_authData),
      headers: {'Content-Type': 'application/json'},
    ).catchError((onError){
      print(onError);
    });
</code>```

It was working with http but it is not working with https.

答:
This is a server side error because of your nginx ssl configuration.

ssl_protocols line in your /etc/nginx/nginx.conf file should look like this :

```<code>ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
</code>```

If you use extra file for your ssl settings in /etc/nginx/sites-enabled/default or yourdomain file in same path, for example a file called ssl-params.conf, add ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; line in this file too.

This is part of my /etc/nginx/sites-enabled/default file:

```<code>server {
    #Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name domain.net www.domain.net;

    # Use the Let's Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/domain.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.net/privkey.pem;

    #Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf; // <- !pay attention this line

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:5000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}
</code>```

This is my /etc/nginx/snippets/ssl-params.conf file:

```<code>ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ciphers EECDH+AESGCM:EDH+AESGCM;
ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
ssl_session_timeout  10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off; # Requires nginx >= 1.5.9
ssl_stapling on; # Requires nginx >= 1.3.7
ssl_stapling_verify on; # Requires nginx => 1.3.7
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
</code>```

And this is ssl_protocols line in my /etc/nginx/nginx.conf

```<code>ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
</code>```

This settings solved my problem.
I hope helps others too.

Body:
I have Node.js rest APIs, which I am using in my flutter app to do requests accordingly, but when I tried to do the same I am getting an exception that is:

Exception has occurred.
HandshakeException (HandshakeException: Handshake error in client (OS Error: TLSV1_ALERT_PROTOCOL_VERSION(tls_record.cc:586)))

I am doing the request with the http client like:

import 'package:http/http.dart' as http;
const _baseUrl = https://domain.in/api/

http.Response response = await http.post(
      _baseUrl + 'user/login',
      body: json.encode(_authData),
      headers: {'Content-Type': 'application/json'},
    ).catchError((onError){
      print(onError);
    });

It was working with http but it is not working with https.

Body:
This is a server side error because of your nginx ssl configuration.

ssl_protocols line in your /etc/nginx/nginx.conf file should look like this :

ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;

If you use extra file for your ssl settings in /etc/nginx/sites-enabled/default or yourdomain file in same path, for example a file called ssl-params.conf, add ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; line in this file too.

This is part of my /etc/nginx/sites-enabled/default file:

server {
    #Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name domain.net www.domain.net;

    # Use the Let's Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/domain.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/domain.net/privkey.pem;

    #Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf; // <- !pay attention this line

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://localhost:5000/;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_redirect off;
    }
}

This is my /etc/nginx/snippets/ssl-params.conf file:

ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ciphers EECDH+AESGCM:EDH+AESGCM;
ssl_ecdh_curve secp384r1; # Requires nginx >= 1.1.0
ssl_session_timeout  10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off; # Requires nginx >= 1.5.9
ssl_stapling on; # Requires nginx >= 1.3.7
ssl_stapling_verify on; # Requires nginx => 1.3.7
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";

And this is ssl_protocols line in my /etc/nginx/nginx.conf

ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;

This settings solved my problem.
I hope helps others too.


问:
python class for graph data structure contain add edge method i find it complex to understand
I'm learning python and this an exercise, I'm trying to build graph data.

```<code>class Vertex:
  def __init__(self, value):
    self.value = value
    self.edges = {}

  def add_edge(self, vertex, weight = 0):
    self.edges[vertex] = weight

  def get_edges(self):
    return list(self.edges.keys())
class Graph:
  def __init__(self, directed = False):
    self.graph_dict = {}
    self.directed = directed

  def add_vertex(self, vertex):
    self.graph_dict[vertex.value] = vertex

  def add_edge(self, from_vertex, to_vertex, weight = 0):
    self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
    if not self.directed:
      self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)
</code>```

In graph class in add_edge method i find the following code complex and I don't understand how it works.

self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
```

答:
I don't know what make you problem but you can write it in two lines</p>

```<code>#get some vertex from ditcionary
some_vertex = self.graph_dict[from_vertex.value]

#and add new edge to this vertex
some_vertex.add_edge(to_vertex.value, weight)
</code>```

Body:
I'm learning python and this an exercise, I'm trying to build graph data.

class Vertex:
  def __init__(self, value):
    self.value = value
    self.edges = {}

  def add_edge(self, vertex, weight = 0):
    self.edges[vertex] = weight

  def get_edges(self):
    return list(self.edges.keys())
class Graph:
  def __init__(self, directed = False):
    self.graph_dict = {}
    self.directed = directed

  def add_vertex(self, vertex):
    self.graph_dict[vertex.value] = vertex

  def add_edge(self, from_vertex, to_vertex, weight = 0):
    self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
    if not self.directed:
      self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)

In graph class in add_edge method i find the following code complex and I don't understand how it works.

self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)

Body:
I don't know what make you problem but you can write it in two lines

#get some vertex from ditcionary
some_vertex = self.graph_dict[from_vertex.value]

#and add new edge to this vertex
some_vertex.add_edge(to_vertex.value, weight)


问:
How to select many rows from 1 table and insert into a specific JSONB field of a specific row in another table? But in a single raw SQL query
postgres 10.3

I have about 1000 rows inside a table called sites

If I query like this

```<code>SELECT id, name from sites;
</code>```

I will get the 1000 rows.

I also have another table called jsonindexdocument with a single row where the id is 1 and a field called index that is JSONB

Is it possible that in a single query I take out all the 1000 rows in sites table and then update the field called index under id 1?

The format of the json would be

```<code>[
  {
     "id": 10,
     "name": "somename"
  },
  {
     "id": 11,
     "name": "another name"
  } // and the rest of the 1000 rows
]
</code>```

I am also okay if it uses more than 1 raw SQL statement.

UPDATE

I want to add that if the result is empty set, then default to empty array in the json field

答:
Assuming you're OK with fully replacing the index value in the jsonindexdocument table:

```<code>UPDATE jsonindexdocument
SET index = (
    -- using json_agg(row_to_json(sites.*)) would also work here, if you want to copy
    -- all columns from the sites table into the json value
    SELECT COALESCE(json_agg(json_build_object(
        'id', id,
        'name', name
    )), '[]'::json)
    FROM sites
)
WHERE id = 1;
</code>```

As an example:

```<code>CREATE TEMP TABLE sites (
    id   INT,
    name TEXT
);

CREATE TEMP TABLE jsonindexdocument (
    id    INT,
    index JSON
);

INSERT INTO sites
VALUES (1, 'name1')
     , (2, 'name2');

INSERT INTO jsonindexdocument
VALUES (1, NULL);

UPDATE jsonindexdocument
SET index = (
    SELECT COALESCE(json_agg(json_build_object(
        'id', id,
        'name', name
    )), '[]'::json)
    FROM sites
)
WHERE id = 1;

SELECT * FROM jsonindexdocument;
</code>```

returns

```<code>+--+------------------------------------------------------------+
|id|index                                                       |
+--+------------------------------------------------------------+
|1 |[{"id" : 1, "name" : "name1"}, {"id" : 2, "name" : "name2"}]|
+--+------------------------------------------------------------+
</code>```

Body:
postgres 10.3

I have about 1000 rows inside a table called sites

If I query like this

SELECT id, name from sites;

I will get the 1000 rows.

I also have another table called jsonindexdocument with a single row where the id is 1 and a field called index that is JSONB

Is it possible that in a single query I take out all the 1000 rows in sites table and then update the field called index under id 1?

The format of the json would be

[
  {
     "id": 10,
     "name": "somename"
  },
  {
     "id": 11,
     "name": "another name"
  } // and the rest of the 1000 rows
]

I am also okay if it uses more than 1 raw SQL statement.

UPDATE

I want to add that if the result is empty set, then default to empty array in the json field

Body:
Assuming you're OK with fully replacing the index value in the jsonindexdocument table:

UPDATE jsonindexdocument
SET index = (
    -- using json_agg(row_to_json(sites.*)) would also work here, if you want to copy
    -- all columns from the sites table into the json value
    SELECT COALESCE(json_agg(json_build_object(
        'id', id,
        'name', name
    )), '[]'::json)
    FROM sites
)
WHERE id = 1;

As an example:

CREATE TEMP TABLE sites (
    id   INT,
    name TEXT
);

CREATE TEMP TABLE jsonindexdocument (
    id    INT,
    index JSON
);

INSERT INTO sites
VALUES (1, 'name1')
     , (2, 'name2');

INSERT INTO jsonindexdocument
VALUES (1, NULL);

UPDATE jsonindexdocument
SET index = (
    SELECT COALESCE(json_agg(json_build_object(
        'id', id,
        'name', name
    )), '[]'::json)
    FROM sites
)
WHERE id = 1;

SELECT * FROM jsonindexdocument;

returns

+--+------------------------------------------------------------+
|id|index                                                       |
+--+------------------------------------------------------------+
|1 |[{"id" : 1, "name" : "name1"}, {"id" : 2, "name" : "name2"}]|
+--+------------------------------------------------------------+


问:
VSCode: Is there a way to hide top action menu bar?
In VSCode, is there a way to hide the top action menu bar that appears in the tabs row? I rarely use it and I find that it crowds the already limited space available to browse through open tabs. Moreover, its presentation is also inconsistent, especially when split panes are activated.

I'm not sure if I am referring to this VSCode functionality properly, so here's a screenshot demonstrating what I'm talking about (file names had to be blurred out due to NDA reasons):

Thank you.

答:
Update 2022-09-28

An issue to address this feature has been completed and it will arrive with the next release. It is already available on the Insiders version.

This closed issue references another feature request different from the original one referenced on this answer.

Context

It is called editor actions and, within the standard/native VSCode settings, you cannot hide it.

A setting to hide this annoying bar is an open issue at VScode's GitHub since March 2018.

Fixes

Removing the whole bar

I feel your pain. This worked for me:

Install the Customize UI extension.

Open your user settings JSON:
cmd + shift + P / ctrl + shift + P

Add this setting:

  "customizeUI.stylesheet": {
    ".editor-actions": "display: none !important;",
  },
```
<p>It is gone!</p>
<h4>Removing specific icons, by position</h4>
<p>The foremost left icon is the number <code>1</code>.</p>
<p><em>Example in plain CSS:</em></p>
<pre class="lang-css prettyprint-override"><code>.menu-item-action-item-icon-1,
.menu-item-action-item-icon-3 {
  display: none !important;
}
</code>```

Example using Customize UI extension:

  "customizeUI.stylesheet": {
    ".menu-item-action-item-icon-1": "display: none !important;",
    ".menu-item-action-item-icon-3": "display: none !important;",
  },

```
<h4>Removing just Gitlens icons</h4>
<p>Gitlens icons can be hidden within Gitlens' settings:</p>
<pre class="lang-json prettyprint-override"><code>"gitlens.menus": {
    "editorGroup": {
        "blame": false,
        "compare": false
    },
},
</code>```

Body:
Update 2022-09-28

An issue to address this feature has been completed and it will arrive with the next release. It is already available on the Insiders version.

This closed issue references another feature request different from the original one referenced on this answer.

Context

It is called editor actions and, within the standard/native VSCode settings, you cannot hide it.

A setting to hide this annoying bar is an open issue at VScode's GitHub since March 2018.

Fixes

Removing the whole bar

I feel your pain. This worked for me:

Install the Customize UI extension.

Open your user settings JSON:
cmd + shift + P / ctrl + shift + P

Add this setting:

  "customizeUI.stylesheet": {
    ".editor-actions": "display: none !important;",
  },

It is gone!

Removing specific icons, by position

The foremost left icon is the number 1.

Example in plain CSS:

.menu-item-action-item-icon-1,
.menu-item-action-item-icon-3 {
  display: none !important;
}

Example using Customize UI extension:

  "customizeUI.stylesheet": {
    ".menu-item-action-item-icon-1": "display: none !important;",
    ".menu-item-action-item-icon-3": "display: none !important;",
  },

Removing just Gitlens icons

Gitlens icons can be hidden within Gitlens' settings:

"gitlens.menus": {
    "editorGroup": {
        "blame": false,
        "compare": false
    },
},


问:
Mercurial: How to overwrite files in a particular folder?
I am working on a new project with three other developers, we are all new to Mercurial.

A post build event is created in Visual Studio 2010 to copy DLLs to a common folder. Each time anyone commits or updates we want to rewrite without considering version or merging. That is, this particular folder overwrite local working copy on each update.

Is it possible?

答:
The conventional wisdom is that you shouldn't be committing build products at all.  You version source code not dlls.  Those you download during build from your CI system.

That said, if they're all DLLs you can set a custom merger for those:

```<code>[merge-patterns]
 **.dll = internal:remote
</code>```

That always uses the "other" version when there's a conflict on .dll files.  More details here.

Body:
The conventional wisdom is that you shouldn't be committing build products at all.  You version source code not dlls.  Those you download during build from your CI system.

That said, if they're all DLLs you can set a custom merger for those:

[merge-patterns]
 **.dll = internal:remote

That always uses the "other" version when there's a conflict on .dll files.  More details here.


问:
How can i trim spaces in object.values?
my object.values(article.data) returns

```<code>[' This is ']
['is ']
['a']
['sentence ']
</code>```

how can i trim and remove the spaces so it becomes

```<code>['Thisis']
['is']
['a']
['sentence']
</code>```

答:
You can implement this in a cleaner way

let obj = {
  'k1': [' This is '],
  'k2': ['is '],
  'k3': ['a'],
  'k4': ['sentence ']
}

const result = Object.values(obj).map(values => values.map(value => value.replace(/\s/g, '')));

console.log(result)```

Title: How can i trim spaces in object.values?

Body:
my object.values(article.data) returns

[' This is ']
['is ']
['a']
['sentence ']

how can i trim and remove the spaces so it becomes

['Thisis']
['is']
['a']
['sentence']


问:
Get cookie by name
I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the for splits the data into separate values and puts it in an array.

```<code> function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie?
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }
</code>```

答:
Get cookie by name just pass the name of cookie to below function</p>

```<code>function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
</code>```

Title: Get cookie by name

Body:
I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the for splits the data into separate values and puts it in an array.

 function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie?
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

Body:
Get cookie by name just pass the name of cookie to below function

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}


问:
How to distribute custom code through SLURM manager?
I have access to a computer cluster with the SLURM manager. I want to achieve that different nodes execute different parts of my code. If I understood properly, this can be achieved through SLURM with the srun command if your code is properly written. It should be something like this MPI example here https://support.ceci-hpc.be/doc/_contents/QuickStart/SubmittingJobs/SlurmTutorial.html .

But I don't understand how to create this code in TF. There is a lot more information for version 1 of TF. If I try something like this

```<code>jobs={'worker': 4}
cluster=tf.distribute.cluster_resolver.SlurmClusterResolver(jobs=jobs)
server0 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=0)
server1 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=1)
server2 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=2)
server2 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=3)
</code>```

and run this using SLURM, I get an error, where I see that only the first server has started, but the second was trying to use the same address, which is 'localhost:8888'. So essentially, I do not know how to create servers on different nodes which can latter communicate. Should I run different scripts simultaneously? Must I use the command line with flags or something like that?

Afterwards, my idea is to use

```<code>with tf.device("/job:worker/task:0"):
#some code
with tf.device("/job:worker/task:1"):
#some other code
</code>```

to distribute work. Any help? I don't think that I can use any of the distribute strategies TF has to offer.

答:
It seems that I have found a solution, so I am posting it, maybe it will help someone. It seems that

```<code>cluster = tf.compat.v1.train.ClusterSpec({'worker': ['n03:2222', 'n04:2223'] })
</code>```

instead of cluster_resolver solves the problem of the same addresses. Later, I needed to invoke a session, and it had to be a session with the target of the server related to task 1 (not sure why, probably it has something to do with the master node), like this:

```<code>with tf.compat.v1.Session(server1.target) as sess:
    x=tf.Variable(...)
    for k in range(n):
        y1=f1(x)
        y2=f2(x)
        y1=y1.eval()
        y2=y2.eval()
</code>```

where f1(x) is a tf.function where the distributing to workers happens, for example:

```<code>@tf.function
def f1(x):
    with tf.device("/job:worker/task:0"):
         y=...
         x.assign(x+1)
    return y
</code>```

and f2(x) is similar, just with task 1.
This was all in one script which I call in a .sh file.

Body:
I have access to a computer cluster with the SLURM manager. I want to achieve that different nodes execute different parts of my code. If I understood properly, this can be achieved through SLURM with the srun command if your code is properly written. It should be something like this MPI example here https://support.ceci-hpc.be/doc/_contents/QuickStart/SubmittingJobs/SlurmTutorial.html .

But I don't understand how to create this code in TF. There is a lot more information for version 1 of TF. If I try something like this

jobs={'worker': 4}
cluster=tf.distribute.cluster_resolver.SlurmClusterResolver(jobs=jobs)
server0 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=0)
server1 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=1)
server2 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=2)
server2 = tf.distribute.Server(cluster.cluster_spec(), job_name='worker', task_index=3)

and run this using SLURM, I get an error, where I see that only the first server has started, but the second was trying to use the same address, which is 'localhost:8888'. So essentially, I do not know how to create servers on different nodes which can latter communicate. Should I run different scripts simultaneously? Must I use the command line with flags or something like that?

Afterwards, my idea is to use

with tf.device("/job:worker/task:0"):
#some code
with tf.device("/job:worker/task:1"):
#some other code

to distribute work. Any help? I don't think that I can use any of the distribute strategies TF has to offer.

Body:
It seems that I have found a solution, so I am posting it, maybe it will help someone. It seems that

cluster = tf.compat.v1.train.ClusterSpec({'worker': ['n03:2222', 'n04:2223'] })

instead of cluster_resolver solves the problem of the same addresses. Later, I needed to invoke a session, and it had to be a session with the target of the server related to task 1 (not sure why, probably it has something to do with the master node), like this:

with tf.compat.v1.Session(server1.target) as sess:
    x=tf.Variable(...)
    for k in range(n):
        y1=f1(x)
        y2=f2(x)
        y1=y1.eval()
        y2=y2.eval()

where f1(x) is a tf.function where the distributing to workers happens, for example:

@tf.function
def f1(x):
    with tf.device("/job:worker/task:0"):
         y=...
         x.assign(x+1)
    return y

and f2(x) is similar, just with task 1.
This was all in one script which I call in a .sh file.


问:
Parsing a tab-delimited text file to replace columns with one vertical list (Python)
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine
</code>```

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

```<code>while segmentedLine:
    item = segmentedLine.split("\t")
    print item
</code>```

Thanks very much for any input.

答:
put everything following a tab on a new line

If this is all you want, why not just use the str.replace function?

```<code>for line in open('feddocs_2011.txt', 'r'):
    segemented_line = line.replace('\t', '\n')
    print(segmented_line)
</code>```

If, for some reason, you want to keep the tabs:

```<code>for line in open('feddocs_2011.txt', 'r'):
    segemented_line = line.replace('\t', '\t\n')
    print(segmented_line)
</code>```

Body:
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list.

I have the following code:

for line in open('feddocs_2011.txt', 'r'):
    segmentedLine = line.split("/t")
    print segmentedLine

This seems to create a separate string for each line, but I think I may need to loop through each of those new strings to split those next. I thought it would have put everything following a tab on a new line. I tried the following, but got an error message that "list" doesn't have a split function.

while segmentedLine:
    item = segmentedLine.split("\t")
    print item

Thanks very much for any input.

Body:
put everything following a tab on a new line

If this is all you want, why not just use the str.replace function?

for line in open('feddocs_2011.txt', 'r'):
    segemented_line = line.replace('\t', '\n')
    print(segmented_line)

If, for some reason, you want to keep the tabs:

for line in open('feddocs_2011.txt', 'r'):
    segemented_line = line.replace('\t', '\t\n')
    print(segmented_line)


问:
table.column is not a function in jquery datatabbe
In jquery datatable  i am getting  error table.column is not a function

```<code><script>

$(document).ready(function() {
    var table = $('#lsotable').dataTable();

    $("#lsotable thead th").each( function ( i ) {

        var select = $('<select><option value=""></option></select>')
            .appendTo( $(this).empty() )
            .on( 'change', function () {
                table.column( i )
                    .search( $(this).val() )
                    .draw();
            } );

        table.column( i ).data().unique().sort().each( function ( d, j ) {
            select.append( '<option value="'+d+'">'+d+'</option>' )
        } );
    } );
} );
</script>
</code>```

I am getiing the table data from while loops, i want it should be only three columns, how i can do .

答:
Those who are struggling with a similar type of problem in datatable version 1.9.* can have a look on here:
 Link

Body:
In jquery datatable  i am getting  error table.column is not a function

I am getiing the table data from while loops, i want it should be only three columns, how i can do .


问:
Initialization goal raised in swi prolog
I'm new to swi-prolog. I installed swi-prolog and, at first, it works fine. I am then receiving this error:

ERROR: /Applications/SWIProlog.app/Contents/swipl/library/win_menu.pl:205: Initialization goal raised exception:

ERROR: file_base_name/2: Cannot represent due to `encoding' (Cannot represent char U0395 using current locale encoding)

I am using Mojave.

Can anybody help?

答: If you try pwd., and the answer is % //, then you should not use the IDE of SWI-prolog. Instead, you could open it in the terminal with SWI-prolog.