问:
How do I delete Firestore dictionary value?
I have a value in a document which I set like this:

```<code>func uploadMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let updateData = ["medications" : [medication : dosage]]

    docRef.setData(updateData, merge: true) { (err) in
        if err != nil {
            print(err?.localizedDescription as Any)
            self.view.makeToast(err?.localizedDescription as! String)
        } else {
            self.refresh()
            print(" Data Uploaded")
        }
    }
}
</code>```

Now I need to Delete this value, but I can't figure out how:

```<code>func removeMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let data = [[medication : dosage] : FieldValue.delete()]

    docRef.updateData(["medications" : data]) { (err) in
        print("delete")
    }
}
</code>```

This compiles but causes a crash:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_TtGCs26_SwiftDeferredNSDictionarySSSS_$ length]: unrecognized
  selector sent to instance 0x2830ca100'

I've tried many different variations including

```<code> let data = [[medication : dosage]]

    docRef.updateData(["medications" : FieldValue.arrayRemove(data)]) { (err) in
        print("delete")
    }
</code>```

The data in Firestore is set like:

```<code>medications {
   Venlafaxine : 37.5,
   Sertraline : 100
}
</code>```

How can I delete a [Venlafaxine : 37.5] row essentially.

答:
There doesn't seem to be a way to do this with a dictionary, only an array. So I had to delete the whole section and rebuild it like so:

```<code> func removeMedDosage(dosage: String, medication: String) {
    print("remove")
    let docRef = db.collection("users").document(userId!)

    removeDictionary = [:]

    for (index, element) in self.meds.enumerated() {
        removeDictionary[element] = self.dosages[index]
    }

    let data = removeDictionary

    docRef.updateData(["medications" : data]) { (err) in

    }
    self.refresh()
}
</code>```

Priot to this I deleted the chosen one from the arrays used for the tableView:

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in

        let index = indexPath.row
        let med = self.meds[index]
        let dose = self.dosages[index]

        self.meds.remove(at: index)
        self.dosages.remove(at: index)

        self.tableView.deleteRows(at: [indexPath], with: .fade)
        self.removeMedDosage(dosage: dose, medication: med)

    }
    return [delete]
}
</code>```

Body:
I have a value in a document which I set like this:

func uploadMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let updateData = ["medications" : [medication : dosage]]

    docRef.setData(updateData, merge: true) { (err) in
        if err != nil {
            print(err?.localizedDescription as Any)
            self.view.makeToast(err?.localizedDescription as! String)
        } else {
            self.refresh()
            print(" Data Uploaded")
        }
    }
}

Now I need to Delete this value, but I can't figure out how:

func removeMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let data = [[medication : dosage] : FieldValue.delete()]

    docRef.updateData(["medications" : data]) { (err) in
        print("delete")
    }
}

This compiles but causes a crash:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_TtGCs26_SwiftDeferredNSDictionarySSSS_$ length]: unrecognized
  selector sent to instance 0x2830ca100'

I've tried many different variations including

 let data = [[medication : dosage]]

    docRef.updateData(["medications" : FieldValue.arrayRemove(data)]) { (err) in
        print("delete")
    }

The data in Firestore is set like:

medications {
   Venlafaxine : 37.5,
   Sertraline : 100
}

How can I delete a [Venlafaxine : 37.5] row essentially.

Body:
There doesn't seem to be a way to do this with a dictionary, only an array. So I had to delete the whole section and rebuild it like so:

 func removeMedDosage(dosage: String, medication: String) {
    print("remove")
    let docRef = db.collection("users").document(userId!)

    removeDictionary = [:]

    for (index, element) in self.meds.enumerated() {
        removeDictionary[element] = self.dosages[index]
    }

    let data = removeDictionary

    docRef.updateData(["medications" : data]) { (err) in

    }
    self.refresh()
}

Priot to this I deleted the chosen one from the arrays used for the tableView:

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "delete") { (action, indexPath) in

        let index = indexPath.row
        let med = self.meds[index]
        let dose = self.dosages[index]

        self.meds.remove(at: index)
        self.dosages.remove(at: index)

        self.tableView.deleteRows(at: [indexPath], with: .fade)
        self.removeMedDosage(dosage: dose, medication: med)

    }
    return [delete]
}


来源: stackexchange

问:
Get the Feature id openlayers5
In OL2 feature id's were generated internally. In OL5 this doesn't seem to be the case since the id's are undefined.  Has the internal feature id been removed from OL5? If not what do I need to do to get the id's generated. I am requesting the id via:

feature.getId()

答:
If a geoJson or other source contains feature ids they will be used, otherwise the feature id will be left undefined.  You could generate your own ids if you you need them.
 If the source contains a mix of features with and without id you will need to ensure  your auto generated ids are unique (e.g. use a prefix).</p>

```<code>var featureId = 0;
vector.getSource().on('addfeature', function(e){
  featureId++;
  if (!e.feature.getId()) {
    e.feature.setId('auto-gen-'+featureId);
  }
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get the Feature id openlayers5

Body:
If a geoJson or other source contains feature ids they will be used, otherwise the feature id will be left undefined.  You could generate your own ids if you you need them.
 If the source contains a mix of features with and without id you will need to ensure  your auto generated ids are unique (e.g. use a prefix).

var featureId = 0;
vector.getSource().on('addfeature', function(e){
  featureId++;
  if (!e.feature.getId()) {
    e.feature.setId('auto-gen-'+featureId);
  }
});


问:
How do I insert this reord into loan table?Some attributes require SELECT statements?
I have a garage_manager table

```<code>CREATE TABLE garage_manager(
garage_code NUMBER(2) NOT NULL,
man_id NUMBER(2) NOT NULL,
specialisation_id NUMBER(4) NOT NULL
);
</code>```

I'm trying to insert a row into the garage_manager table like this.Man_id is hard-coded.

```<code>INSERT INTO garage_manager VALUES(
(SELECT garage_code FROM garage WHERE garage_email = 'melbournec@rdbms.example.com'),
1,
(SELECT specialisation_id FROM manager_specialisation WHERE specialisation_type='S')
);
</code>```

However, I'm getting the error "too many values"?

答:
Maybe there are multiple specialisation_ids that match specialisation_type='S'? If so, you need to aggregate that column in some way.

Another approach is to use INSERT...SELECT syntax.

INSERT INTO garage_manager (garage_code, man_id, specialisation_id)
SELECT garage.garage_code, 1, manager_specialisation.specialisation_id
FROM garage, manager_specialisation
WHERE garage_email = 'melbournec@rdbms.example.com' AND specialisation_type='S'
```

Note that if there are multiple matching garages or manager specialisations, then you will end up inserting multiple rows this way. You didn't provide enough information about your database schema to be able to tell if that might be a problem.

Body:
I have a garage_manager table

CREATE TABLE garage_manager(
garage_code NUMBER(2) NOT NULL,
man_id NUMBER(2) NOT NULL,
specialisation_id NUMBER(4) NOT NULL
);

I'm trying to insert a row into the garage_manager table like this.Man_id is hard-coded.

INSERT INTO garage_manager VALUES(
(SELECT garage_code FROM garage WHERE garage_email = 'melbournec@rdbms.example.com'),
1,
(SELECT specialisation_id FROM manager_specialisation WHERE specialisation_type='S')
);

However, I'm getting the error "too many values"?

Body:
Maybe there are multiple specialisation_ids that match specialisation_type='S'? If so, you need to aggregate that column in some way.

Another approach is to use INSERT...SELECT syntax.

INSERT INTO garage_manager (garage_code, man_id, specialisation_id)
SELECT garage.garage_code, 1, manager_specialisation.specialisation_id
FROM garage, manager_specialisation
WHERE garage_email = 'melbournec@rdbms.example.com' AND specialisation_type='S'

Note that if there are multiple matching garages or manager specialisations, then you will end up inserting multiple rows this way. You didn't provide enough information about your database schema to be able to tell if that might be a problem.


问:
Problem trying to retrieve info from a json file with an api with php
first, thanks in advance for your help.

I have some problems trying to get data from an online JSON file. I using PHP (with cURL). I can access the file and I can put an echo and see all of the "raw" data in it. I want to find a way to show only the type of data I want (for example, only a movie). I use the foreach but I got a notice and a warning.

I tried with the second argument of json_decode and try with foreach but it doesn't work. I did some research but even if I try, there is always the same errors. I tried with "movie" from the beginning of the file but I also have the same error. Is it because "movie" doesn't have a "[" (it is also twice)? Then, I tried with the "apiver" but same error.

//getting the access of the file - cURL is working fine
$sJSON = see_json('link');
$aJSON = json_decode($sJSON, true);

foreach($aJSON->apiver as $mydatas) {
  foreach ($mydatas->values as $value) {
    echo $value->value . "
";
  }
}
```

```//beginning of the JSON file
"movie": {
        "1010414": {
            "title_fr": "Godzilla II - Roi des Monstres",
            "lang_ov": "en",
            "release_de_ch": "2019-05-30",
            "title": "Godzilla: King of the Monsters",
            "release_fr_ch": "2019-05-29",
            "title_de": "Godzilla II: King of the Monsters",
            "id": "1010414"
        },
        "1011095": {
            "title_fr": "Le Parc des merveilles",
            "lang_ov": "en",
            "release_de_ch": "2019-04-11",
            "title": "Wonder Park",
            "release_fr_ch": "2019-04-03",
            "title_de": "Willkommen im Wunder Park",
            "id": "1011095"

//far in the file
"apiver": 210,
    "sched": [
        {
            "ts": 1559201400,
            "id": "VS1258",
            "duration": 129,
            "movie": "1012351",
            "site": "SPE",
            "aud": 3,
            "age": "6/10",
            "lang": "de"
        },
        {
            "ts": 1559202300,
            "id": "VM33930",
            "duration": 85,
            "movie": "1012655",
            "site": "MOS",
            "aud": 3,
            "age": "6/6",
            "lang": "de"
```

I want to show all data from "apiver" but it results in 2 errors :

Notice: Trying to get property 'apiver' of non-object in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

Warning: Invalid argument supplied for foreach() in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

What am I doing wrong?

Again, thanks for your help!

答:
First of all, I can suggest you to use the file_get_contents builtin function for fetching the content from the API.

```<code>$sJSON = file_get_contents("link");
</code>```

Now come to the decode of JSON file, the json_decode is good. But I suggest you not to use the true as 2nd Argument, as it converts the Object into Associative array.

```<code>$response = json_decode($sJSON);
</code>```

Now use the $response->movie to see the movie objects.
Now to iter in the object, use foreach loop and use the $value variable

```<code>foreach ($response->movie as $key => $value) {
    // Do something
}
</code>```

Now, to get the individual objects use $value->title_fr and so on inside the foreach loop.

I'm giving an example to show the movie names in a new line

```<code>$sJSON = file_get_contents("link");
$response = json_decode($sJSON);

foreach ($response->movie as $key => $value) {
    echo $value->title_fr;
    echo "<br>";
}
</code>```

Body:
first, thanks in advance for your help.

I have some problems trying to get data from an online JSON file. I using PHP (with cURL). I can access the file and I can put an echo and see all of the "raw" data in it. I want to find a way to show only the type of data I want (for example, only a movie). I use the foreach but I got a notice and a warning.

I tried with the second argument of json_decode and try with foreach but it doesn't work. I did some research but even if I try, there is always the same errors. I tried with "movie" from the beginning of the file but I also have the same error. Is it because "movie" doesn't have a "[" (it is also twice)? Then, I tried with the "apiver" but same error.

//getting the access of the file - cURL is working fine
$sJSON = see_json('link');
$aJSON = json_decode($sJSON, true);

foreach($aJSON->apiver as $mydatas) {
  foreach ($mydatas->values as $value) {
    echo $value->value . "
";
  }
}

//beginning of the JSON file
"movie": {
        "1010414": {
            "title_fr": "Godzilla II - Roi des Monstres",
            "lang_ov": "en",
            "release_de_ch": "2019-05-30",
            "title": "Godzilla: King of the Monsters",
            "release_fr_ch": "2019-05-29",
            "title_de": "Godzilla II: King of the Monsters",
            "id": "1010414"
        },
        "1011095": {
            "title_fr": "Le Parc des merveilles",
            "lang_ov": "en",
            "release_de_ch": "2019-04-11",
            "title": "Wonder Park",
            "release_fr_ch": "2019-04-03",
            "title_de": "Willkommen im Wunder Park",
            "id": "1011095"

//far in the file
"apiver": 210,
    "sched": [
        {
            "ts": 1559201400,
            "id": "VS1258",
            "duration": 129,
            "movie": "1012351",
            "site": "SPE",
            "aud": 3,
            "age": "6/10",
            "lang": "de"
        },
        {
            "ts": 1559202300,
            "id": "VM33930",
            "duration": 85,
            "movie": "1012655",
            "site": "MOS",
            "aud": 3,
            "age": "6/6",
            "lang": "de"

I want to show all data from "apiver" but it results in 2 errors :

Notice: Trying to get property 'apiver' of non-object in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

Warning: Invalid argument supplied for foreach() in
  C:\xampp\htdocs\Cinema Pathe\curl.php on line 28

What am I doing wrong?

Again, thanks for your help!

Body:
First of all, I can suggest you to use the file_get_contents builtin function for fetching the content from the API.

$sJSON = file_get_contents("link");

Now come to the decode of JSON file, the json_decode is good. But I suggest you not to use the true as 2nd Argument, as it converts the Object into Associative array.

$response = json_decode($sJSON);

Now use the $response->movie to see the movie objects.
Now to iter in the object, use foreach loop and use the $value variable

foreach ($response->movie as $key => $value) {
    // Do something
}

Now, to get the individual objects use $value->title_fr and so on inside the foreach loop.

I'm giving an example to show the movie names in a new line

$sJSON = file_get_contents("link");
$response = json_decode($sJSON);

foreach ($response->movie as $key => $value) {
    echo $value->title_fr;
    echo "<br>";
}


问:
Bash: can't launch a program created with make on linux
I want to build my program using make and then launch the created executable via bash script, but bash can't find the executable, although it was created and i can launch it manually. The problem only exist on linux mint 19 in Gnome-terminal.
Edit: The exact error message is: "/path/to/my/executable: no such file or directory"

I have a cross-platform project where i need to run cmake, then build the project and finally launch the created executable. I have a bash script to automate the process:
Edit: Its only the part that causes the trouble ;)

for TASK in $@; do
    if [[ $TASK == "make" ]]; then
        call cmake here, this creates a .sln or a make file
    elif [[ $TASK == "build" ]]; then
        if  [[ $OS == 'CYGWIN_NT-10.0' ]]; then
            MSBuild.exe "./build/debug/myproject.sln"
        elif [[ $OS == 'Linux' ]]; then
            cd ./build/debug/ && make
        else
            error...
        fi
    elif [[ $TASK == "run" ]]; then
        if  [[ $OS == 'CYGWIN_NT-10.0' ]]; then
            ./build/debug/Debug/program.exe
        elif [[ $OS == 'Linux' ]]; then
            ./build/debug/program
        else
            error...
        fi
    else
        error...
    fi
done
```

Calling "./script.sh make build run" should, for example, call cmake to create the build files, then call the build program (make on linux or msbuild on windows) and then launch the created executable. This works fine on windows 10 in a cygwin terminal. On Linux the call "./script.sh build run" fails, because it can't find the executable. However "./script.sh build && ./build/debug/program" works nicely. Surprisingly "./script.sh build && ./script.sh run" also works as expected.
Why is that? Is there any Bug in the bash script? And why does it work on Cygwin but not on linux mint?

答:
Ok, I solved it. Asking questions seems to be the first step to finding a solution.
The problem seems to be, that the call "./script.sh build run" first evaluates the build command "cd ./build/debug/ && make". I thougth such commands would spawn a new sub shell, where the cd and make commands are then evaluated and then the shell would continue in the original working directory. Apparently this does not happen and the working directory of the executing script is changed to "./build/debug". The next command "run" tries to execute "./build/debug/program" but since the current working directory is changed, it is essentially looking for "./build/debug/build/debug/program" which does not exist.
I added the line

cd ../../
```

<p>to the code for the build-command. It now looks like this</p>

<pre class="lang-sh prettyprint-override"><code>...
elif [[ $OS == 'Linux' ]]; then
    cd ./build/debug/ && make
    cd ../../
else
...
</code>```

I don't know exactly why, but it works this way on linux.

Body:
I want to build my program using make and then launch the created executable via bash script, but bash can't find the executable, although it was created and i can launch it manually. The problem only exist on linux mint 19 in Gnome-terminal.
Edit: The exact error message is: "/path/to/my/executable: no such file or directory"

I have a cross-platform project where i need to run cmake, then build the project and finally launch the created executable. I have a bash script to automate the process:
Edit: Its only the part that causes the trouble ;)

for TASK in $@; do
    if [[ $TASK == "make" ]]; then
        call cmake here, this creates a .sln or a make file
    elif [[ $TASK == "build" ]]; then
        if  [[ $OS == 'CYGWIN_NT-10.0' ]]; then
            MSBuild.exe "./build/debug/myproject.sln"
        elif [[ $OS == 'Linux' ]]; then
            cd ./build/debug/ && make
        else
            error...
        fi
    elif [[ $TASK == "run" ]]; then
        if  [[ $OS == 'CYGWIN_NT-10.0' ]]; then
            ./build/debug/Debug/program.exe
        elif [[ $OS == 'Linux' ]]; then
            ./build/debug/program
        else
            error...
        fi
    else
        error...
    fi
done

Calling "./script.sh make build run" should, for example, call cmake to create the build files, then call the build program (make on linux or msbuild on windows) and then launch the created executable. This works fine on windows 10 in a cygwin terminal. On Linux the call "./script.sh build run" fails, because it can't find the executable. However "./script.sh build && ./build/debug/program" works nicely. Surprisingly "./script.sh build && ./script.sh run" also works as expected.
Why is that? Is there any Bug in the bash script? And why does it work on Cygwin but not on linux mint?

Body:
Ok, I solved it. Asking questions seems to be the first step to finding a solution.
The problem seems to be, that the call "./script.sh build run" first evaluates the build command "cd ./build/debug/ && make". I thougth such commands would spawn a new sub shell, where the cd and make commands are then evaluated and then the shell would continue in the original working directory. Apparently this does not happen and the working directory of the executing script is changed to "./build/debug". The next command "run" tries to execute "./build/debug/program" but since the current working directory is changed, it is essentially looking for "./build/debug/build/debug/program" which does not exist.
I added the line

cd ../../

to the code for the build-command. It now looks like this

...
elif [[ $OS == 'Linux' ]]; then
    cd ./build/debug/ && make
    cd ../../
else
...

I don't know exactly why, but it works this way on linux.


问:
Limiting sensor reading into 4 decimal
I am a newbie to Python. I am fetching sensor readings and it has too many decimal places (x.xxxxxxxx)
I want to limit the reading into 4 decimals places (x.xxxx).

```<code>from altimu10v5.lsm6ds33 import LSM6DS33
from altimu10v5.lis3mdl import LIS3MDL
from altimu10v5.lps25h import LPS25H

from time import sleep

lsm6ds33 = LSM6DS33()
lsm6ds33.enable()

lps25h = LPS25H()
lps25h.enable()

lis3mdl = LIS3MDL()
lis3mdl.enable()

while True:

    #print(lsm6ds33.get_accelerometer_raw())
    print("{:.2f}".format.lsm6ds33.get_accelerometer_g_forces())

    sleep(0.4)
</code>```

When I run this code I get the following error message:

" attribute error : ' builtin_function_or_method' object has no attribute 'lsm6ds33'

答:
Try:

```<code>print("{:.4f}".format(lsm6ds33.get_accelerometer_g_forces()))
</code>```

Reference: Python: str.format()

EDIT: In cases where you have an array of values that you wish to string.format(), iterate over each value using a for loop and format them one at a time. Like so:

```<code># Assuming "lsm6ds33.get_accelerometer_g_forces()" returns the array [-0.5555, -0.78788, 0.878888]...

accelArray= lsm6ds33.get_accelerometer_g_forces() #temp variable to hold the array

for accelNumber in accelArray:
    print("{:.4f}".format(accelNumber))
</code>```

Given the array [-0.5555, -0.78788, 0.878888], the above loop will output:

```<code>-0.5555
-0.7879
0.8789
</code>```

Title: Limiting sensor reading into 4 decimal

Body:
I am a newbie to Python. I am fetching sensor readings and it has too many decimal places (x.xxxxxxxx)
I want to limit the reading into 4 decimals places (x.xxxx).

from altimu10v5.lsm6ds33 import LSM6DS33
from altimu10v5.lis3mdl import LIS3MDL
from altimu10v5.lps25h import LPS25H

from time import sleep

lsm6ds33 = LSM6DS33()
lsm6ds33.enable()

lps25h = LPS25H()
lps25h.enable()

lis3mdl = LIS3MDL()
lis3mdl.enable()

while True:

    #print(lsm6ds33.get_accelerometer_raw())
    print("{:.2f}".format.lsm6ds33.get_accelerometer_g_forces())

    sleep(0.4)

When I run this code I get the following error message:

" attribute error : ' builtin_function_or_method' object has no attribute 'lsm6ds33'

Body:
Try:

print("{:.4f}".format(lsm6ds33.get_accelerometer_g_forces()))

Reference: Python: str.format()

EDIT: In cases where you have an array of values that you wish to string.format(), iterate over each value using a for loop and format them one at a time. Like so:

# Assuming "lsm6ds33.get_accelerometer_g_forces()" returns the array [-0.5555, -0.78788, 0.878888]...

accelArray= lsm6ds33.get_accelerometer_g_forces() #temp variable to hold the array

for accelNumber in accelArray:
    print("{:.4f}".format(accelNumber))

Given the array [-0.5555, -0.78788, 0.878888], the above loop will output:

-0.5555
-0.7879
0.8789


问:
I want to check open applications before turn off my computer through java program
Actually I am working on a java based application which has a functionality to turn off my system on a specific time and it's working fine but, the requirement says that if any application is open then it should not be close before turn off my system must have to close all the open application manually.
I am unable to find out the solution.</p>

答: I have never tried this but it looks like you would have to use: Runtime.getRuntime().exec().  This seems to be a pretty good example of how to do this.</p>

ContentLicense: CC BY-SA 3.0


问:
easily refactoring many non-trivial "static library projects" to "dll projects"
I have 6 static library projects :-

```<code>- Math
- ECS             : depends on Math
- Utility         : depends on ECS
- Physics         : depends on Utility
- Graphics        : depends on Utility
- BaseGame        : depends on Physics and Graphics
- Some game (.exe): depends on BaseGame
(The "depends" here is transitive e.g. BaseGame also depends on ECS.)
</code>```

I succeeded in using 6 projects via "static libraries" technique.

Today, I heard that dynamic library can reduce compilation time (Let's not discuss whether this is true),

so I read these below links and successfully create a small demo.

https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=vs-2019 (official)

https://www.badprog.com/c-windows-creating-a-dynamic-link-library-dll   (alternative)

How do I build an import library (.lib) AND a DLL in Visual C++?  (troubleshooting)

Here is some code in my test demo :-

```<code>#ifdef SomeName1_EXPORTS
#define SomeMacro1 __declspec(dllexport)
#else
#define SomeMacro1 __declspec(dllimport)
#endif
SomeMacro1 void someFunction(int someParam);
</code>```

Now, it is exciting time to apply it to my real projects.

At the first step, I want to export all functions and classes of my 6 libraries.

I assume that I have to add SomeMacro1 (different for each project) to every function in all 6 projects (~100K lines), right?

That is a huge refactoring.

Are there any easier way?  Do I miss something very important?

Other notes :-

I want to switch my library projects back to static library easily (in case something go wrong).

I prefer a cross platform solution. (e.g. no pervasive refactoring need if I want to run in Linux later)

I prefer a solution that when I cut-and-paste a source file from one project to another, the cost of refactoring (in code) does not increase from normal.

(SomeMacro1 is currently specific to a project)

Similar question : How to convert a static library project into a dll project in VS2005

Bounty Reason

Thank Andriy Tylychko's answer that provides useful cautions and suggests that refactoring would be inevitably complicated,      but I still believe there are some easy ways to refactor my projects.

Now, I wish to change my library projects to dynamic libraries. (faster compilation)

Then when I ship my product, I will convert them back to static library. (better performance)

Edit: Bounty awards to Robert Andrzejuk because of his link in comment.
 (https://learn.microsoft.com/en-us/cpp/cpp/using-dllimport-and-dllexport-in-cpp-classes?view=vs-2019)

It may sound simple, but I have never known that I can __declspec(dllexport) at class level.

Although that is not my dream, it makes a lot of things easier.

答:
Strictly speaking, converting to DLLs will reduce mainly linking time, but you can notice (subtle in most cases) performance degradation because now "whole program optimisation" has much less room for optimisations, e.g. inlining functions across different binaries.

Dynamically linked libraries and statically linked libraries are quite different beasts, DLLs require much more attention. You need to carefully design their public API and define it accordingly (usually by macros like ones you presented). E.g. it's not recommended to use standard library types (and many others) in DLL public API that depend on particular type of C-runtime (like debug and release) - mainly it's about allocating memory in one binary and releasing in another that should be avoided. But this is not always a problem.

It doesn't make much sense to switch back and forth between static and dynamic libs.

Static libraries are usually much simpler and don't care about public API as everything is automatically accessible from outside. E.g. Math libraries are usually static as almost all functionality should be exported anyway and they (usually) don't have any complicated internal "business" logic.

Bigger libraries with "business" logic that you'd like to hide (e.g. to have more freedom to modify it) and with well defined public API bring long-term benefits. E.g. you can update only a small DLL instead of huge monolitic EXE if the API wasn't changed.

As it's hard to carefully plan ahead, the need to convert static lib to DLL (once) happens quite often as the project matures. In this case you don't need to export every class and function but to carefully select what exactly should be exported and ideally refactor existing API to better suit new reality. Luckily it seems you don't have any circular dependencies as they could add a lot of headache.

Refactoring inevitably becomes more complicated across DLLs, but this shouldn't be a big issue. If your lib looks like it should be a DLL - make it a DLL, advantages will be bigger than a disadvantage of a not so easy copy/pasting.

From your example, with very limited knowledge so it's pure guessing, it looks like only Physics and maybe Graphics should be DLLs, probably BaseGame too.

Body:
I have 6 static library projects :-

- Math
- ECS             : depends on Math
- Utility         : depends on ECS
- Physics         : depends on Utility
- Graphics        : depends on Utility
- BaseGame        : depends on Physics and Graphics
- Some game (.exe): depends on BaseGame
(The "depends" here is transitive e.g. BaseGame also depends on ECS.)

I succeeded in using 6 projects via "static libraries" technique.

Today, I heard that dynamic library can reduce compilation time (Let's not discuss whether this is true),

so I read these below links and successfully create a small demo.

https://learn.microsoft.com/en-us/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=vs-2019 (official)

https://www.badprog.com/c-windows-creating-a-dynamic-link-library-dll   (alternative)

How do I build an import library (.lib) AND a DLL in Visual C++?  (troubleshooting)

Here is some code in my test demo :-

#ifdef SomeName1_EXPORTS
#define SomeMacro1 __declspec(dllexport)
#else
#define SomeMacro1 __declspec(dllimport)
#endif
SomeMacro1 void someFunction(int someParam);

Now, it is exciting time to apply it to my real projects.

At the first step, I want to export all functions and classes of my 6 libraries.

I assume that I have to add SomeMacro1 (different for each project) to every function in all 6 projects (~100K lines), right?

That is a huge refactoring.

Are there any easier way?  Do I miss something very important?

Other notes :-

I want to switch my library projects back to static library easily (in case something go wrong).

I prefer a cross platform solution. (e.g. no pervasive refactoring need if I want to run in Linux later)

I prefer a solution that when I cut-and-paste a source file from one project to another, the cost of refactoring (in code) does not increase from normal.

(SomeMacro1 is currently specific to a project)

Similar question : How to convert a static library project into a dll project in VS2005

Bounty Reason

Thank Andriy Tylychko's answer that provides useful cautions and suggests that refactoring would be inevitably complicated,      but I still believe there are some easy ways to refactor my projects.

Now, I wish to change my library projects to dynamic libraries. (faster compilation)

Then when I ship my product, I will convert them back to static library. (better performance)

Edit: Bounty awards to Robert Andrzejuk because of his link in comment.
 (https://learn.microsoft.com/en-us/cpp/cpp/using-dllimport-and-dllexport-in-cpp-classes?view=vs-2019)

It may sound simple, but I have never known that I can __declspec(dllexport) at class level.

Although that is not my dream, it makes a lot of things easier.


问:
Mocking free function
I am stuck in a problem and can't seem to find the solution.

I am using VS2005 SP1 for compiling the code.

I have a global function:

```<code>A* foo();
</code>```

I have a mock class

```<code>class MockA : public A {
public:
    MOCK_METHOD0 (bar, bool());
    ...
};
</code>```

In the sources, it is accessed like this: foo()->bar(). I cannot find a way to mock this behavior. And I cannot change the sources, so the solution in google mock cook book is out of question.

Any help or pointers in the right direction will be highly appreciated. :)

答:
There are 2 options:

If you insist on using gmock, there's an "extension" for global mocking from apriorit: https://github.com/apriorit/gmock-global

It's rather limited, though - or at least I couldn't figure out in 5 minutes how to have side effects on a mocked call.

If you're willing to switch from gmock, then hippomocks has a very neat way of doing what you want.

Here's an example for mocking fopen, fclose and fgets for testing a member function which reads from a file using cstdio (streams are very inefficient):

```<code>TEST_CASE("Multi entry") {
    std::vector<std::string> files{"Hello.mp3", "World.mp3"};
    size_t entry_idx = 0;
    MockRepository mocks;
    mocks.OnCallFunc(fopen).Return(reinterpret_cast<FILE *>(1));
    mocks.OnCallFunc(fgets).Do(
        [&](char * buf, int n, FILE * f)->char *{
            if (entry_idx < files.size())
            {
                strcpy(buf, files[entry_idx++].c_str());
                return buf;
            }
            else
                return 0;
            }
        );
    mocks.OnCallFunc(fclose).Return(0);

    FileExplorer file_explorer;
    for (const auto &entry: files)
        REQUIRE_THAT(file_explorer.next_file_name(), Equals(entry.c_str()));
    REQUIRE_THAT(file_explorer.next_file_name(), Equals(""));
}
</code>```

Where the function under test looks like this:

```<code>string FileExplorer::next_file_name() {
    char entry[255];
    if (fgets((char *)entry, 255, _sorted_entries_in_dir) == NULL)
        return string();
    _current_idx++;
    if (_current_idx == _line_offsets.size())
        _line_offsets.push_back(static_cast<unsigned>(char_traits<char>::length(entry)) + _line_offsets.back());
    return string(entry);
}
</code>```

I'm using catch2 as the testing framework here, but I think hippomocks would work with Google's Testing framework as well (I recommend catch2, by the way, really easy to work with).

Title: Mocking free function

Body:
I am stuck in a problem and can't seem to find the solution.

I am using VS2005 SP1 for compiling the code.

I have a global function:

A* foo();

I have a mock class

class MockA : public A {
public:
    MOCK_METHOD0 (bar, bool());
    ...
};

In the sources, it is accessed like this: foo()->bar(). I cannot find a way to mock this behavior. And I cannot change the sources, so the solution in google mock cook book is out of question.

Any help or pointers in the right direction will be highly appreciated. :)

Body:
There are 2 options:

If you insist on using gmock, there's an "extension" for global mocking from apriorit: https://github.com/apriorit/gmock-global

It's rather limited, though - or at least I couldn't figure out in 5 minutes how to have side effects on a mocked call.

If you're willing to switch from gmock, then hippomocks has a very neat way of doing what you want.

Here's an example for mocking fopen, fclose and fgets for testing a member function which reads from a file using cstdio (streams are very inefficient):

TEST_CASE("Multi entry") {
    std::vector<std::string> files{"Hello.mp3", "World.mp3"};
    size_t entry_idx = 0;
    MockRepository mocks;
    mocks.OnCallFunc(fopen).Return(reinterpret_cast<FILE *>(1));
    mocks.OnCallFunc(fgets).Do(
        [&](char * buf, int n, FILE * f)->char *{
            if (entry_idx < files.size())
            {
                strcpy(buf, files[entry_idx++].c_str());
                return buf;
            }
            else
                return 0;
            }
        );
    mocks.OnCallFunc(fclose).Return(0);

    FileExplorer file_explorer;
    for (const auto &entry: files)
        REQUIRE_THAT(file_explorer.next_file_name(), Equals(entry.c_str()));
    REQUIRE_THAT(file_explorer.next_file_name(), Equals(""));
}

Where the function under test looks like this:

string FileExplorer::next_file_name() {
    char entry[255];
    if (fgets((char *)entry, 255, _sorted_entries_in_dir) == NULL)
        return string();
    _current_idx++;
    if (_current_idx == _line_offsets.size())
        _line_offsets.push_back(static_cast<unsigned>(char_traits<char>::length(entry)) + _line_offsets.back());
    return string(entry);
}

I'm using catch2 as the testing framework here, but I think hippomocks would work with Google's Testing framework as well (I recommend catch2, by the way, really easy to work with).


问:
Implementing search in mvc 4
I have a textbox where user types the string he needs to search. If the user enters only a single word string, then I am able to retrieve the correct data from database but if the user enters a multi-word string then my code fails.

I am using EntityFramework to get the data.

Here is my code to get the data using a single word string.

```<code>public ActionResult SearchResult(string search)
{
   var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(search) || oh.Description.Contains(search));
   List<Mobiles> prod = new List<Mobiles>();
   foreach (var p in j)
   {
       Mobiles Mob = new Mobiles();
       Mob.Description = p.Description;
       Mob.ImgUrl = p.Url;
       Mob.MobileName = p.MobileName;
       Mob.Price = Convert.ToString(p.Price);
       Mob.SlNo = p.SlNo;
       prod.Add(Mob);
   }

   return View("~/Views/Product/Index.cshtml", prod);
}
</code>```

I tried breaking the string into single word using split but could not get the correct data.

```<code>string str = null;
string[] strArr = null;
int count = 0;
str = //UserInput;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
</code>```

答:
```<code>string str = null;
        string[] strArr = null;
        int count = 0;
        str = search;
        char[] splitchar = { ' ' };
        strArr = str.Split(splitchar);
        for (count = 0; count <= strArr.Length - 1; count++)
        {
            string i = strArr[count];
            var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(i) || oh.Description.Contains(i));
            //MessageBox.Show(strArr[count]);
            foreach (var p in j)
            {
                Mobiles Mob = new Mobiles();
                Mob.Description = p.Description;
                Mob.ImgUrl = p.Url;
                Mob.MobileName = p.MobileName;
                Mob.Price = Convert.ToString(p.Price);
                Mob.SlNo = p.SlNo;
                prod.Add(Mob);
            }
        }
</code>```

as I help you fix the problem - this is the final code

Title: Implementing search in mvc 4

Body:
I have a textbox where user types the string he needs to search. If the user enters only a single word string, then I am able to retrieve the correct data from database but if the user enters a multi-word string then my code fails.

I am using EntityFramework to get the data.

Here is my code to get the data using a single word string.

public ActionResult SearchResult(string search)
{
   var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(search) || oh.Description.Contains(search));
   List<Mobiles> prod = new List<Mobiles>();
   foreach (var p in j)
   {
       Mobiles Mob = new Mobiles();
       Mob.Description = p.Description;
       Mob.ImgUrl = p.Url;
       Mob.MobileName = p.MobileName;
       Mob.Price = Convert.ToString(p.Price);
       Mob.SlNo = p.SlNo;
       prod.Add(Mob);
   }

   return View("~/Views/Product/Index.cshtml", prod);
}

I tried breaking the string into single word using split but could not get the correct data.

string str = null;
string[] strArr = null;
int count = 0;
str = //UserInput;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);

Body:
string str = null;
        string[] strArr = null;
        int count = 0;
        str = search;
        char[] splitchar = { ' ' };
        strArr = str.Split(splitchar);
        for (count = 0; count <= strArr.Length - 1; count++)
        {
            string i = strArr[count];
            var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(i) || oh.Description.Contains(i));
            //MessageBox.Show(strArr[count]);
            foreach (var p in j)
            {
                Mobiles Mob = new Mobiles();
                Mob.Description = p.Description;
                Mob.ImgUrl = p.Url;
                Mob.MobileName = p.MobileName;
                Mob.Price = Convert.ToString(p.Price);
                Mob.SlNo = p.SlNo;
                prod.Add(Mob);
            }
        }

as I help you fix the problem - this is the final code


问:
Send Mail to a user if count of open issues greater a specific limit
how could i create a workflow which on every change of the current issue user checks the total amount of open issues for this user and if the amount is greater then lets say 5 the user gets a mail with a little warning message?

I guess this here is close to my topic, but only close:
https://youtrack-support.jetbrains.com/hc/en-us/community/posts/206582955-How-to-count-user-s-issues-

All our users have a mail in youtrack, the workflow should only work for one usergroup/project however.

Thank you and best regards

答:
The How to count user's issues? illustrates the approach that valid for old workflow.
For the new JavaScript workflow, I suggest you use the search method for getting all open issues assigned to the required user. Then, you can use the user.notify method to send an email to this user.
You can find common information about JavaScript workflow in the JavaScript Workflow Quick Start Guide article. I hope this helps.
Here is an example that illustrates how to send a message with the assigned issues count to the user:

var entities = require('@jetbrains/youtrack-scripting-api/entities');
var search = require('@jetbrains/youtrack-scripting-api/search');

exports.rule = entities.Issue.onChange({
  title: 'Assignee count',
  guard: function(ctx) {
    return ctx.issue.isChanged(ctx.Assignee) && ctx.issue.fields.Assignee;
  },
  action: function(ctx) {
    var issue = ctx.issue;

    var user = issue.fields.Assignee;
    var query = 'for: ' + user.login + ' #Unresolved';
    var assignedToUser = search.search(issue.project, query, ctx.currentUser);

    var count = assignedToUser.size;
    var subj = 'Attention!';
    var body = 'You have ' + count + ' assigned issues';
    user.notify(subj, body);
  },
  requirements: {
    Assignee: {
      type: entities.User.fieldType
    }
  }
});
```


问:
using python how to find a element and print its index of csv file
I have a csv file with below matrix like information. By giving it as a input in that there is a element -1. I need a code to find the index of -1. Please help me in this.
The below data is the csv file input to python:

答:
Try this:</p>

```<code>import pandas as pd
csv = pd.read_csv(r'C:/.../file.csv', ';')
index = []

for i,r in csv.iterrows():
      index.append(i)

print(index[-1])
</code>```

Body:
Try this:

import pandas as pd
csv = pd.read_csv(r'C:/.../file.csv', ';')
index = []

for i,r in csv.iterrows():
      index.append(i)

print(index[-1])


问:
Dynamics AX 2009: Add a field to InventJournalTrans, propagate to InventTrans
I need to add an additional field to InventJournalTrans, that after posting will show up in the InventTrans table.  The field is a reference column to a record in another table.  What method(s) do I need to modify to make this behavior happen?

Currently, I have already added the fields to both tables and modified the Form to allow the user to enter and save the new field.  I just can't seem to find the bottom of the rabbit hole on where the actual posting to InventTrans is occurring.

Ideally, it should just be a:

inventTrans.ReasonRefRecId = inventJournalTrans.ReasonRefRecId;

assignment statement before the

inventTrans.insert();

call. Anybody have a clue on where this is at?

答:
The link above does contain the solution -- I have included the code from that page in case that page disappears or no longer becomes available.  Thanks to gl00mie for answering on that site and providing this answer.

You should create a new InventMovement method like this:

```<code>public MyNewFieldType myNewField()
{
    return MyNewFieldType::DefaultValue; // suppose your new field is an enum
}
</code>```

Then modify \Classes\InventMovement\initInventTransFromBuffer

```<code>void initInventTransFromBuffer(InventTrans _inventTrans, InventMovement _movement_orig)
{
    // ... append this line to the end of whatever else is already in this method
    _inventTrans.MyNewField            = this.myNewField();
}
</code>```

And finally overload the new method in the InventMov_Journal class:

```<code>public MyNewFieldType myNewField()
{
    return inventJournalTrans.MyNewField;
}
</code>```

Body:
The link above does contain the solution -- I have included the code from that page in case that page disappears or no longer becomes available.  Thanks to gl00mie for answering on that site and providing this answer.

You should create a new InventMovement method like this:

public MyNewFieldType myNewField()
{
    return MyNewFieldType::DefaultValue; // suppose your new field is an enum
}

Then modify \Classes\InventMovement\initInventTransFromBuffer

void initInventTransFromBuffer(InventTrans _inventTrans, InventMovement _movement_orig)
{
    // ... append this line to the end of whatever else is already in this method
    _inventTrans.MyNewField            = this.myNewField();
}

And finally overload the new method in the InventMov_Journal class:

public MyNewFieldType myNewField()
{
    return inventJournalTrans.MyNewField;
}


问:
How to add data to a hash reference
I am having issues appending data to an array of hashes.  Instead of appendibg the data into the hash it is creating a new hash.

```<code>$json_data =
{
    'site_data' =>
     {
        'urldata' =>
        [
            {
                'URL' => "$filedata{'filename'}"
            }
        ],
    }
}
my %format =('Format'=>'ZIP');
push ($json_data->{'site_data'}->{'urldata'},\%format);
</code>```

What I am expecting is.

```<code>'urldata':
 [
    {
        'URL':"www.espn.com",
        'Format':"ZIP"
    }

 ],
</code>```

What I am getting is.

```<code>'urldata':
 [
    {
        'URL':"www.espn.com"
    },
    {
        'Format':"ZIP"
    }

 ],
</code>```

答:
There are a few things going on here.

Firstly, this syntax causes problems:

```<code>push ($json_data->{'site_data'}->{'urldata'},\%format);
</code>```

This uses an experimental feature that was added in Perl 5.14 and removed again in 5.24. So please don't use that. You need to explicitly deference your array reference (by putting @{ ... } around the expression.

```<code>push (@{ $json_data->{'site_data'}->{'urldata'} }, \%format);
</code>```

But that doesn't get you any closer. That just gets you the same, broken, solution working on any version of Perl :-)

The push() function only works on arrays. In your case, you're using it on the array (reference) stored in the urldata key of your hash. But you don't want to push() a new element onto that array (as that gives you the incorrect result that you're currently seeing). You want to access the existing, first hash that's stored in the array and add a key/value pair to that.

The first element of your urldata array is given by:

```<code>$json_data->{'site_data'}->{'urldata'}->[0]; # The '0' gives the first element.
</code>```

That is a hash reference, so you can add values to the hash in exactly the same way as you would for any other hash reference.

```<code>$json_data->{'site_data'}->{'urldata'}->[0]->{'Format'} = 'ZIP';
</code>```

Of course, you can tidy up this code by removing the quote marks around hash keys:

```<code>$json_data->{site_data}->{urldata}->[0]->{Format} = 'ZIP';
</code>```

And arrows between indexing brackets are always optional:

```<code>$json_data->{site_data}{urldata}[0]{Format} = 'ZIP';
</code>```

Title: How to add data to a hash reference

Body:
I am having issues appending data to an array of hashes.  Instead of appendibg the data into the hash it is creating a new hash.

$json_data =
{
    'site_data' =>
     {
        'urldata' =>
        [
            {
                'URL' => "$filedata{'filename'}"
            }
        ],
    }
}
my %format =('Format'=>'ZIP');
push ($json_data->{'site_data'}->{'urldata'},\%format);

What I am expecting is.

'urldata':
 [
    {
        'URL':"www.espn.com",
        'Format':"ZIP"
    }

 ],

What I am getting is.

'urldata':
 [
    {
        'URL':"www.espn.com"
    },
    {
        'Format':"ZIP"
    }

 ],

Body:
There are a few things going on here.

Firstly, this syntax causes problems:

push ($json_data->{'site_data'}->{'urldata'},\%format);

This uses an experimental feature that was added in Perl 5.14 and removed again in 5.24. So please don't use that. You need to explicitly deference your array reference (by putting @{ ... } around the expression.

push (@{ $json_data->{'site_data'}->{'urldata'} }, \%format);

But that doesn't get you any closer. That just gets you the same, broken, solution working on any version of Perl :-)

The push() function only works on arrays. In your case, you're using it on the array (reference) stored in the urldata key of your hash. But you don't want to push() a new element onto that array (as that gives you the incorrect result that you're currently seeing). You want to access the existing, first hash that's stored in the array and add a key/value pair to that.

The first element of your urldata array is given by:

$json_data->{'site_data'}->{'urldata'}->[0]; # The '0' gives the first element.

That is a hash reference, so you can add values to the hash in exactly the same way as you would for any other hash reference.

$json_data->{'site_data'}->{'urldata'}->[0]->{'Format'} = 'ZIP';

Of course, you can tidy up this code by removing the quote marks around hash keys:

$json_data->{site_data}->{urldata}->[0]->{Format} = 'ZIP';

And arrows between indexing brackets are always optional:

$json_data->{site_data}{urldata}[0]{Format} = 'ZIP';


问:
Load CSV and convert to date
I've imported array from csv with data %d.%m.%Y but R reads as %Y.%m.%d. Which function should I use? Here are some my attempts but not succesfull    </p>

```<code>x <- c$Date
fast_strptime(x, format = "%d.%m.%Y")

parse_date(x, format = "%d.%m.%Y")

 cols(
    x = col_date(format = "%d.%m.%Y")
  )
</code>```

答:
To change the format of Date r uses asDate just like asType is used :-

```<code>x<- as.Date(dates,
  format = "%m/%d/%y")
</code>```

Title: Load CSV and convert to date

Body:
I've imported array from csv with data %d.%m.%Y but R reads as %Y.%m.%d. Which function should I use? Here are some my attempts but not succesfull

x <- c$Date
fast_strptime(x, format = "%d.%m.%Y")

parse_date(x, format = "%d.%m.%Y")

 cols(
    x = col_date(format = "%d.%m.%Y")
  )

Body:
To change the format of Date r uses asDate just like asType is used :-

x<- as.Date(dates,
  format = "%m/%d/%y")


问:
Could not find Windows Runtime type 'Windows.Web.UI.WebViewControlSettings'
We're trying to use the WebView control in a WPF app, but get the above exception at run time.

According to everything I've read, including this SO answer, we should only need .NET 4.6.2 and the latest Windows updates.

However, we are using .NET 4.7.2, and have all the latest Windows updates. I'm using Win7, but other developers with Win10 are also having problems.

I tried installing the Microsoft.Toolkit.Wpf.UI.Controls Nuget package, but that didn't help.

Anyone any ideas what we need to do to use this control? Thanks

Update - Ah, just found this MSDN page that implies the control is only available for Win10. Anyone able to confirm or deny this? More to the point, if it is Win10 only, is there something that supports HTML5 that works on Win7? The standard WebBrowser control doesn't support HTML5.

答:
Anyone able to confirm or deny this?

I can confirm that using the WebView control in a WPF application requires the application to run on the April 2018 (version 18.03) release of Windows 10 or later. It won't work on Windows 7.

is there something that supports HTML5 that works on Win7?

I am afraid there is no built-in control available. If your users are still on Windows 7, you may want to look for a third-party browser control such as for example CefSharp.


问:
IBM MQ and .NET Core application
I am writing a .NET Core (2.1) Windows Service which will be listening for messages from IBM MQ.

Could anyone point me to a link to a repository with an example, article or at least decent documentation?

答:
Please check this other SO post explaining how to obtain the IBM MQ .NET client libraries.

That being said, IBM has a nice page on Getting started with IBM MQ classes for .NET and IBM MQ samples.

Title: IBM MQ and .NET Core application


问:
JQuery, load, parse, sum and display from external page
I'm trying to load an external page which contains a table like this:

```<code><table id="uniquedatatable">
 <tr class="row">
  <td class="num col"><a> 1 </a></td>
  <td class="str col"><a>Text</a></td>
  <td class="num col"><a>  7</a></td>
  <td class="str col"><a>Text</a></td>
 </tr>
</table>
</code>```

*Notice the whitespace's in the class names of the td's and around the numbers (1,7).

I need to find all cell's (td's) with class "num col", get the numeric value between the a tag'a and sum all the values. Last I need to display this value on my own page.

So the result I would get from the above table should be: 1 + 7 = 8.

I've gotten this far:

```<code> <script src="http://code.jquery.com/jquery-1.5.1.min.js" type="text/javascript"></script>

 <p id="result"></p>

 <script type="text/javascript">
   var url = "http://someurl";
   var sum = 0;

   $('#result').load('url #uniquedatatable tr td.num col a', function() {
     sum += Number($(this).text());
   });

   _gel('result').innerHTML = sum;
 </script>
</code>```

Realizing something is wrong (close to being correct I hope :)), I need help connecting the "dots" here so that I can:

Calculate the sum (this is the "big" problem :S)

Write the result back.

Any help is appreciated.

答:
Try this:</p>

```<code><script type="text/javascript">
        var url = "<LOCAL_URL>";
        var sum = 0;
        $('#result').load(url, function() {
            $("#uniquedatatable tr td.num.col a", "#result" ).each(function(){
                sum += parseInt($(this).text(), 10);
            });
                     _gel('result').innerHTML = sum;

        });
        </script>
</code>```

Body:
I'm trying to load an external page which contains a table like this:

   1
  Text
    7
  Text

*Notice the whitespace's in the class names of the td's and around the numbers (1,7).

I need to find all cell's (td's) with class "num col", get the numeric value between the a tag'a and sum all the values. Last I need to display this value on my own page.

So the result I would get from the above table should be: 1 + 7 = 8.

I've gotten this far:

Realizing something is wrong (close to being correct I hope :)), I need help connecting the "dots" here so that I can:

Calculate the sum (this is the "big" problem :S)

Write the result back.

Any help is appreciated.

Body:
Try this:

<script type="text/javascript">
        var url = "<LOCAL_URL>";
        var sum = 0;
        $('#result').load(url, function() {
            $("#uniquedatatable tr td.num.col a", "#result" ).each(function(){
                sum += parseInt($(this).text(), 10);
            });
                     _gel('result').innerHTML = sum;

        });
        </script>


问:
What happens on syslog-ng if no transport is configured, but UDP port is set?
By default, as stated in the documentation of syslog-ng, the default Transport Protocol used by syslog-ng is TCP.,

If I don't configure the Transport Protocol, but instead I configure PORT 514 which is the default UDP port, what will happen? Will the communications go over TCP or UDP?

答: The syslog() and network() drivers of syslog-ng use TCP by default. Setting the port() option to 514 without specifying transport() means 514/tcp.


问:
How can I get a List of subelements from a subdictionary?
I want to get a list of subelements from a subdictionary

I have this:

```<code>Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;
</code>```

And I want something like this (Fetch all InstanceLog-Lists from the subdictinary in one big list.):

```<code>List<InstanceLog> logList = GetValues(dic);
</code>```

I have tried something like this but it don't work:

```<code>List<InstanceLog> logList = GetFetchtedList()
  .Select(x => x.Value.ToList())
  .Cast<InstanceLog>()
  .ToList()
</code>```

Thanks a lot for the help!

答:
You have to flatten dic twice:

```<code>Dictionary<string, Dictionary<string, List<InstanceLog>>> dic = ...;

List<InstanceLog> logList = dic
  .SelectMany(pair => pair.Value) // Inner Dictionaries
  .SelectMany(pair => pair.Value) // Inner Lists
  .ToList();                      // Materialized as one big list
</code>```

Body:
I want to get a list of subelements from a subdictionary

I have this:

Dictionary<string, Dictionary<string, List<InstanceLog>>> dic;

And I want something like this (Fetch all InstanceLog-Lists from the subdictinary in one big list.):

List<InstanceLog> logList = GetValues(dic);

I have tried something like this but it don't work:

List<InstanceLog> logList = GetFetchtedList()
  .Select(x => x.Value.ToList())
  .Cast<InstanceLog>()
  .ToList()

Thanks a lot for the help!

Body:
You have to flatten dic twice:

Dictionary<string, Dictionary<string, List<InstanceLog>>> dic = ...;

List<InstanceLog> logList = dic
  .SelectMany(pair => pair.Value) // Inner Dictionaries
  .SelectMany(pair => pair.Value) // Inner Lists
  .ToList();                      // Materialized as one big list


问:
sort string date and sort it
I would like to use sort my list of article by date (dd/mm/yyyy).
Dates are String.

```<code>public class ArticleComparator implements Comparator<Article> {

    @Override
    public int compare(Article a1, Article a2) {
        // TODO Auto-generated method stub
        int result = a1.getDate().compareTo(a2.getDate());
        if(result == 0)
            result = a1.getAuteur().getPseudo().compareTo(a2.getAuteur().getPseudo());
    return result;
}
</code>```

```<code>public class ReseauSocial {

    private HashMap<String, CompteUtilisateur> utilisateurs;
    private List <Article> article;

    public ReseauSocial() {
    }

    public void tirerArticles() {
        Collections.sort(article, new ArticleComparator());
    }

    public void connecter(String pseudo, String mdp) {
    }
}
</code>```

But can you help me to sort dates from newest to oldest

Thank you for your answer but it does not works.. That is I obtain after modifying my code

```<code>public class MainClass {

    static List<Article> articles = new ArrayList<>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Article a1 = new Article ("article1", "TP1", true, "01/02/2018");
        Article a2 = new Article ("article2", "TP2", true, "01/02/2019");
        articles.add(a1);
        articles.add(a2);

        ReseauSocial rsc = new ReseauSocial(articles);
        rsc.tirerArticles();

        for(int i = 0; i<articles.size(); i++) {
            System.out.print("Articles : "+ articles.get(i).getDate().toString()+"\n");

        }

    }

}
</code>```

```<code>Article 1 : Fri Feb 01 00:00:00 CET 2019
Articles 2 : Thu Feb 01 00:00:00 CET 2018
Articles : 01/02/2018
Articles : 01/02/2019
</code>```

答:
If you use an already comparable data type (a class that implements Comparable),

then you can just return the result of its own compareTo method:

```<code>public int compare(Article a1, Article a2) {
    // define a suitable formatter
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    // parse both dates
    LocalDate ldOne = LocalDate.parse(a1.getDate(), dtf);
    LocalDate ldTwo = LocalDate.parse(a2.getDate(), dtf);
    // compare the dates and return the result
    return ldOne.compareTo(ldTwo);
}
</code>```

Please note that using Strings for dates is generally not a good practice. Consider refactoring your class attributes that represent dates to have a suitable data type.

Title: sort string date and sort it

Body:
I would like to use sort my list of article by date (dd/mm/yyyy).
Dates are String.

public class ArticleComparator implements Comparator
 {

    @Override
    public int compare(Article a1, Article a2) {
        // TODO Auto-generated method stub
        int result = a1.getDate().compareTo(a2.getDate());
        if(result == 0)
            result = a1.getAuteur().getPseudo().compareTo(a2.getAuteur().getPseudo());
    return result;
}

public class ReseauSocial {

    private HashMap<String, CompteUtilisateur> utilisateurs;
    private List
 article;

    public ReseauSocial() {
    }

    public void tirerArticles() {
        Collections.sort(article, new ArticleComparator());
    }

    public void connecter(String pseudo, String mdp) {
    }
}

But can you help me to sort dates from newest to oldest

Thank you for your answer but it does not works.. That is I obtain after modifying my code

public class MainClass {

    static List
 articles = new ArrayList<>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Article a1 = new Article ("article1", "TP1", true, "01/02/2018");
        Article a2 = new Article ("article2", "TP2", true, "01/02/2019");
        articles.add(a1);
        articles.add(a2);

        ReseauSocial rsc = new ReseauSocial(articles);
        rsc.tirerArticles();

        for(int i = 0; i<articles.size(); i++) {
            System.out.print("Articles : "+ articles.get(i).getDate().toString()+"\n");

        }

    }

}

Article 1 : Fri Feb 01 00:00:00 CET 2019
Articles 2 : Thu Feb 01 00:00:00 CET 2018
Articles : 01/02/2018
Articles : 01/02/2019

Body:
If you use an already comparable data type (a class that implements Comparable),

then you can just return the result of its own compareTo method:

public int compare(Article a1, Article a2) {
    // define a suitable formatter
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    // parse both dates
    LocalDate ldOne = LocalDate.parse(a1.getDate(), dtf);
    LocalDate ldTwo = LocalDate.parse(a2.getDate(), dtf);
    // compare the dates and return the result
    return ldOne.compareTo(ldTwo);
}

Please note that using Strings for dates is generally not a good practice. Consider refactoring your class attributes that represent dates to have a suitable data type.


问:
how to get the column name of the greatest value by using greatest function postgresql?
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

```<code>select greatest(col1,col2,col3,col4) from mytable;
</code>```

But I need to know the column name of the greatest value.

答:
The other answers are good and I definitely agree with Gordon that this smells of a data model issue.  However, you can (ab)use jsonb to do this without having to retype the names of all of your columns, if you have a unique key in your table.

```<code>create table test (id int, col1 int, col2 int, col3 int);
insert into test values (1, 1, 2, 3), (2, 6, 5, 4), (3, 7, 9, 8);

select distinct on (id)
  id,
  col,
  val
from (
    select id,
           col,
           val
    from test
    join lateral to_jsonb(test) s1(js) on true
    join lateral jsonb_each(js) s2(col, val) on true
) sub where col != 'id'
order by id, val desc;
 id | col  | val
----+------+-----
  1 | col3 | 3
  2 | col1 | 6
  3 | col2 | 9
(3 rows)
</code>```

Basically, create jsonb for each row, which will be something like {"id": 1, "col1": 1, "col2": 2, "col3": 3} and then split it out into keys and values using jsonb_each.  The result would be something like this:

```<code> id | col  | val
----+------+-----
  1 | id   | 1
  1 | col1 | 1
  1 | col2 | 2
  1 | col3 | 3
  2 | id   | 2
  2 | col1 | 6
  2 | col2 | 5
  2 | col3 | 4
...
</code>```

From there, remove the id rows and find the greatest val per id using distinct on.

You can use the same technique on any table, you would just have to change the name of the id column, if it's not id.  Here's another example:

```<code>create table test2 (id int, t1 timestamp, t2 timestamp);
insert into test2 values (1, '2019-02-01T00:00:00', '2019-01-01T00:00:00');

select distinct on (id)
  id,
  col,
  val
from (
    select id,
           col,
           val
    from test2
    join lateral to_jsonb(test2) s1(js) on true
    join lateral jsonb_each(js) s2(col, val) on true
) sub where col != 'id'
order by id, val desc;
 id | col |          val
----+-----+-----------------------
  1 | t1  | "2019-02-01T00:00:00"
(1 row)
</code>```

Body:
I have four columns in my table which are col1,col2,col3,col4.
I can find the greatest value by using

select greatest(col1,col2,col3,col4) from mytable;

But I need to know the column name of the greatest value.

Body:
The other answers are good and I definitely agree with Gordon that this smells of a data model issue.  However, you can (ab)use jsonb to do this without having to retype the names of all of your columns, if you have a unique key in your table.

create table test (id int, col1 int, col2 int, col3 int);
insert into test values (1, 1, 2, 3), (2, 6, 5, 4), (3, 7, 9, 8);

select distinct on (id)
  id,
  col,
  val
from (
    select id,
           col,
           val
    from test
    join lateral to_jsonb(test) s1(js) on true
    join lateral jsonb_each(js) s2(col, val) on true
) sub where col != 'id'
order by id, val desc;
 id | col  | val
----+------+-----
  1 | col3 | 3
  2 | col1 | 6
  3 | col2 | 9
(3 rows)

Basically, create jsonb for each row, which will be something like {"id": 1, "col1": 1, "col2": 2, "col3": 3} and then split it out into keys and values using jsonb_each.  The result would be something like this:

 id | col  | val
----+------+-----
  1 | id   | 1
  1 | col1 | 1
  1 | col2 | 2
  1 | col3 | 3
  2 | id   | 2
  2 | col1 | 6
  2 | col2 | 5
  2 | col3 | 4
...

From there, remove the id rows and find the greatest val per id using distinct on.

You can use the same technique on any table, you would just have to change the name of the id column, if it's not id.  Here's another example:

create table test2 (id int, t1 timestamp, t2 timestamp);
insert into test2 values (1, '2019-02-01T00:00:00', '2019-01-01T00:00:00');

select distinct on (id)
  id,
  col,
  val
from (
    select id,
           col,
           val
    from test2
    join lateral to_jsonb(test2) s1(js) on true
    join lateral jsonb_each(js) s2(col, val) on true
) sub where col != 'id'
order by id, val desc;
 id | col |          val
----+-----+-----------------------
  1 | t1  | "2019-02-01T00:00:00"
(1 row)


问:
Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference (Fragment)
This is the java file code for fragment:

```<code>@SuppressLint({"NewApi", "ResourceAsColor"})
public void createCardView(String id, String date, final String order) {
    flag = true;
    cardView = new CardView(context);
    cardView.setLayoutParams(layoutParamsCard);
    cardView.setElevation(5);
    relativeLayout = new RelativeLayout(context);
    relativeLayout.setLayoutParams(layoutParamsRelative);
    textView = new TextView(context);
    orderID = new TextView(context);
    textView.setLayoutParams(layoutParamsTextView);
    textView.setText("Order ID:");
    textView.setTextColor(Color.parseColor("#1e1e1e"));
    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    orderID.setLayoutParams(layoutParamsTextViewID);
    orderID.setText(id);
    orderID.setTextColor(Color.parseColor("#646464"));
    orderID.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    orderDate = new TextView(context);
    orderDate.setText(date);
    orderDate.setLayoutParams(layoutParamsOrderDate);
    viewOrder = new Button(context);
    viewOrder.setText("View Order");
    viewOrder.setTextColor(Color.parseColor("#ffffff"));
    viewOrder.setBackgroundColor(Color.parseColor("#326432"));
    viewOrder.setLayoutParams(layoutParamsViewOrder);
    viewOrder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LayoutInflater inflater = getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.view_order_dialog,null);
            dialogBuilder.setView(dialogView);
            final TextView orderTextView = dialogView.findViewById(R.id.orderTextView);
            final Button close = dialogView.findViewById(R.id.close);
            orderTextView.setText(order);
            dialogBuilder.setTitle("Order ID: " + orderID.getText().toString());
            final AlertDialog alertDialog = dialogBuilder.create();
            alertDialog.show();
        }
    });
    cardView.addView(relativeLayout);
    relativeLayout.addView(textView);
    relativeLayout.addView(orderID);
    relativeLayout.addView(viewOrder);
    relativeLayout.addView(orderDate);
    gridLayout.addView(cardView);
}
</code>```

I am not able to launch custom dialogview from fragment. It crashes the app when i open that fragment. I am using this code to create cards dynamically and creating an OnClickListner for each card.

答:
In My Case this type of error is showing in case of displaying Dialog on the RecyclerView item click.

1)Define Activity in your class like this:-

```<code>       // Initialize activity
       Activity activity;

      // define activity of this class//
        activity=EditFieldsActivity.this;
</code>```

2)Pass this activity in your Adapter Like this:-

```<code>EditFieldAdapter adapter = new EditFieldAdapter(getApplicationContext(),data,activity);
recyclerFieldManagement.setAdapter(adapter);
</code>```

3)And Get This activity in your adapter and use activity for showing Dialog as:-

```<code>private Activity activity;
    public EditFieldAdapter(Context applicationContext, List<FieldDetails> data, Activity activity) {
        this.ctx=applicationContext;
        this.data=data;
        this.activity=activity;
    }
</code>```

Hope this will help you.Thanks...

Body:
This is the java file code for fragment:

@SuppressLint({"NewApi", "ResourceAsColor"})
public void createCardView(String id, String date, final String order) {
    flag = true;
    cardView = new CardView(context);
    cardView.setLayoutParams(layoutParamsCard);
    cardView.setElevation(5);
    relativeLayout = new RelativeLayout(context);
    relativeLayout.setLayoutParams(layoutParamsRelative);
    textView = new TextView(context);
    orderID = new TextView(context);
    textView.setLayoutParams(layoutParamsTextView);
    textView.setText("Order ID:");
    textView.setTextColor(Color.parseColor("#1e1e1e"));
    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    orderID.setLayoutParams(layoutParamsTextViewID);
    orderID.setText(id);
    orderID.setTextColor(Color.parseColor("#646464"));
    orderID.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    orderDate = new TextView(context);
    orderDate.setText(date);
    orderDate.setLayoutParams(layoutParamsOrderDate);
    viewOrder = new Button(context);
    viewOrder.setText("View Order");
    viewOrder.setTextColor(Color.parseColor("#ffffff"));
    viewOrder.setBackgroundColor(Color.parseColor("#326432"));
    viewOrder.setLayoutParams(layoutParamsViewOrder);
    viewOrder.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LayoutInflater inflater = getLayoutInflater();
            final View dialogView = inflater.inflate(R.layout.view_order_dialog,null);
            dialogBuilder.setView(dialogView);
            final TextView orderTextView = dialogView.findViewById(R.id.orderTextView);
            final Button close = dialogView.findViewById(R.id.close);
            orderTextView.setText(order);
            dialogBuilder.setTitle("Order ID: " + orderID.getText().toString());
            final AlertDialog alertDialog = dialogBuilder.create();
            alertDialog.show();
        }
    });
    cardView.addView(relativeLayout);
    relativeLayout.addView(textView);
    relativeLayout.addView(orderID);
    relativeLayout.addView(viewOrder);
    relativeLayout.addView(orderDate);
    gridLayout.addView(cardView);
}

I am not able to launch custom dialogview from fragment. It crashes the app when i open that fragment. I am using this code to create cards dynamically and creating an OnClickListner for each card.

Body:
In My Case this type of error is showing in case of displaying Dialog on the RecyclerView item click.

1)Define Activity in your class like this:-

       // Initialize activity
       Activity activity;

      // define activity of this class//
        activity=EditFieldsActivity.this;

2)Pass this activity in your Adapter Like this:-

EditFieldAdapter adapter = new EditFieldAdapter(getApplicationContext(),data,activity);
recyclerFieldManagement.setAdapter(adapter);

3)And Get This activity in your adapter and use activity for showing Dialog as:-

private Activity activity;
    public EditFieldAdapter(Context applicationContext, List<FieldDetails> data, Activity activity) {
        this.ctx=applicationContext;
        this.data=data;
        this.activity=activity;
    }

Hope this will help you.Thanks...


问:
Bootstrap editable accordion name
I'm trying to build a Bootstrap accordion using Knockout foreach with editable header. When double clicking on the accordion name, the name should become an input box (probably not the best idea to do this) that should save the change on enter click or click outside that area (changing the focus). My problem is that when a user double clicks on the name to edit it, the panel expand and collapses and some find it difficult to edit.

```<code><div class="col-lg-12 panel m-t-5 panel-group" id="mAccordion">
    <div class="panel panel-default" data-bind="foreach:{ data: selectedItemM, as: 'mod'}">
        <div class="panel-heading ui-sortable-handle" style="border-color:black; background-color:black; margin-bottom: 2px" data-bind="visible:!IsDeleted()">
            <i class="fas fa-trash-alt pull-right" style="color:red; cursor:pointer" data-bind="event:{'click':$root.deleteM}"></i>
            <a class="accordion-toggle accordion-inner" style="color:#fff; text-decoration:none;cursor:pointer;" data-bind="attr:{href:'#mPanelBody_'+Id}" data-toggle="collapse" data-parent="#modAccordion">
                <h4 class="panel-title" data-bind="attr:{id:'header_'+Id}, text: Name, event:{'dblclick':$root.editM}" style="color:white;cursor: pointer; width:30%"></h4>
                <input type="text" class="panel-title" data-bind="attr:{id:'input_'+Id}, textInput: Name,valueUpdate: 'afterkeydown', event:{keypress:$root.renameM}" style="color:white;display:none; background-color:black; width:30%;" />
            </a>
        </div>
        <div class="panel-collapse accordion-sub collapse" data-bind="attr:{id:'mPanelBody_'+Id}, visible:!IsDeleted()"></div>
    </div>
</div>
</code>```

It is possible to make the name of the accordion just to be editable on double click (or simple click) without doing anything to the accordion (expand or collapse) and expand or collapse it just when clicking outside the name area, on the empty space from the header?

答:
You can use the hasFocus binding to detect and set focus on the input. You can use event.stopPropagation in your click handlers to prevent the click event from bubbling up to the accorion's toggle click target. Here's an example that shows:

Clicking on the text (green border) in the header starts editing it.

Removing focus on the edit input puts back the header

Clicking outside the text in the heading (blue border) toggles the accordion.

const expanded = ko.observable(false);

const focus = ko.observable(false);
const title = ko.observable("Heading");

const startEdit = function(data, event) {
  focus(true);
  event.stopPropagation();
};

const toggle = function() {
  if (!focus()) {
    expanded(!expanded());
  }
};

ko.applyBindings({ expanded, toggle, focus, title, startEdit });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2 {
 border: 1px solid blue;
 padding: .5rem;
}

span {
 border: 1px solid green;
}</code>```

  <input type="text" data-bind="textInput: title, visible: focus, hasFocus: focus, clickBubble: false">

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Title: Bootstrap editable accordion name

Body:
I'm trying to build a Bootstrap accordion using Knockout foreach with editable header. When double clicking on the accordion name, the name should become an input box (probably not the best idea to do this) that should save the change on enter click or click outside that area (changing the focus). My problem is that when a user double clicks on the name to edit it, the panel expand and collapses and some find it difficult to edit.

                <input type="text" class="panel-title" data-bind="attr:{id:'input_'+Id}, textInput: Name,valueUpdate: 'afterkeydown', event:{keypress:$root.renameM}" style="color:white;display:none; background-color:black; width:30%;" />

It is possible to make the name of the accordion just to be editable on double click (or simple click) without doing anything to the accordion (expand or collapse) and expand or collapse it just when clicking outside the name area, on the empty space from the header?

Body:
You can use the hasFocus binding to detect and set focus on the input. You can use event.stopPropagation in your click handlers to prevent the click event from bubbling up to the accorion's toggle click target. Here's an example that shows:

Clicking on the text (green border) in the header starts editing it.

Removing focus on the edit input puts back the header

Clicking outside the text in the heading (blue border) toggles the accordion.

const expanded = ko.observable(false);

const focus = ko.observable(false);
const title = ko.observable("Heading");

const startEdit = function(data, event) {
  focus(true);
  event.stopPropagation();
};

const toggle = function() {
  if (!focus()) {
    expanded(!expanded());
  }
};

ko.applyBindings({ expanded, toggle, focus, title, startEdit });

h2 {
 border: 1px solid blue;
 padding: .5rem;
}

span {
 border: 1px solid green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<h2 data-bind="click: toggle">
  <span data-bind="text: title, click: startEdit, visible: !focus()"></span>
  <input type="text" data-bind="textInput: title, visible: focus, hasFocus: focus, clickBubble: false">
</h2>

<div data-bind="visible: expanded">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>


问:
Fatal error: Uncaught Error: Cannot use object of type Entrada as array
Who help me with this problem?

```<code>56    public static function mostrar_entradas_busqueda($entradas) {
57            $count = count($entradas);
58            for ($i = 1; $i <= $count; $i++) {
59                if ($i % 3 == 1) {
60                    ?>
61                    <div class="row">
62                        <?php
63                    }
64                    $entradas = $entradas[$i - 1];
65                    self::mostrar_entrada_busqueda($entradas);
66
67                    if ($i % 3 == 0) {
68                        ?>
69                    </div>
70                        <?php
71                    }
72                }
73                if ($i % 3 !== 0) {
74                    ?>
75                    </div>
76                    <?php
77                }
78            }
</code>```

Fatal error: Uncaught Error: Cannot use object of type Entrada as
  array in C:\xampp\htdocs\blog\app\EscritorEntradas.inc.php:64 Stack
  trace: #0 C:\xampp\htdocs\blog\vistas\buscar.php(81):
  EscritorEntradas::mostrar_entradas_busqueda(Object(Entrada)) #1
  C:\xampp\htdocs\blog\index.php(117):
  include_once('C:\xampp\htdocs...') #2 {main} thrown in
  C:\xampp\htdocs\blog\app\EscritorEntradas.inc.php on line 64

答:
The first time you execute it, this line...

```<code>$entradas = $entradas[$i - 1];
</code>```

... rewrites the value of $entradas to an object (value of the very zeroth element of $entradas array). The next time you try to execute it, you essentially query that object as an array, hence the error.

Solution: just rename that variable, and you're done:

```<code>$entrada = $entradas[$i - 1]; // and now it's single
self::mostrar_entrada_busqueda($entrada);
</code>```

And yes, variables are scoped per function in PHP, not per block. But even if the latter were the case, you'd still have to rewrite that line; I'm not aware of any language that has different rules of scope resolution for right and left parts of assignment statements.

As a sidenote, I'm really not sure why you check for i % 3 == 0 inside if (i % 3 == 1) branch.

Body:
Who help me with this problem?

56    public static function mostrar_entradas_busqueda($entradas) {
57            $count = count($entradas);
58            for ($i = 1; $i <= $count; $i++) {
59                if ($i % 3 == 1) {
60                    ?>
61

62                        <?php
63                    }
64                    $entradas = $entradas[$i - 1];
65                    self::mostrar_entrada_busqueda($entradas);
66
67                    if ($i % 3 == 0) {
68                        ?>
69

70                        <?php
71                    }
72                }
73                if ($i % 3 !== 0) {
74                    ?>
75

76                    <?php
77                }
78            }

Fatal error: Uncaught Error: Cannot use object of type Entrada as
  array in C:\xampp\htdocs\blog\app\EscritorEntradas.inc.php:64 Stack
  trace: #0 C:\xampp\htdocs\blog\vistas\buscar.php(81):
  EscritorEntradas::mostrar_entradas_busqueda(Object(Entrada)) #1
  C:\xampp\htdocs\blog\index.php(117):
  include_once('C:\xampp\htdocs...') #2 {main} thrown in
  C:\xampp\htdocs\blog\app\EscritorEntradas.inc.php on line 64

Body:
The first time you execute it, this line...

$entradas = $entradas[$i - 1];

... rewrites the value of $entradas to an object (value of the very zeroth element of $entradas array). The next time you try to execute it, you essentially query that object as an array, hence the error.

Solution: just rename that variable, and you're done:

$entrada = $entradas[$i - 1]; // and now it's single
self::mostrar_entrada_busqueda($entrada);

And yes, variables are scoped per function in PHP, not per block. But even if the latter were the case, you'd still have to rewrite that line; I'm not aware of any language that has different rules of scope resolution for right and left parts of assignment statements.

As a sidenote, I'm really not sure why you check for i % 3 == 0 inside if (i % 3 == 1) branch.


问:
How to run the Kick command of a bot via node.js?
I tried for a moment to make a command to kick a member, but after testing in mons discord, no message appears, and the member is not kick.

So this is for a bot discord with Node.js. I tried to remake commands via sites, and via videos (for the kick command), the editor does not give me any error, but the bot does not respond to the command in question

```<code>client.on('message', message => {
    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
      case 'kick' :
        if(!args[1]) message.channel.send('Vous devez spécifier la personne.')

        const user = message.mentions.users.first();

        if(user){
          const member = member.guild.member(user);

          if(member){
            member.kick('Vous avez été expulsé du serveur !').then(() =>{
              message.reply('Le joueur suivant a été expulsé : ${user.tag}');
            }).catch(err =>{
              message.reply('I was unable to kick the member')
              console.log(err);
            });
          } else
            message.reply("Le membre n'est pas dans la guilde.")
          }

        }

  })
</code>```

I would therefore, possible, know why this command does not work. Even though I think I should answer your questions. Thanks in advance for all the help !

答:
You can try using command handler you can use this guide
then create a folder for commands inside that folder you can create kick.js which will be for the kick command then do this </p>

```<code>let kUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!kUser) return message.channel.send("Please mention a user to kick!")
let kReason = args.join(" ").slice(22);
if(!kReason) return message.channel.send ("Please specify some reasons for the kick")
message.guild.member(kUser).kick(kReason);
message.channel.send(`${kUser} has been kicked from the server`);
</code>```

<p>Remember to also check permission so you are sure they have permission before they can kick members and also you can decide to log the kick in a channel where the bot send message to after the user has been click like this </p>

```<code>// this will look for logchannel so if you don't have that channel you can create or let logchannel = message.guild.channels.find(c => c.name === "logchannel");
logchannel.send(`${kUser} has been kicked from the server`);
</code>```

Body:
I tried for a moment to make a command to kick a member, but after testing in mons discord, no message appears, and the member is not kick.

So this is for a bot discord with Node.js. I tried to remake commands via sites, and via videos (for the kick command), the editor does not give me any error, but the bot does not respond to the command in question

client.on('message', message => {
    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
      case 'kick' :
        if(!args[1]) message.channel.send('Vous devez spécifier la personne.')

        const user = message.mentions.users.first();

        if(user){
          const member = member.guild.member(user);

          if(member){
            member.kick('Vous avez été expulsé du serveur !').then(() =>{
              message.reply('Le joueur suivant a été expulsé : ${user.tag}');
            }).catch(err =>{
              message.reply('I was unable to kick the member')
              console.log(err);
            });
          } else
            message.reply("Le membre n'est pas dans la guilde.")
          }

        }

  })

I would therefore, possible, know why this command does not work. Even though I think I should answer your questions. Thanks in advance for all the help !

Body:
You can try using command handler you can use this guide
then create a folder for commands inside that folder you can create kick.js which will be for the kick command then do this

let kUser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!kUser) return message.channel.send("Please mention a user to kick!")
let kReason = args.join(" ").slice(22);
if(!kReason) return message.channel.send ("Please specify some reasons for the kick")
message.guild.member(kUser).kick(kReason);
message.channel.send(`${kUser} has been kicked from the server`);

Remember to also check permission so you are sure they have permission before they can kick members and also you can decide to log the kick in a channel where the bot send message to after the user has been click like this

// this will look for logchannel so if you don't have that channel you can create or let logchannel = message.guild.channels.find(c => c.name === "logchannel");
logchannel.send(`${kUser} has been kicked from the server`);


问:
Finding hard-coded IP addresses using Visual Studio 2010 'Find in Files' utility (Ctrl+Shift+F)
I need to find all hard-coded IP addresses in some of our Visual Studio 2010 solutions.

How would I do this using the standard 'Find' utility (Ctrl+Shift+F) from Visual Studio 2010?

Body: For Visual studio 2017 this regex worked fine for me: ((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
Yeah, you may have encountered a scheduler overload.

I sincerely hope not.

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

OwnerDisplayName: Joshua


问:
Jersey Constructor
How it's possible to load something at the start of the system? I`m not have a "main" where my program starts !? </p>

答:
You could use a singleton object defined in Application#getSingletons().

```<code>public class MyApp extends Application
{
    public Set<Class<?>> getClasses()
    {
        return null;
    }

    public Set<Object> getSingletons()
    {
        Set<Object> set = new HashSet<Object>();
        Foo foo = /* init foo somehow */;
        set.add(foo);
        return set;
    }
}
</code>```

From RESTful Java (if you have the book, see p.142):

The getSingletons() method returns a list of preallocated JAX-RS web services and @Provider-annotated classes. You, as the application programmer, are responsible for creating these objects. The JAX-RS runtime will iterate through the list of objects and register them internally. When these objects are registered, JAX-RS will also inject values for @Context annotated fields and setter methods.

Title: Jersey Constructor

Body:
You could use a singleton object defined in Application#getSingletons().

public class MyApp extends Application
{
    public Set<Class<?>> getClasses()
    {
        return null;
    }

    public Set<Object> getSingletons()
    {
        Set<Object> set = new HashSet<Object>();
        Foo foo = /* init foo somehow */;
        set.add(foo);
        return set;
    }
}

From RESTful Java (if you have the book, see p.142):

The getSingletons() method returns a list of preallocated JAX-RS web services and @Provider-annotated classes. You, as the application programmer, are responsible for creating these objects. The JAX-RS runtime will iterate through the list of objects and register them internally. When these objects are registered, JAX-RS will also inject values for @Context annotated fields and setter methods.


问:
How to search for dataframes and sort each one accordingly?
I have dataframes in my local named like s1_down_threshold, s1_up_threshold, s2_down_threshold,s2_down_threshold, s19_down_threshold, s19_down_threshold and so on.

I would like to sort the dataframes having 'down_threshold' in their names in descending order based on one column and the dataframes having 'up_threshold' in their names in ascending order based on the same column.

I know that I can use .sort_values() for each and every one of them, but I would like to know if there is a more efficient way to do it?

I was hoping for something as follows:

Going through the names of all the dataframes in my local and then finding the dataframes with 'down_threshold' in their names and sorting them accordingly and then repeating the same process for 'up_threshold'

Edit 1:

答:
If all your df's are saved in the csv format in the same folder you can use the os library to import all of them and use the split function to decide wether to sort them in ascending or in a descending fashion.

Here is what it could look like :

```<code>import os

for file in os.listdir('./folder1/'):
    pd.read_csv('folder1/' + file)
    if file.split('.')[0].split('_')[1] =='down':
        df.sort_values(ascending = False, inplace = True)
    elif file.split('.')[0].split('_')[1] =='up':
        df.sort_values(ascending = True, inplace = True)
    df.to_csv('folder1/' + file)
</code>```

If there are other files in your local directory you can read the csv inside the if and elif conditions.

Body:
If all your df's are saved in the csv format in the same folder you can use the os library to import all of them and use the split function to decide wether to sort them in ascending or in a descending fashion.

Here is what it could look like :

import os

for file in os.listdir('./folder1/'):
    pd.read_csv('folder1/' + file)
    if file.split('.')[0].split('_')[1] =='down':
        df.sort_values(ascending = False, inplace = True)
    elif file.split('.')[0].split('_')[1] =='up':
        df.sort_values(ascending = True, inplace = True)
    df.to_csv('folder1/' + file)

If there are other files in your local directory you can read the csv inside the if and elif conditions.