问:
How to properly define destructor
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

```<code>class1::~class1(void) {

}
</code>```

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico

答:
Memory on stack

If there is no heap-allocated object inside your class, there is no need for you to explicitly define the destructor of your class. The compiler-generated one should handle the job quite well, i.e., call destructors for base class objects and member objects, etc.

Memory on heap - manual memory management

If there is any heap-allocated objects inside your class, you need manually deallocate them in your destructor. Make sure you have them deallocated properly at all possible exit points, e.g., handle exceptions and deallocate resources.

Memory on heap - RAII

Alternatively, you may use some well-defined RAII class to handle the resource management for you automatically, e.g., scoped_ptr, scoped_array in Boost, shared_ptr in STL, etc.

Title: How to properly define destructor

Body:
I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.

What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created.
The program works perfectly fine and the objects do what they should.

The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.

Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).

My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?

I found out (probably this was obvious for you already) that a destructor like

class1::~class1(void) {

}

won't work (I defined similar destructors for all internally defined classes).

Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?

Thanks to anyone who will answer/help/comment.

Federico


来源: stackexchange

问:
Flutter Push notification to iOS & Android without firebase?
I wonder how to push notifications to my Flutter app users in both Android and iOS devices Without using any external service like Firebase or OneSignal?

I want to implement a code in PHP which can send push real time notifications to all/spesific users in my Flutter app which works in both Android and iOS.

I found some solutions like flutter_local_notifications with workmanger which can fetch the API in the background only minimum 15 minuts. Workmanger is Not good solution because its work only during 15 min and it will consume the battery and internet.

I need an efficient solution to my flutter app for both Android & iOS devices, which can listen on real time to the coming messages from the server even when the app is closed.

How to fix that? thanks

答: Unfortunately, I think this is not possible. Even OneSignal uses the Firebase API to deliver the notifications, as you can see here. For all other solutions, you will have to balance the update frequency with internet use and battery consumption.</p>

ContentLicense: CC BY-SA 4.0


问:
How do I browse directories for json files (JavaScript)?
I want to browse directories for json files and merge all json files into one json file per directory.
My javascript skill is at beginner level.

The javascript code needs to run by calling it in the Terminal, not in the browser.

答:
you can make use of glob npm package to retrieve all json file paths in the directories.

glob : https://www.npmjs.com/package/glob

you can simply go with :

```<code>const glob = require("glob");
const fs = require('fs-extra');

async function processJsonData(){
  let parentDirectoryPath = '<specify path here>';
  let data = {};

  let jsonFilePaths = glob.sync(`${parentDirectoryPath}/*/*.json`);
  //this will return paths for all the json files

    for (const jsonFilePath of jsonFilePaths) {
        let content = await fs.readJsonSync(jsonFilePath);
        Object.assign(data,content);
    }

     await fs.writeJson(<filePath>, data, {spaces: 2});
    //here specify your file path
}

</code>```

ps. I am a new contributor, might have misread the question.

Body:
you can make use of glob npm package to retrieve all json file paths in the directories.

glob : https://www.npmjs.com/package/glob

you can simply go with :

const glob = require("glob");
const fs = require('fs-extra');

async function processJsonData(){
  let parentDirectoryPath = '<specify path here>';
  let data = {};

  let jsonFilePaths = glob.sync(`${parentDirectoryPath}/*/*.json`);
  //this will return paths for all the json files

    for (const jsonFilePath of jsonFilePaths) {
        let content = await fs.readJsonSync(jsonFilePath);
        Object.assign(data,content);
    }

     await fs.writeJson(<filePath>, data, {spaces: 2});
    //here specify your file path
}

ps. I am a new contributor, might have misread the question.


问:
how to upload all type of file to cloudinary using django with filefield
hello guys i want to upload  all type of file to cloudinary
this is my model
i  don't want to  upload a specific kind of file but all  type
pleaze  help me

```<code>class post(models.Model):
titre=models.CharField(unique=True,null=True,max_length=100)
description=models.TextField(null=True,blank=True,max_length=400)
T=models.CharField(default="image",blank=True,max_length=50)
image=models.FileField(null=True)
cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True)
datepost=models.DateTimeField(auto_now_add=True,blank=True)
user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True)
vue=models.IntegerField(default=0,blank=True)
def __str__(self):
    return self.titre

def save(self, *args ,**kwargs):
    #cette partie permet de generer un identifiant unique
    f=self.image.read(1000)
    self.image.seek(0)
    mime=magic.from_buffer(f,mime=True)
    if "video" in mime :
        self.T="short"
    super(post,self).save(*args,**kwargs)
</code>```

thanks for your helps and sorry for my bad english

答:
There are different types of files that are being supported when uploading your assets to your Cloudinary Media Library Account, and it can be identified using the [parameter resource_type][1]. There is also the class CloudinaryField where you can provide the parameter resource_type="auto" to support different file types automatically, for example:

```<code>from cloudinary.models import CloudinaryField
from django.contrib import admin
from django.db import models

class Photo(models.Model):
    name = models.CharField(max_length=159)
    image = CloudinaryField(
        "Image",
        resource_type="auto",  # <= Options: image, video, raw, auto
    )
</code>```

There is a sample project as part of the Cloudinary Python SDK which can be found [here][2].

[1]: https://cloudinary.com/documentation/image_upload_api_reference#:~:text=parameter%20to%20attachment).-,resource_type,-String
[2]: https://github.com/cloudinary/cloudinary-django-sample

Body:
hello guys i want to upload  all type of file to cloudinary
this is my model
i  don't want to  upload a specific kind of file but all  type
pleaze  help me

class post(models.Model):
titre=models.CharField(unique=True,null=True,max_length=100)
description=models.TextField(null=True,blank=True,max_length=400)
T=models.CharField(default="image",blank=True,max_length=50)
image=models.FileField(null=True)
cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True)
datepost=models.DateTimeField(auto_now_add=True,blank=True)
user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True)
vue=models.IntegerField(default=0,blank=True)
def __str__(self):
    return self.titre

def save(self, *args ,**kwargs):
    #cette partie permet de generer un identifiant unique
    f=self.image.read(1000)
    self.image.seek(0)
    mime=magic.from_buffer(f,mime=True)
    if "video" in mime :
        self.T="short"
    super(post,self).save(*args,**kwargs)

thanks for your helps and sorry for my bad english

Body:
There are different types of files that are being supported when uploading your assets to your Cloudinary Media Library Account, and it can be identified using the [parameter resource_type][1]. There is also the class CloudinaryField where you can provide the parameter resource_type="auto" to support different file types automatically, for example:

from cloudinary.models import CloudinaryField
from django.contrib import admin
from django.db import models

class Photo(models.Model):
    name = models.CharField(max_length=159)
    image = CloudinaryField(
        "Image",
        resource_type="auto",  # <= Options: image, video, raw, auto
    )

There is a sample project as part of the Cloudinary Python SDK which can be found [here][2].

[1]: https://cloudinary.com/documentation/image_upload_api_reference#:~:text=parameter%20to%20attachment).-,resource_type,-String
[2]: https://github.com/cloudinary/cloudinary-django-sample


问:
How to make a space between <i> tags (icons) in table?
I have a classic HTML table. In one column I want to add 3 icons with links to edit for example users. I am using twitter-bootstrap and glyphsicons. How to make more space between icons???
I prefer to use CSS.</p>

```<code><td>
   <a href='#'>
       <i class='icon-ok'></i>
   </a>
   <a href='#'>
       <i class='icon-pencil'></i>
   </a>
   <a href='#'>
       <i class='icon-remove'></i>
   </a>
</td>
</code>```

答:
Just add padding; like so:</p>
```<code>i {
padding: 5px;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Just add padding; like so:

i {
padding: 5px;
}


问:
Selecting select list values depending on another select list value
I have two select boxes (one for Car Types and the other for Car Models) in a web page that I would like to change one of them according to the other using JavaScript.

The code sample is as in the following:

```<code><html>

<head>
<script type="text/javascript">

function showCarModels(CarTypeVaraiable)
{

//I want to hide all the options in the CarModelsList and select the options with name property value equals to CarTypeVaraiable Value .. How I can write this in JavaScript ?????

}
</script>

</head>

</script>

<body>

<p>Selecting Car Models depending on the Car Type Value ..... </p>

Car Type<select id="selCarType" name="selCarType" class="selCarType" size="1" onchange="showCarModels('selCarType');">
<option class="City" value="0" selected="selected">choose Car Type</option>
<option class="CarType" value="100" >Toyota</option>
<option class="CarType" value="200" >Chevrlolet</option>
<option class="CarType" value="300" >Kia</option>
</select>

Car Model
<select id="selCarModel" name="selCarModel" class="selCarModel" size="1">

<option class="City" value="0">choose Car Model</option>

<option class="CarType" value="110" name="100" title="13" >Toyota optra</option>
<option class="CarType" value="120" name="100" title="13" >Toyota Aveo</option>
<option class="CarType" value="130" name="100" title="13" >Toyota Corolla</option>

<option class="CarType" value="210" name="200" title="13" >Chevrlolet Optra</option>
<option class="CarType" value="220" name="200" title="13" >Chevrlolet Aveo</option>

<option class="CarType" value="301" name="300" title="13" >Kia Rio</option>
<option class="CarType" value="450" name="300" title="13" >Kia Optima</option>
<option class="CarType" value="600" name="300" title="13" >Kia Serato</option>

</select>

</body>

</html>
</code>```

What I should write in the code to carry out this dependency between the two dropdown lists?

答:
You can do it in HTML + javascript + CSS, however once your structure grows it will be very hard to maintain. It is also easy to make typo and it is hard to test.
Better solution would be to use AJAX - store values for all categories in the database and create new select with options returned by server. You will have generic solution and adding new category + values is just adding records to the database, no need of changing html + js + css.

UPDATE:

I am not sure what backend language do you use, if it is php then you can take a look here: w3schools ajax example. If you use something else, then idea remains the same. Here you have beginning of ajax tutorial by w3schools. The example displays personal information after choosing  a name from select, but you can just wrap the output in select tag and generate option for each out.

Body:
I have two select boxes (one for Car Types and the other for Car Models) in a web page that I would like to change one of them according to the other using JavaScript.

The code sample is as in the following:

</script>

Selecting Car Models depending on the Car Type Value .....

Car Type<select id="selCarType" name="selCarType" class="selCarType" size="1" onchange="showCarModels('selCarType');">
<option class="City" value="0" selected="selected">choose Car Type</option>
<option class="CarType" value="100" >Toyota</option>
<option class="CarType" value="200" >Chevrlolet</option>
<option class="CarType" value="300" >Kia</option>
</select>

Car Model
<select id="selCarModel" name="selCarModel" class="selCarModel" size="1">

<option class="City" value="0">choose Car Model</option>

<option class="CarType" value="110" name="100" title="13" >Toyota optra</option>
<option class="CarType" value="120" name="100" title="13" >Toyota Aveo</option>
<option class="CarType" value="130" name="100" title="13" >Toyota Corolla</option>

<option class="CarType" value="210" name="200" title="13" >Chevrlolet Optra</option>
<option class="CarType" value="220" name="200" title="13" >Chevrlolet Aveo</option>

<option class="CarType" value="301" name="300" title="13" >Kia Rio</option>
<option class="CarType" value="450" name="300" title="13" >Kia Optima</option>
<option class="CarType" value="600" name="300" title="13" >Kia Serato</option>

</select>

What I should write in the code to carry out this dependency between the two dropdown lists?


问:
Android Studio Gradle project "Unable to start the daemon process /initialization of VM"
Version of Android Studio (Beta) 0.8.4

OS version: Windows 8

Java JRE/JDK version: 1.8.0_11

```<code>Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at http://gradle.org/docs/1.12/userguide/gradle_daemon.html
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 1048576KB object heap
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
</code>```

答:
Different solutions work for different people. I have tried almost all the solutions posted above and on other forums.

In my case, the problem was occurring because the Mobile Hotspot feature was enabled on my laptop.

Laptop Configuration:
-Windows 10
-RAM 12GB
-Android Studio 4.2.2
-Gradle version 6.7.1

Body:
Version of Android Studio (Beta) 0.8.4

OS version: Windows 8

Java JRE/JDK version: 1.8.0_11

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at http://gradle.org/docs/1.12/userguide/gradle_daemon.html
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 1048576KB object heap
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0


问:
Lookup in MongoDB using spring data
I have a query that would be fairly simple using SQL databases. However, in MongoDB, I'm not sure on how to do it. I am building a notification system. I have a collection that stores notifications, and another that creates a document when the user has seen the notification, as such:

notifications collection:

```<code>_id: 1
content: "some content"
targetGroup: "somegroup"
</code>```

seen-notification collection

```<code>_id: 1
notificationId: 1
userName: "johndoe"
</code>```

I'm building an endpoint that should return all notifications in a specific group, that the user has not already seen. In a SQL pseudo-code, I'm trying to do:

```<code>SELECT
    *
FROM
    notifications AS n
INNER JOIN
    seen-notification AS sn
ON n._id = sn.notificationId
WHERE
    sn.notificationId IS NULL
    AND n.targetGroup = "somegroup"
</code>```

So, basically, a right join with a where clause. I'm using spring data with a MongoRepository. Right now, i'm making two different selects and iterating through them to remove the already seen. I've looked into mongo's $lookup and several SO questions regarding it, but I just couldn't get it work with spring data and MongoRepository. I'm fairly new to mongo with spring data, so maybe there's a way to accomplish this with $lookup and I just didn't figure out how.

答:
try

https://mongoplayground.net/p/-dZHmP9yj-c

expects collection names of notifications and seenNotifications

```<code>@Aggregation(pipeline = {
    "{$match: { targetGroup: ?0 } }",
    "{$lookup: { from: \"seenNotifications\", localField: \"_id\", foreignField: \"notificationId\", as: \"seenNotificationsDocs\"}}",
    "{$match: { seenNotificationsDocs: { $size: 0 } } }",
    "{$project: { seenNotificationsDocs: 0 } }",
})
List<Notifications> findUnseenNotificationByTargetGroup(String targetGroup);
</code>```
```<code>@Document("notifications")
public class Notifications {

    @Id
    private Integer id;

    private String content;

    private String targetGroup;

    //getter & setter
}
</code>```

Title: Lookup in MongoDB using spring data

Body:
I have a query that would be fairly simple using SQL databases. However, in MongoDB, I'm not sure on how to do it. I am building a notification system. I have a collection that stores notifications, and another that creates a document when the user has seen the notification, as such:

notifications collection:

_id: 1
content: "some content"
targetGroup: "somegroup"

seen-notification collection

_id: 1
notificationId: 1
userName: "johndoe"

I'm building an endpoint that should return all notifications in a specific group, that the user has not already seen. In a SQL pseudo-code, I'm trying to do:

SELECT
    *
FROM
    notifications AS n
INNER JOIN
    seen-notification AS sn
ON n._id = sn.notificationId
WHERE
    sn.notificationId IS NULL
    AND n.targetGroup = "somegroup"

So, basically, a right join with a where clause. I'm using spring data with a MongoRepository. Right now, i'm making two different selects and iterating through them to remove the already seen. I've looked into mongo's $lookup and several SO questions regarding it, but I just couldn't get it work with spring data and MongoRepository. I'm fairly new to mongo with spring data, so maybe there's a way to accomplish this with $lookup and I just didn't figure out how.

Body:
try

https://mongoplayground.net/p/-dZHmP9yj-c

expects collection names of notifications and seenNotifications

@Aggregation(pipeline = {
    "{$match: { targetGroup: ?0 } }",
    "{$lookup: { from: \"seenNotifications\", localField: \"_id\", foreignField: \"notificationId\", as: \"seenNotificationsDocs\"}}",
    "{$match: { seenNotificationsDocs: { $size: 0 } } }",
    "{$project: { seenNotificationsDocs: 0 } }",
})
List<Notifications> findUnseenNotificationByTargetGroup(String targetGroup);

@Document("notifications")
public class Notifications {

    @Id
    private Integer id;

    private String content;

    private String targetGroup;

    //getter & setter
}


问:
How to fix 'command not found' for aws-cdk after running the npm install
I am trying to install the aws-cdk and in the terminal and I run the npm install -g aws-cdk.  As stated here  After npm runs, I get:

```<code>/usr/local/Cellar/node/9.8.0/bin/cdk -> /usr/local/Cellar/node/9.8.0/lib/node_modules/aws-cdk/bin/cdk
+ aws-cdk@0.31.0
updated 1 package in 1.636s
</code>```

If I try to run cdk I get:

```<code>zsh: command not found: cdk
</code>```

答:
Installing as root worked for me:
sudo npm install -g aws-cdk

Body:
I am trying to install the aws-cdk and in the terminal and I run the npm install -g aws-cdk.  As stated here  After npm runs, I get:

/usr/local/Cellar/node/9.8.0/bin/cdk -> /usr/local/Cellar/node/9.8.0/lib/node_modules/aws-cdk/bin/cdk
+ aws-cdk@0.31.0
updated 1 package in 1.636s

If I try to run cdk I get:

zsh: command not found: cdk


问:
How can I perform a git diff using a wildcard search?
When I do a git status, I get something like this:

```<code>modified   a/mega/super/duper/long/path/to/the/file/foo.php
modified   a/mega/super/duper/long/path/to/the/file/another/folder/bar.php
modified   a/mega/super/duper/long/path/to/the/file/someotherfolder/blahblah.php
</code>```

If I want to see what has changes for the bar.php-file (line 2) how do I do that?

I was hoping to be able to do something like this:

```<code>git diff */bar.php
git diff bar.php
</code>```

And that git could tab-complete or read my mind. :-)

Idea 1: Writing it out:

It's quite extensive having to write:

```<code>git diff a/mega/super/duper/long/path/to/the/file/another/folder/bar.php
</code>```

Idea 2: Use the mouse + Copy/paste

I could use the mouse and copy-paste, but that too seems like a poor solution. Taking the fingers away from the keyboard usually isn't the solution. And I have to do it quite a lot.

Idea 3: Git add patch

By running git add -p, I automatically goes into an interactive mode, being able to do a bunch of stuff. But it's not quite what I'm after.

Idea 4: Using sed

I found this SO-question: git diff just the first file, which suggests this:

```<code>git diff $(git diff --name-only | sed -n '1 p')
</code>```

I could then setup an Alfred-snippet or a bash-script that prints that. Whereafter I can change the 1 to the number of file I would like to see.

This is close to being good.

Idea 5: Bash-script to copy file-name of nth file to clipboard

Another way would be to make a bashscript, that copies the nth-file to the clipboard. Then I could do it in two swift commands, like this:

```<code>./copy-file-name-for-first-file-in-git-status.sh     # Named to make easy to understand.
git diff [PASTE]
</code>```

This would actually also solve it for the bonus-question below.

Bonus question - Same problem for git add and git log

The same issue is present, if I don't want to do a git add ., but want to add files individually in the deep nested folders. Then I also have to type my way through the entire path, for every single file.

答:
For ease of use, how about a Git alias rather than an external function? You can put it in your global config and you won't have to mess with remembering the new function or adding it to the path.

As you can see below it will run the diff with only a (potentially) very short substring to identify the file. It's a regex search and will gracefully handle cases when you specify a regex that matches no files or more than one file.

Add this to your git config:

```<code>[alias]
        diffr = "!a() { myfile=$(git status | awk '/modified:/ {print $2}' |grep "$1") ; cnt=$(git status |awk '/modified:/ {print $2}'|grep "$1" |wc -l) ;if [ $cnt -eq 1 ] ; then git diff $myfile;else printf '%s Matched %s files\n' $1 $cnt;fi; if ! [ $cnt -eq 0 ] ; then git status |grep "$1"; fi; }; a"
</code>```

Run it with git diffr "<regex>"

Here's the status of the test repo:

```<code>me@mypc MINGW64 /c/repos/aliastest (master)
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   mega/super/duper/long/path/to/the/file/another/folder/bar.php
        modified:   mega/super/duper/long/path/to/the/file/foo.php
        modified:   mega/super/duper/long/path/to/the/file/someotherfolder/blahblah.php

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Here's a successful diff for a file with 'foo' in the name (when it's the only matching file):

```<code>me@mypc MINGW64 /c/repos/aliastest (master)
$ git diffr foo
warning: LF will be replaced by CRLF in mega/super/duper/long/path/to/the/file/foo.php.
The file will have its original line endings in your working directory
diff --git a/mega/super/duper/long/path/to/the/file/foo.php b/mega/super/duper/long/path/to/the/file/foo.php
index 90be1f3..294186e 100644
--- a/mega/super/duper/long/path/to/the/file/foo.php
+++ b/mega/super/duper/long/path/to/the/file/foo.php
@@ -1 +1 @@
-before
+after
</code>```

This is how it handles the invalid case where the regex matched more than one file:

```<code>me@mypc MINGW64 /c/repos/aliastest (master)
$ git diffr "folder/b[al]"
folder/b[al] Matched 2 files
        modified:   mega/super/duper/long/path/to/the/file/another/folder/bar.php
        modified:   mega/super/duper/long/path/to/the/file/someotherfolder/blahblah.php
</code>```

Here it is handling a regex that matched no files:

```<code>me@mypc MINGW64 /c/repos/aliastest (master)
$ git diffr "sirnotappearinginthisfilm"
sirnotappearinginthisfilm Matched 0 files
</code>```

Aside from all the escaping it's just a plain Bash function so you can edit it as you please. You could call a separate executable in place of the Bash function but then you'd have external dependencies.
Minor adjustments to the script could fulfill your git add request as well. If I find time to write it I'll post it here. Similar functionality with git log seems like a different animal entirely since your possible results can be enormous.

I have had the same desire to keep my hands on the keyboard and the same problems with Git on the command line, but until now I hadn't really thought of how to solve this one. I'll be using this solution from now on whether or not anyone else does, so thanks for the suggestion.

Body:
When I do a git status, I get something like this:

modified   a/mega/super/duper/long/path/to/the/file/foo.php
modified   a/mega/super/duper/long/path/to/the/file/another/folder/bar.php
modified   a/mega/super/duper/long/path/to/the/file/someotherfolder/blahblah.php

If I want to see what has changes for the bar.php-file (line 2) how do I do that?

I was hoping to be able to do something like this:

git diff */bar.php
git diff bar.php

And that git could tab-complete or read my mind. :-)

Idea 1: Writing it out:

It's quite extensive having to write:

git diff a/mega/super/duper/long/path/to/the/file/another/folder/bar.php

Idea 2: Use the mouse + Copy/paste

I could use the mouse and copy-paste, but that too seems like a poor solution. Taking the fingers away from the keyboard usually isn't the solution. And I have to do it quite a lot.

Idea 3: Git add patch

By running git add -p, I automatically goes into an interactive mode, being able to do a bunch of stuff. But it's not quite what I'm after.

Idea 4: Using sed

I found this SO-question: git diff just the first file, which suggests this:

git diff $(git diff --name-only | sed -n '1 p')

I could then setup an Alfred-snippet or a bash-script that prints that. Whereafter I can change the 1 to the number of file I would like to see.

This is close to being good.

Idea 5: Bash-script to copy file-name of nth file to clipboard

Another way would be to make a bashscript, that copies the nth-file to the clipboard. Then I could do it in two swift commands, like this:

./copy-file-name-for-first-file-in-git-status.sh     # Named to make easy to understand.
git diff [PASTE]

This would actually also solve it for the bonus-question below.

Bonus question - Same problem for git add and git log

The same issue is present, if I don't want to do a git add ., but want to add files individually in the deep nested folders. Then I also have to type my way through the entire path, for every single file.

Body:
For ease of use, how about a Git alias rather than an external function? You can put it in your global config and you won't have to mess with remembering the new function or adding it to the path.

As you can see below it will run the diff with only a (potentially) very short substring to identify the file. It's a regex search and will gracefully handle cases when you specify a regex that matches no files or more than one file.

Add this to your git config:

[alias]
        diffr = "!a() { myfile=$(git status | awk '/modified:/ {print $2}' |grep "$1") ; cnt=$(git status |awk '/modified:/ {print $2}'|grep "$1" |wc -l) ;if [ $cnt -eq 1 ] ; then git diff $myfile;else printf '%s Matched %s files\n' $1 $cnt;fi; if ! [ $cnt -eq 0 ] ; then git status |grep "$1"; fi; }; a"

Run it with git diffr "<regex>"

Here's the status of the test repo:

me@mypc MINGW64 /c/repos/aliastest (master)
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   mega/super/duper/long/path/to/the/file/another/folder/bar.php
        modified:   mega/super/duper/long/path/to/the/file/foo.php
        modified:   mega/super/duper/long/path/to/the/file/someotherfolder/blahblah.php

no changes added to commit (use "git add" and/or "git commit -a")

Here's a successful diff for a file with 'foo' in the name (when it's the only matching file):

me@mypc MINGW64 /c/repos/aliastest (master)
$ git diffr foo
warning: LF will be replaced by CRLF in mega/super/duper/long/path/to/the/file/foo.php.
The file will have its original line endings in your working directory
diff --git a/mega/super/duper/long/path/to/the/file/foo.php b/mega/super/duper/long/path/to/the/file/foo.php
index 90be1f3..294186e 100644
--- a/mega/super/duper/long/path/to/the/file/foo.php
+++ b/mega/super/duper/long/path/to/the/file/foo.php
@@ -1 +1 @@
-before
+after

This is how it handles the invalid case where the regex matched more than one file:

me@mypc MINGW64 /c/repos/aliastest (master)
$ git diffr "folder/b[al]"
folder/b[al] Matched 2 files
        modified:   mega/super/duper/long/path/to/the/file/another/folder/bar.php
        modified:   mega/super/duper/long/path/to/the/file/someotherfolder/blahblah.php

Here it is handling a regex that matched no files:

me@mypc MINGW64 /c/repos/aliastest (master)
$ git diffr "sirnotappearinginthisfilm"
sirnotappearinginthisfilm Matched 0 files

Aside from all the escaping it's just a plain Bash function so you can edit it as you please. You could call a separate executable in place of the Bash function but then you'd have external dependencies.
Minor adjustments to the script could fulfill your git add request as well. If I find time to write it I'll post it here. Similar functionality with git log seems like a different animal entirely since your possible results can be enormous.

I have had the same desire to keep my hands on the keyboard and the same problems with Git on the command line, but until now I hadn't really thought of how to solve this one. I'll be using this solution from now on whether or not anyone else does, so thanks for the suggestion.


问:
WinRM: ERROR - Failed to authenticate to 172.x.x.x. WinRM::WinRMAuthorizationError
I'm trying to execute some chef commands on a Windows server using Jenkins.

When I run the build on Jenkins to execute the chef commands, I get the error below:

```<code>ERROR: Failed to authenticate to 172.54.78.989 as demo-user
Response: WinRM::WinRMAuthorizationError
Hint: Make sure to prefix domain usernames with the correct domain name.
Hint: Local user names should be prefixed with computer name or IP address.
EXAMPLE: my_domain\user_namer
ERROR: WinRM::WinRMAuthorizationError: WinRM::WinRMAuthorizationError
Build step 'Execute Windows batch command' marked build as failure
Finished: FAILURE
</code>```

Trying to figure out how to fix this

答:
I was able to fix the issue

It was caused by my user (demo-user) not belonging to domain name that allowed to connect from Chef to the Windows Server.

All I had to do was to get a user that was part of my organization domain name, replace demo-user with that user in my chef commands, and then run the Jenkins build again.

This time it worked fine.

Body:
I'm trying to execute some chef commands on a Windows server using Jenkins.

When I run the build on Jenkins to execute the chef commands, I get the error below:

ERROR: Failed to authenticate to 172.54.78.989 as demo-user
Response: WinRM::WinRMAuthorizationError
Hint: Make sure to prefix domain usernames with the correct domain name.
Hint: Local user names should be prefixed with computer name or IP address.
EXAMPLE: my_domain\user_namer
ERROR: WinRM::WinRMAuthorizationError: WinRM::WinRMAuthorizationError
Build step 'Execute Windows batch command' marked build as failure
Finished: FAILURE

Trying to figure out how to fix this


问:
Discord Bot - "Attribute Error: 'NoneType' object has no attribute 'strip.'
I'm a new coder, and I've been following atutorial on how to create a discord bot with the code below having been virtually copied the code straight out from the tutorial, and I've create a .env file to store my AuthToken.  Every time I run the code, I get error below aforementioned code. Any tips? Thanks in advance!

Code:

```<code>import os

import discord

from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')
client.run(TOKEN)

</code>```

Error:

```<code>Traceback (most recent call last):   File "/Users/XXXXXXXXXXXX/scratch/discordbot/app.py", line 16, in <module>
    client.run(TOKEN)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 640, in run
    return future.result()   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 621, in runner
    await self.start(*args, **kwargs)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 584, in start
    await self.login(*args, bot=bot)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'

</code>```

答:
It seems that the read token is a 'NoneType' object.

So if you use client.run(str(TOKEN)) instead of client.run(TOKEN) the method should be able to handle the token correctly and your bot should work.

Body:
I'm a new coder, and I've been following atutorial on how to create a discord bot with the code below having been virtually copied the code straight out from the tutorial, and I've create a .env file to store my AuthToken.  Every time I run the code, I get error below aforementioned code. Any tips? Thanks in advance!

Code:

import os

import discord

from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')
client.run(TOKEN)

Error:

Traceback (most recent call last):   File "/Users/XXXXXXXXXXXX/scratch/discordbot/app.py", line 16, in <module>
    client.run(TOKEN)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 640, in run
    return future.result()   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 621, in runner
    await self.start(*args, **kwargs)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 584, in start
    await self.login(*args, bot=bot)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/discord/client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'


问:
How to Convert spark dataframe to nested json using spark scala dynamically
I want to convert the  DataFrame to nested json. Sourse Data:-

DataFrame have data value like :-

Expected Output:-

I have to convert DataFrame value to Nested Json like : -

Appreciate your help !

答:
If you want to persist the data then save dataframe with format json

```<code>df.write.json("path")
</code>```

You can use toJSON function, which will convert dataframe to Dataset[String]

```<code>df.toJSON
</code>```

If there's only one element then you can further manipulate to get string

```<code>df.toJSON.take(1).head
</code>```

Thanks.

Body:
If you want to persist the data then save dataframe with format json

df.write.json("path")

You can use toJSON function, which will convert dataframe to Dataset[String]

df.toJSON

If there's only one element then you can further manipulate to get string

df.toJSON.take(1).head

Thanks.


问:
Rebuilding historical builds through TFS with version numbers
I have automatic build numbering setup, based on build date/name, using approach proposed by John Robbins from Wintellect described here. So the version/resource file is automatically created on build time but not checked-in.

I wonder how to approach a problem of rebuilding historical versions (based on labels) and having the original build number/name in them. Is it possible to detect 'GetVersion' parameter of MSBuild and try to recreate the original build name from it?

Is it a sane approach anyway? What alternatives do you see?

答:
You ask question Rebuilding historical builds but it actually Rebuilding historical change Set or label, I know what you mean but I am trying to tell you what I need to say, so I don't see that we need to build a label with the specific name the label or change set can has many build as needed and since we use the date and time in the build number it will more realistic to has the current time and date the build was taken instead of old one

Thanks

M.Radwan


问:
Add another key/value pair to all objects inside a jsonb array in POSTGRES
I have a table, let's call it myTable with the following structure

```<code>ID   | data
____________
uuid | jsonb
</code>```

The data in the jsonb field is an array structured in the following way:

```<code>[
  {
    "valueA": "500",
    "valueB": "ABC",
  },
  {
    "valueA": "300",
    "valueB": "CDE",
  }
]
</code>```

What I want to do is transform that data by adding a valueC and set it to valueA, for all the objects inside the 'data' jsonb array.

This is the result I want:

```<code>[
  {
    "valueA": "500",
    "valueB": "ABC",
    "valueC": "500",
  },
  {
    "valueA": "300",
    "valueB": "CDE",
    "valueC": "300",
  }
]
</code>```

I tried doing it with the following query:

```<code>UPDATE myTable
SET data = d.json_array
FROM (
    SELECT
        jsonb_agg(
                 jsonb_set(elems, '{valueC}', elems->'valueA')
        ) as json_array
    FROM
        myTable,
        jsonb_array_elements(data) elems
) d;
</code>```

This worked for some on the entries in myTable, but for some it went crazy and created 300+ additional entries, along with the ones I previosly had.

What am I missing in my query?

答:
Those FROM statements are unnecessary. You shouldn't need one on the UPDATE clause at all - your problem is that the subquery does a FROM myTable and then basically self-joins (by cartesian product) this subquery result against the whole myTable. The last (or really, any) UPDATE to each row wins, depending on the join order, making your result unpredictable.

I'd move the subquery in the SET clause where it only refers to the data of the row that is being updated:

```<code>UPDATE myTable
SET data = (
    SELECT jsonb_agg(
        jsonb_set(elems, '{valueC}', elems->'valueA')
    )
    FROM jsonb_array_elements(data) elems
);
</code>```

Alternatively, you would need to add a JOIN condition between the updated table and the FROM result:

```<code>UPDATE myTable u
SET data = d.json_array
FROM (
    SELECT
        id,
        jsonb_agg(
                 jsonb_set(elems, '{valueC}', elems->'valueA')
        ) as json_array
    FROM
        myTable,
        jsonb_array_elements(data) elems
    GROUP BY
        id
) d
WHERE
    u.id = d.id;
</code>```

Body:
I have a table, let's call it myTable with the following structure

ID   | data
____________
uuid | jsonb

The data in the jsonb field is an array structured in the following way:

[
  {
    "valueA": "500",
    "valueB": "ABC",
  },
  {
    "valueA": "300",
    "valueB": "CDE",
  }
]

What I want to do is transform that data by adding a valueC and set it to valueA, for all the objects inside the 'data' jsonb array.

This is the result I want:

[
  {
    "valueA": "500",
    "valueB": "ABC",
    "valueC": "500",
  },
  {
    "valueA": "300",
    "valueB": "CDE",
    "valueC": "300",
  }
]

I tried doing it with the following query:

UPDATE myTable
SET data = d.json_array
FROM (
    SELECT
        jsonb_agg(
                 jsonb_set(elems, '{valueC}', elems->'valueA')
        ) as json_array
    FROM
        myTable,
        jsonb_array_elements(data) elems
) d;

This worked for some on the entries in myTable, but for some it went crazy and created 300+ additional entries, along with the ones I previosly had.

What am I missing in my query?

Body:
Those FROM statements are unnecessary. You shouldn't need one on the UPDATE clause at all - your problem is that the subquery does a FROM myTable and then basically self-joins (by cartesian product) this subquery result against the whole myTable. The last (or really, any) UPDATE to each row wins, depending on the join order, making your result unpredictable.

I'd move the subquery in the SET clause where it only refers to the data of the row that is being updated:

UPDATE myTable
SET data = (
    SELECT jsonb_agg(
        jsonb_set(elems, '{valueC}', elems->'valueA')
    )
    FROM jsonb_array_elements(data) elems
);

Alternatively, you would need to add a JOIN condition between the updated table and the FROM result:

UPDATE myTable u
SET data = d.json_array
FROM (
    SELECT
        id,
        jsonb_agg(
                 jsonb_set(elems, '{valueC}', elems->'valueA')
        ) as json_array
    FROM
        myTable,
        jsonb_array_elements(data) elems
    GROUP BY
        id
) d
WHERE
    u.id = d.id;


问:
Take data from List on equal parts (samples) C#
Consider I have the following List:

```<code>var numbers = new List<int>(){ 3, 6, 7, 8, 9, 1, 4 };
</code>```

and I have a variable that contains the number of samples that I want to take from the array:

```<code>const int SAMPLES_COUNT = 4;
</code>```

My goal is to take 4 samples on equal ranges ( as much as possible ) from the list and put them into another list. For example the new list should look like this:

```<code>var samples = new List<int>(){ 3, 7, 9, 4};
</code>```

Is there any work around in order to achieve this result.

答:
You can try to use arithmetic to get the mod number and use loop or lambda to make it.</p>
```<code>const int SAMPLES_COUNT = 4;
var numbers = new List<int>(){ 3, 6, 7, 8, 9, 1, 4 };
var divNumber = Math.Ceiling((decimal)numbers.Count / (decimal)SAMPLES_COUNT);
var result = numbers.Where((x,i)=> i % divNumber == 0).ToList();
</code>```

Body:
Consider I have the following List:

var numbers = new List<int>(){ 3, 6, 7, 8, 9, 1, 4 };

and I have a variable that contains the number of samples that I want to take from the array:

const int SAMPLES_COUNT = 4;

My goal is to take 4 samples on equal ranges ( as much as possible ) from the list and put them into another list. For example the new list should look like this:

var samples = new List<int>(){ 3, 7, 9, 4};

Is there any work around in order to achieve this result.

Body:
You can try to use arithmetic to get the mod number and use loop or lambda to make it.

const int SAMPLES_COUNT = 4;
var numbers = new List<int>(){ 3, 6, 7, 8, 9, 1, 4 };
var divNumber = Math.Ceiling((decimal)numbers.Count / (decimal)SAMPLES_COUNT);
var result = numbers.Where((x,i)=> i % divNumber == 0).ToList();


问:
why String.format 0.1d double value as exact 0.1 in java?
IEEE 754 float numbers are discret.

```<code>public class MyTest2 {
  public static void main(String[] args) {
    //about 1.00000001490116119384765625E-1 in IEEE-754
    float f = 0.1f;
    //about 1.00000000000000005551115123126E-1 in IEEE-754
    double d = 0.1d;
    System.out.println(String.format("double 0.1= %.30f", d));
    System.out.println(String.format("float 0.1 = %.15f", f));
    System.out.println(d+"");
  }
}
</code>```

See this code run live at IdeOne.com. Running in JDK8, output is

```<code>double 0.1= 0.100000000000000000000000000000
float 0.1 = 0.100000001490116
0.1
</code>```

The float value is printed as expected.
I expect double value 0.1d to be printed something like 1.000000000000000055511151231260. Why it print
all zeros in fraction part?

If I convert double variable d to string, it prints 0.1.

```<code>System.out.println(d+"");
</code>```

How does java convet the neartest float value of 0.1d (which is stroed as about 1.00000001490116119384765625E-1) to exact 0.1?

答:
The Java specification requires this imperfect display of values. The f format produces only as many significant digits as the Double.toString(double) method would produce and then mindlessy appends zeros to get to the requested precision.

Per the documentation, for the f format, if the precision exceeds the number of digits after the decimal point that Double.toString(double) would produce, then “zeros may be appended to reach the precision.” This does not state what those zeros are appended to. Presumably, they are appended to the string that Double.toString(double) would produce.

The documentation for Double.toString(double) says it produces “as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double.” I discuss that further here. For 0.1000000000000000055511151231257827021181583404541015625, Double.toString(double) produces “0.1”. (The neighboring values, 0.09999999999999999167332731531132594682276248931884765625 and
0.10000000000000001942890293094023945741355419158935546875, are both further from .1 than 0.1000000000000000055511151231257827021181583404541015625 is, and they are formatted as “0.09999999999999999” and “0.10000000000000002”, so “0.1” serves to uniquely distinguish 0.1000000000000000055511151231257827021181583404541015625 from its neighbors.)

Thus, System.out.println(String.format("double 0.1= %.30f", d)) starts with the “0.1” from Double.toString(double) and appends 29 zeroes.

Similarly, if you change d to 0.09999999999999999167332731531132594682276248931884765625, String.format produces “0.099999999999999990000000000000”—it has taken the toString result and appended zeros. And for 0.10000000000000001942890293094023945741355419158935546875 it produces “0.100000000000000020000000000000”.

This conforms to the specification. The specified behavior is incapable of presenting the true value correctly, so I regard the specification as defective.

Incidentally, the Java specification is troublesome whether the requested precision is greater than or less than the number of digits that Double.toString(double) would produce. In the case when the request permission is less, the Java specification requires a double rounding that can increase errors.

Body:
IEEE 754 float numbers are discret.

public class MyTest2 {
  public static void main(String[] args) {
    //about 1.00000001490116119384765625E-1 in IEEE-754
    float f = 0.1f;
    //about 1.00000000000000005551115123126E-1 in IEEE-754
    double d = 0.1d;
    System.out.println(String.format("double 0.1= %.30f", d));
    System.out.println(String.format("float 0.1 = %.15f", f));
    System.out.println(d+"");
  }
}

See this code run live at IdeOne.com. Running in JDK8, output is

double 0.1= 0.100000000000000000000000000000
float 0.1 = 0.100000001490116
0.1

The float value is printed as expected.
I expect double value 0.1d to be printed something like 1.000000000000000055511151231260. Why it print
all zeros in fraction part?

If I convert double variable d to string, it prints 0.1.

System.out.println(d+"");

How does java convet the neartest float value of 0.1d (which is stroed as about 1.00000001490116119384765625E-1) to exact 0.1?


问:
Ways to get last commit author in Github Actions workflow
I am working on converting a Jenkins Pipeline into a Github Actions workflow and need a way of storing the commit author as an environment variable for later use in node.js code.

I have read the documentation and this seems to be the only way I can get it working:

```<code>name: Feature Branch PR

on:
  pull_request:
    types: [opened, edited, synchronize]
  push:
    branches:
    - '**'
</code>```

Then in the Env section:

```<code>env:
   AUTHOR: ${{ github.event.pusher.name }}
</code>```

The problem is this only works for Push triggers. So if i remove the on: push section from top of yml workflow (so it only triggers on PRs) the AUTHOR info becomes empty.

I cannot find a way to get it for commits. Does anyone know of of a way? We do not want this workflow to trigger on pushes.

I also tried

```<code>        AUTHOR: $(jq '.commits.committer.name' $GITHUB_EVENT_PATH)
</code>```

I think this was syntactically incorrect though.

答:
As YakovL mentioned,

```<code>env:
  ${{ github.event.pull_request.user.login }}
</code>```

Works fine in a Github action.

Body:
I am working on converting a Jenkins Pipeline into a Github Actions workflow and need a way of storing the commit author as an environment variable for later use in node.js code.

I have read the documentation and this seems to be the only way I can get it working:

name: Feature Branch PR

on:
  pull_request:
    types: [opened, edited, synchronize]
  push:
    branches:
    - '**'

Then in the Env section:

env:
   AUTHOR: ${{ github.event.pusher.name }}

The problem is this only works for Push triggers. So if i remove the on: push section from top of yml workflow (so it only triggers on PRs) the AUTHOR info becomes empty.

I cannot find a way to get it for commits. Does anyone know of of a way? We do not want this workflow to trigger on pushes.

I also tried

        AUTHOR: $(jq '.commits.committer.name' $GITHUB_EVENT_PATH)

I think this was syntactically incorrect though.

Body:
As YakovL mentioned,

env:
  ${{ github.event.pull_request.user.login }}

Works fine in a Github action.


问:
Flutter: Location permission: when in use or always
I'm trying to know if the user has selected "only when in use" or "always" for the location.

https://pub.dev/packages/location_permissions

I tried this code from the package:

```<code> ServiceStatus serviceStatus =
          await LocationPermissions().checkServiceStatus();
      print(serviceStatus);
</code>```

But it prints:

```<code>ServiceStatus.enabled
</code>```

Is there a possibility (perhaps with another package) to know this?

Thanks in advance!

答:
Geolocator package may be used for that. From its readMe page:

This method returns a value of the GeolocationStatus enum indicating
the availability of the location services on the device. Optionally
you can specify if you want to test for
GeolocationPermission.locationAlways or
GeolocationPermission.locationWhenInUse

. Have a look here - https://pub.dev/packages/geolocator

Body:
I'm trying to know if the user has selected "only when in use" or "always" for the location.

https://pub.dev/packages/location_permissions

I tried this code from the package:

 ServiceStatus serviceStatus =
          await LocationPermissions().checkServiceStatus();
      print(serviceStatus);

But it prints:

ServiceStatus.enabled

Is there a possibility (perhaps with another package) to know this?

Thanks in advance!


问:
Is the C# static constructor thread safe?
In other words, is this Singleton implementation thread safe:</p>

```<code>public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}
</code>```

答:
Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.

```<code>public class Singleton
{
    private static Singleton instance;
    // Added a static mutex for synchronising use of instance.
    private static System.Threading.Mutex mutex;
    private Singleton() { }
    static Singleton()
    {
        instance = new Singleton();
        mutex = new System.Threading.Mutex();
    }

    public static Singleton Acquire()
    {
        mutex.WaitOne();
        return instance;
    }

    // Each call to Acquire() requires a call to Release()
    public static void Release()
    {
        mutex.ReleaseMutex();
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In other words, is this Singleton implementation thread safe:

public class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        instance = new Singleton();
    }

    public static Singleton Instance
    {
        get { return instance; }
    }
}

Body:
Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.

public class Singleton
{
    private static Singleton instance;
    // Added a static mutex for synchronising use of instance.
    private static System.Threading.Mutex mutex;
    private Singleton() { }
    static Singleton()
    {
        instance = new Singleton();
        mutex = new System.Threading.Mutex();
    }

    public static Singleton Acquire()
    {
        mutex.WaitOne();
        return instance;
    }

    // Each call to Acquire() requires a call to Release()
    public static void Release()
    {
        mutex.ReleaseMutex();
    }
}


问:
Backslashes being added into my cookie in Python
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what.  Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world.

Anyway, so basically I am keeping information input into a form in a cookie.  I am attempting to append to the previous cookie with the new information entered.  But for some reason on the third entry of data the cookie suddenly gets "\" in it.  I am not sure where they are coming from though.

This is the type of output I am getting:

"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"

```<code>#!/usr/local/bin/python

import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')
    for myCookie in cookies:
        myCookie = myCookie.split('=')
        name = myCookie[0]
        value = myCookie[1]
        if name == 'critter' :
            hideMe = value

#import critterClass

#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')

#make cookie
cookie = Cookie.SimpleCookie()

#set critter Cookie
if critterName is not None:
    cookie['critter'] = critterName
#If already named
else:
    #if action asked, append cookie
    if input2 is not None:
        cookie['critter'] = hideMe+":"+input2
    else:
        cookie['critter'] = "default"

print cookie

print "Content-type: text/html\n\n"

if ((critterName is None) and (input2 is None)):
    print """
    <form name="critter" id="critter" method="post" action="critter.py">
    <label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
    <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    """
else:
    formTwo ="""
    <form name="critter2" id="critter2" method="post" action="critter.py">
    <label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
    <input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
    <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    [name,play,feed,mood,levels,end]
    """
    print formTwo % (critterName,critterName)

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')
    for myCookie in cookies:
        myCookie = myCookie.split('=')
        name = myCookie[0]
        value = myCookie[1]
        if name == 'critter' :
            print "name"+name
            print "value"+value
</code>```

答:
As explained by others, the backslashes are escaping double quote characters you insert into the cookie value. The (hidden) mechanism in action here is the SimpleCookie class. The BaseCookie.output() method returns a string representation suitable to be sent as HTTP headers. It will insert escape characters (backslashes) before double quote characters and before backslash characters.

The

```<code>print cookie
</code>```

statement activates BaseCookie.output().

On each trip your string makes through the cookie's output() method, backslashes are multiplied (starting with the 1st pair of quotes).

```<code>>>> c1=Cookie.SimpleCookie()
>>> c1['name']='A:0'
>>> print c1
Set-Cookie: name="A:0"
>>> c1['name']=r'"A:0"'
>>> print c1
Set-Cookie: name="\"A:0\""
>>> c1['name']=r'"\"A:0\""'
>>> print c1
Set-Cookie: name="\"\\\"A:0\\\"\""
>>>
</code>```

OwnerDisplayName: Levi

Body:
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what.  Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world.

Anyway, so basically I am keeping information input into a form in a cookie.  I am attempting to append to the previous cookie with the new information entered.  But for some reason on the third entry of data the cookie suddenly gets "\" in it.  I am not sure where they are coming from though.

This is the type of output I am getting:

"\"\\"\\\\"test:more\\\\":rttre\\":more\":and more"

#!/usr/local/bin/python

import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')
    for myCookie in cookies:
        myCookie = myCookie.split('=')
        name = myCookie[0]
        value = myCookie[1]
        if name == 'critter' :
            hideMe = value

#import critterClass

#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')

#make cookie
cookie = Cookie.SimpleCookie()

#set critter Cookie
if critterName is not None:
    cookie['critter'] = critterName
#If already named
else:
    #if action asked, append cookie
    if input2 is not None:
        cookie['critter'] = hideMe+":"+input2
    else:
        cookie['critter'] = "default"

print cookie

print "Content-type: text/html\n\n"

if ((critterName is None) and (input2 is None)):
    print """
    <form name="critter" id="critter" method="post" action="critter.py">
    Name your pet: <input type="text" name="input" id="input" />
    <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    """
else:
    formTwo ="""
    <form name="critter2" id="critter2" method="post" action="critter.py">
    %s wants to: <input type="text" name="input2" id="input2" />
    <input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
    <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    [name,play,feed,mood,levels,end]
    """
    print formTwo % (critterName,critterName)

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')
    for myCookie in cookies:
        myCookie = myCookie.split('=')
        name = myCookie[0]
        value = myCookie[1]
        if name == 'critter' :
            print "name"+name
            print "value"+value

LastEditorDisplayName: Levi

Body:
As explained by others, the backslashes are escaping double quote characters you insert into the cookie value. The (hidden) mechanism in action here is the SimpleCookie class. The BaseCookie.output() method returns a string representation suitable to be sent as HTTP headers. It will insert escape characters (backslashes) before double quote characters and before backslash characters.

The

print cookie

statement activates BaseCookie.output().

On each trip your string makes through the cookie's output() method, backslashes are multiplied (starting with the 1st pair of quotes).

>>> c1=Cookie.SimpleCookie()
>>> c1['name']='A:0'
>>> print c1
Set-Cookie: name="A:0"
>>> c1['name']=r'"A:0"'
>>> print c1
Set-Cookie: name="\"A:0\""
>>> c1['name']=r'"\"A:0\""'
>>> print c1
Set-Cookie: name="\"\\\"A:0\\\"\""
>>>

OwnerDisplayName: gimel

LastEditorDisplayName: gimel


问:
create custom nested output from json using javascript

let data = {
  "needData": [
    {
      arrayData: [
        {
          "key": "dummy",
          "value": "needed value"
        },
        {
          "key": "secret",
          "random": "secret_random"
        },
        {
          "key": "another",
          "value": "testing"
        },
        {
          "key": "another_Secret",
          "random": "testing_value"
        },
      ]
    }
  ]
};
let json, testing;
data.needData.map((value) => {
  json = {
    arrayData: [
      {
        needed_key: value.arrayData[0].key,
        needed_value: value.arrayData[0].value,
      },
    ],
  };
  testing = {
    arrayData: [
      {
        needed_key: value.arrayData.key,
        needed_value: value.arrayData.value,
      },
    ],
  };
});
console.log("value got by running json", json);
console.log("value got by running testing", testing);```
</div>
</div>
</p>
<p>I am trying to save data in json object by using map function but the problem is I can save data by using <code>needed_key:value.arrayData.key</code> <code>needed_value:value.arrayData.value</code></p>
<p>if all the needed_key and needed_value are same I can use above code but here problem is key name is same but the needed_value get change by <code>random and value</code> I only want to save values of those data which contain in <code>value</code> not <code>random</code> is there any way I can get <code>key and value</code> value not <code>key and random</code> value</p>
<p>I can use manual code to fetch the data but what if data is more and I don't want to use manual code</p>
<h2>Expected Output</h2>
```{
  "arrayData": [
      {
          "needed_key": "dummy",
          "needed_value": "needed value"
      },
      {
          "needed_key": "another",
          "needed_value": "testing"
      }
  ]
}

```

答:
Array.map and Array.filter implementation.

let data = {
  "needData": [
    {
      arrayData: [
        { "key": "dummy", "value": "needed value" },
        { "key": "secret", "random": "secret_random" },
        { "key": "another", "value": "testing" },
        { "key": "another_Secret", "random": "testing_value" },
      ]
    }
  ]
};
const output = data.needData.map((value) => {
  const { arrayData } = value;
  const opArrayData = arrayData.filter(item => item.key && item.value && !item.random);
  const parsedArray = opArrayData.map((node => ({ needed_key: node.key, needed_value: node.value })));
  return { arrayData: parsedArray }
});
console.log(output);```

Body:
let data = {
  "needData": [
    {
      arrayData: [
        {
          "key": "dummy",
          "value": "needed value"
        },
        {
          "key": "secret",
          "random": "secret_random"
        },
        {
          "key": "another",
          "value": "testing"
        },
        {
          "key": "another_Secret",
          "random": "testing_value"
        },
      ]
    }
  ]
};
let json, testing;
data.needData.map((value) => {
  json = {
    arrayData: [
      {
        needed_key: value.arrayData[0].key,
        needed_value: value.arrayData[0].value,
      },
    ],
  };
  testing = {
    arrayData: [
      {
        needed_key: value.arrayData.key,
        needed_value: value.arrayData.value,
      },
    ],
  };
});
console.log("value got by running json", json);
console.log("value got by running testing", testing);

I am trying to save data in json object by using map function but the problem is I can save data by using needed_key:value.arrayData.key needed_value:value.arrayData.value

if all the needed_key and needed_value are same I can use above code but here problem is key name is same but the needed_value get change by random and value I only want to save values of those data which contain in value not random is there any way I can get key and value value not key and random value

I can use manual code to fetch the data but what if data is more and I don't want to use manual code

Expected Output

{
  "arrayData": [
      {
          "needed_key": "dummy",
          "needed_value": "needed value"
      },
      {
          "needed_key": "another",
          "needed_value": "testing"
      }
  ]
}


问:
Dictionary from another dictionary
I have a dictionary with IDs and counts:

```<code>  items_count = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
    }
</code>```

Key is "category":"id". I want to separate category and put it in another dictionary like:

```<code>items_count2 = {
    '1111': {'271': 111, '190': 3, '201': 0},
    '1231': {'106': 13},
    '1211': {'104': 111}
    }
</code>```

but when I do this

```<code>items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count}
</code>```

I get error
"ValueError: too many values to unpack (expected 2)"

please help to understand, what am I doing wrong?

答:
So first your suggestion should be:

```<code>items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}
</code>```

But this won't be working neither, cause you have multiple k, v per sub-dictionary.

So below is a way to do, without using dict comprehension:

```<code>dct = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
}

# Initialize your new dict
new_dct = {k.split(':')[0]: {} for k in dct} # Or k in dct.keys()

# Loop through old dict
for k, v in dct.items():
    # Set value to top > sub key in new dict
    new_dct[k.split(':')[0]][k.split(':')[1]] = v

print(new_dct)
</code>```

Output:

```<code>{'1111': {'271': 111, '190': 3, '201': 9}, '1231': {'106': 13}, '1211': {'104': 111}}
</code>```

Title: Dictionary from another dictionary

Body:
I have a dictionary with IDs and counts:

  items_count = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
    }

Key is "category":"id". I want to separate category and put it in another dictionary like:

items_count2 = {
    '1111': {'271': 111, '190': 3, '201': 0},
    '1231': {'106': 13},
    '1211': {'104': 111}
    }

but when I do this

items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count}

I get error
"ValueError: too many values to unpack (expected 2)"

please help to understand, what am I doing wrong?

Body:
So first your suggestion should be:

items_count2 = {k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}

But this won't be working neither, cause you have multiple k, v per sub-dictionary.

So below is a way to do, without using dict comprehension:

dct = {
    '1111:271': 111,
    '1111:190': 3,
    '1231:106': 13,
    '1211:104': 111,
    '1111:201': 9
}

# Initialize your new dict
new_dct = {k.split(':')[0]: {} for k in dct} # Or k in dct.keys()

# Loop through old dict
for k, v in dct.items():
    # Set value to top > sub key in new dict
    new_dct[k.split(':')[0]][k.split(':')[1]] = v

print(new_dct)

Output:

{'1111': {'271': 111, '190': 3, '201': 9}, '1231': {'106': 13}, '1211': {'104': 111}}


问:
Java - HashMap for booking system
I have been given an exercise to develop an appropriate data structure to implement a tennis court booking system.

A hashmap is what is required for this and I was given a diagram as a visual representation of the data structure.

From looking at the diagram, I am unclear on how the Key and Value should be defined in the HashMap. Should 'Court' be a class, which is the Key?

For the value, it shows a time, and a players name. How would the value be defined, since it has two values of time and player name?

diagram link

答:
Creating a HashMap for each Date1 is an odd and confusing approach for a HashMap can't really represent a date as we understand it. but given that this is the assignment, you have to keep information about the court number, the playtime and the competitors names. These are at least three fields, if we concat the competitors names to one String.

With only using HashMap you will probably have to use a multi-dimensional HashMap.

```<code>HashMap<Integer, HashMap<String, String>> Date1 = new HashMap<String, HashMap<String, String>>();
</code>```

The outer HashMap holds the court number as the key of type Integer and the pairings as the value of type HashMap.
The inner HashMap holds the playtime as key of type String (though you might as well use the type Time) and the competitors names as value of type String.

When creating this, it is vital to generate addintional accessors to avoid tedious chained calls of Date1.get(someIntVariable).get(someStringOrTime) to receive the players names.

```<code>public HashMap<String, String> getPairingsForCourt(int court) {
    return Date1.get(court);
}

public String getPlayersForCourtOnTime(int court, String time) {
    return getPairingsForCourt(court).get(time);
}
</code>```

By any chance getting familiar with all the aspects of HashMap requires some time. Especially if you come across mechanisms like keySet() or entrySet(). Have a look on here for a detailed yet understandable start:
A Guide to Java HashMap

Title: Java - HashMap for booking system

Body:
Creating a HashMap for each Date1 is an odd and confusing approach for a HashMap can't really represent a date as we understand it. but given that this is the assignment, you have to keep information about the court number, the playtime and the competitors names. These are at least three fields, if we concat the competitors names to one String.

With only using HashMap you will probably have to use a multi-dimensional HashMap.

HashMap<Integer, HashMap<String, String>> Date1 = new HashMap<String, HashMap<String, String>>();

The outer HashMap holds the court number as the key of type Integer and the pairings as the value of type HashMap.
The inner HashMap holds the playtime as key of type String (though you might as well use the type Time) and the competitors names as value of type String.

When creating this, it is vital to generate addintional accessors to avoid tedious chained calls of Date1.get(someIntVariable).get(someStringOrTime) to receive the players names.

public HashMap<String, String> getPairingsForCourt(int court) {
    return Date1.get(court);
}

public String getPlayersForCourtOnTime(int court, String time) {
    return getPairingsForCourt(court).get(time);
}

By any chance getting familiar with all the aspects of HashMap requires some time. Especially if you come across mechanisms like keySet() or entrySet(). Have a look on here for a detailed yet understandable start:
A Guide to Java HashMap


问:
What is 'Closure' in Functions?
I am right now learning a beautiful programming language, Dart, which I am loving so much. However, I am finding my basic programming knowledge has some gaps, and one of them is 'Closure' in Functions which I am finding difficult to understand. Can you please explain to me what is unique from Anonymous Function??</p>

答:
"Closure" is a word that is used about many different things.

Generally, and originally, a closure is a (function) value which contains references to variables (it "closes over" those variables).

In Dart, you can introduce functions in two different ways.

A function declaration: int foo(int x) => x; (as a top-level, static - if prefixed by static, instance or local function).

A function expression: (int x) => x (as an expression).

The first function is named, and can be called by name, referring directly to the declaration (foo(42)).
It can also be turned into a function value by "tearing off" the function:

int Function(int) f = foo;
```
<p>A function expression evaluates to a function value directly.</p>
<pre class="lang-dart prettyprint-override"><code>int Function(int) f = (int x) => x;
</code>```

A lot of people use the word "closure" about function values, also called "first class function values" because they are objects like any other object, not special second-class values that can only be used in limited ways.
If you see someone saying "closure", assume that's what they mean - an object which is also a function.

Technically, the function values here do not close over any variables.
An example of one which does would be:

int Function(int) adder(int base) => (int addition) => base + addition;
int Function(int) add2 = adder(2);
```

The function value stored in the add2 variable here is the value of the function expression (int addition) => base + addition. The base variable is not bound by this expression, it is instead captured/"closed over" by the closure/function value. The base variable being closed over here comes from the invocation of adder with the value 2.

Title: What is 'Closure' in Functions?

Body:
"Closure" is a word that is used about many different things.

Generally, and originally, a closure is a (function) value which contains references to variables (it "closes over" those variables).

In Dart, you can introduce functions in two different ways.

A function declaration: int foo(int x) => x; (as a top-level, static - if prefixed by static, instance or local function).

A function expression: (int x) => x (as an expression).

The first function is named, and can be called by name, referring directly to the declaration (foo(42)).
It can also be turned into a function value by "tearing off" the function:

int Function(int) f = foo;

A function expression evaluates to a function value directly.

int Function(int) f = (int x) => x;

A lot of people use the word "closure" about function values, also called "first class function values" because they are objects like any other object, not special second-class values that can only be used in limited ways.
If you see someone saying "closure", assume that's what they mean - an object which is also a function.

Technically, the function values here do not close over any variables.
An example of one which does would be:

int Function(int) adder(int base) => (int addition) => base + addition;
int Function(int) add2 = adder(2);

The function value stored in the add2 variable here is the value of the function expression (int addition) => base + addition. The base variable is not bound by this expression, it is instead captured/"closed over" by the closure/function value. The base variable being closed over here comes from the invocation of adder with the value 2.


问:
RecyclerView adapter showing wrong images
I have a RecyclerView adapter that looks like this:

```<code>public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private static Context context;
    private List<Message> mDataset;

    public RecyclerAdapter(Context context, List<Message> myDataset) {
        this.context = context;
        this.mDataset = myDataset;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener {
        public TextView title;
        public LinearLayout placeholder;

        public ViewHolder(View view) {
            super(view);
            view.setOnCreateContextMenuListener(this);

            title = (TextView) view.findViewById(R.id.title);
            placeholder = (LinearLayout) view.findViewById(R.id.placeholder);
        }
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_layout, parent, false);
        ViewHolder vh = new ViewHolder((LinearLayout) view);

        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Message item = mDataset.get(position);

        holder.title.setText(item.getTitle());

        int numImages = item.getImages().size();

        if (numImages > 0) {
            View test = LayoutInflater.from(holder.placeholder.getContext()).inflate(R.layout.images, holder.placeholder, false);
            ImageView image = (ImageView) test.findViewById(R.id.image);
            Glide.with(context)
                .load("http://www.website.com/test.png")
                .fitCenter()
                .into(image);
            holder.placeholder.addView(test);
        }
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}
</code>```

However, some of the items in the RecyclerView are showing images when they shouldn't be. How can I stop this from happening?

I do the check if (numImages > 0) { in onBindViewHolder(), but that's still not stopping it from showing images for items that shouldn't have images.

答:
```<code>   override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }
</code>```

This Works for Me

Body:
I have a RecyclerView adapter that looks like this:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private static Context context;
    private List<Message> mDataset;

    public RecyclerAdapter(Context context, List<Message> myDataset) {
        this.context = context;
        this.mDataset = myDataset;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, View.OnClickListener {
        public TextView title;
        public LinearLayout placeholder;

        public ViewHolder(View view) {
            super(view);
            view.setOnCreateContextMenuListener(this);

            title = (TextView) view.findViewById(R.id.title);
            placeholder = (LinearLayout) view.findViewById(R.id.placeholder);
        }
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_layout, parent, false);
        ViewHolder vh = new ViewHolder((LinearLayout) view);

        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Message item = mDataset.get(position);

        holder.title.setText(item.getTitle());

        int numImages = item.getImages().size();

        if (numImages > 0) {
            View test = LayoutInflater.from(holder.placeholder.getContext()).inflate(R.layout.images, holder.placeholder, false);
            ImageView image = (ImageView) test.findViewById(R.id.image);
            Glide.with(context)
                .load("http://www.website.com/test.png")
                .fitCenter()
                .into(image);
            holder.placeholder.addView(test);
        }
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}

However, some of the items in the RecyclerView are showing images when they shouldn't be. How can I stop this from happening?

I do the check if (numImages > 0) { in onBindViewHolder(), but that's still not stopping it from showing images for items that shouldn't have images.

Body:
   override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

This Works for Me


问:
Is there a way to prevent my application from running on sandboxie?
Is it possible to prevent or detect that my application is running on a sandboxie and not let it start or something alike ?

I have made a really silly easy game and have found out that people are using it on sandboxie in order to hack on it.

It constantly monitors the running process and other things to prevent hacks and while running on sandboxie the hack prevention in place becomes pretty useless.

答: Try a favourite-search-engine-here search for GetModuleHandle sandboxie


问:
Mongoose find() method not working with query parameters
I'm trying to find a particular document in mongodb  using Node Js and mongoose .

But when I'm running following code snippet I'm getting no response from database.

const express = require("express");
const router = express.Router();
const Vehicle = require("../db/models/vehicle");

//api to get single vehicle data
router.get("/vehicle", async (req, res, next) => {
  try {
    const { name } = req.query;
    console.log(name);
    const vehicle = await Vehicle.find({ name: name });
    res.status(200).json(vehicle);
  } catch (error) {
    res.status(500).json({ message: error });
  }
});```
</div>
</div>
</p>
<p>[postman image with no response][1]</p>
<p>But when I'm running following code snippet I'm getting  response from database.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require("express");
const router = express.Router();
const Vehicle = require("../db/models/vehicle");

//api to get single vehicle data
router.get("/vehicle", async (req, res, next) => {
  try {

    const vehicle = await Vehicle.find({ name: "BMW II" });
    res.status(200).json(vehicle);
  } catch (error) {
    res.status(500).json({ message: error });
  }
});</code>```

[postman image with response][2]
What should I do ?
[1]: https://i.stack.imgur.com/7svLJ.png
[2]: https://i.stack.imgur.com/ZgxRa.png

答:
As seen by this You are sending your query as name="BMW II" then in the server your name variable will be set to '"BMW II"' Therefore you will not get the correct results.

//your req will have a field like this
req = {query: { name: '"BMW II"' },...}
```
<p>when sending query strings you do not enclose in quotes even though it is string. query strings in express are by default identified as strings in the backend.<br />
just send in like <code>name=BMW II</code> and your name variable will be set to <code>'BMW II'</code>.</p>
<pre class="lang-js prettyprint-override"><code>req = {query: { name: 'BMW II' },...}
</code>```

In case you are sending a number as a query string say num=5 Then in the backend you will have parse it to an integer if you are willing to do calculations on it since it is received as string from req.query

req = {query: { num: '5' },...}
```

Body:
I'm trying to find a particular document in mongodb  using Node Js and mongoose .

But when I'm running following code snippet I'm getting no response from database.

const express = require("express");
const router = express.Router();
const Vehicle = require("../db/models/vehicle");

//api to get single vehicle data
router.get("/vehicle", async (req, res, next) => {
  try {
    const { name } = req.query;
    console.log(name);
    const vehicle = await Vehicle.find({ name: name });
    res.status(200).json(vehicle);
  } catch (error) {
    res.status(500).json({ message: error });
  }
});

[postman image with no response][1]

But when I'm running following code snippet I'm getting  response from database.

const express = require("express");
const router = express.Router();
const Vehicle = require("../db/models/vehicle");

//api to get single vehicle data
router.get("/vehicle", async (req, res, next) => {
  try {

    const vehicle = await Vehicle.find({ name: "BMW II" });
    res.status(200).json(vehicle);
  } catch (error) {
    res.status(500).json({ message: error });
  }
});

[postman image with response][2]
What should I do ?
[1]: https://i.stack.imgur.com/7svLJ.png
[2]: https://i.stack.imgur.com/ZgxRa.png

Body:
As seen by this You are sending your query as name="BMW II" then in the server your name variable will be set to '"BMW II"' Therefore you will not get the correct results.

//your req will have a field like this
req = {query: { name: '"BMW II"' },...}

when sending query strings you do not enclose in quotes even though it is string. query strings in express are by default identified as strings in the backend.

just send in like name=BMW II and your name variable will be set to 'BMW II'.

req = {query: { name: 'BMW II' },...}

In case you are sending a number as a query string say num=5 Then in the backend you will have parse it to an integer if you are willing to do calculations on it since it is received as string from req.query

req = {query: { num: '5' },...}


问:
Calculate mean of list elements inside and outside of range
I have the following dataframe:

```<code>import pandas as pd
mydict = {'ref_start': {0: 73, 1: 93, 2: 107, 3:150},
          'ref_end': {0: 74, 1: 95, 2: 109, 3:150}}
mydf = pd.DataFrame(mydict, columns = ["ref_start", "ref_end"])
</code>```

Which denotes the start and end of my indexes (plus 1, because my "ref_start" / "ref_end" is 1-indexed), in my list:

```<code>import numpy as np
import random
randomlist = []
for i in range(0,200):
    n = random.randint(5,60)
    randomlist.append(n)
</code>```

Now, I want to (1) calculate the mean of elements that are within the range of ref_start and ref_end:

```<code>mymean=[]
for i in range(0, len(mydf)):
   if randomlist[mydf.iloc[i]['ref_start']-1] == mydf.iloc[i]['ref_end']-1:
       mymean.append(np.mean(randomlist[mydf.iloc[i]['ref_start']-1]))
   else:
       mymean.append(np.mean(randomlist[mydf.iloc[i]['ref_start']-1:mydf.iloc[i]['ref_end']-1]))
</code>```

However, how do I get the mean of the ranges outside mydf, ie. from 1 (start) to 72, 75 to 92, 96 to 106, 110 to 149, and 151 to the end?

答:
I solved it now like this:</p>
```<code>elsemean=[]
for i in range(0,len(mydf)):
    if i == 0:
        elsemean.append(np.mean(randomlist[:int(mydf.iloc[i]["ref_start"]-1)]))
    if mydf.iloc[i]["ref_start"] == mydf.iloc[i]["ref_end"]:
        pass
    if i == len(mydf)-1:
        elsemean.append(np.mean(randomlist[int(mydf.iloc[i]["ref_end"]+1):]))
    else:
        i += 1
        elsemean.append(np.mean(randomlist[int(mydf.iloc[i-1]["ref_end"]+1):int(mydf.iloc[i]["ref_start"]-1)]))
</code>```

Body:
I have the following dataframe:

import pandas as pd
mydict = {'ref_start': {0: 73, 1: 93, 2: 107, 3:150},
          'ref_end': {0: 74, 1: 95, 2: 109, 3:150}}
mydf = pd.DataFrame(mydict, columns = ["ref_start", "ref_end"])

Which denotes the start and end of my indexes (plus 1, because my "ref_start" / "ref_end" is 1-indexed), in my list:

import numpy as np
import random
randomlist = []
for i in range(0,200):
    n = random.randint(5,60)
    randomlist.append(n)

Now, I want to (1) calculate the mean of elements that are within the range of ref_start and ref_end:

mymean=[]
for i in range(0, len(mydf)):
   if randomlist[mydf.iloc[i]['ref_start']-1] == mydf.iloc[i]['ref_end']-1:
       mymean.append(np.mean(randomlist[mydf.iloc[i]['ref_start']-1]))
   else:
       mymean.append(np.mean(randomlist[mydf.iloc[i]['ref_start']-1:mydf.iloc[i]['ref_end']-1]))

However, how do I get the mean of the ranges outside mydf, ie. from 1 (start) to 72, 75 to 92, 96 to 106, 110 to 149, and 151 to the end?

Body:
I solved it now like this:

elsemean=[]
for i in range(0,len(mydf)):
    if i == 0:
        elsemean.append(np.mean(randomlist[:int(mydf.iloc[i]["ref_start"]-1)]))
    if mydf.iloc[i]["ref_start"] == mydf.iloc[i]["ref_end"]:
        pass
    if i == len(mydf)-1:
        elsemean.append(np.mean(randomlist[int(mydf.iloc[i]["ref_end"]+1):]))
    else:
        i += 1
        elsemean.append(np.mean(randomlist[int(mydf.iloc[i-1]["ref_end"]+1):int(mydf.iloc[i]["ref_start"]-1)]))


答:
```<code>items_count2  = {}
for k, v in items_count.items():
  t = items_count2.get(k.split(':')[0],{})
  t[k.split(':')[1]] = v
  items_count2[k.split(':')[0]] = t
</code>```

output:

```<code>{'1111': {'190': 3, '201': 9, '271': 111},
 '1211': {'104': 111},
 '1231': {'106': 13}}
</code>```
```<code>{k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}
</code>```

will not give the desired solution because if the key already exists it will be replaced by the current one. So your values will always be a directory of single keys.

Title: Dictionary from another dictionary

Body:
items_count2  = {}
for k, v in items_count.items():
  t = items_count2.get(k.split(':')[0],{})
  t[k.split(':')[1]] = v
  items_count2[k.split(':')[0]] = t

output:

{'1111': {'190': 3, '201': 9, '271': 111},
 '1211': {'104': 111},
 '1231': {'106': 13}}

{k.split(':')[0]: {k.split(':')[1]: v} for k, v in items_count.items()}

will not give the desired solution because if the key already exists it will be replaced by the current one. So your values will always be a directory of single keys.


答:
Say we have a HashMap named as "Date1".
Well, now i can put a value with a key in this "Date1" HashMap & later can retrieve that value with the key -> Date1.get("key")

According to your diagram, the keys will be court1, court2, ....

So that, when i will ask for Date1.get("court1"), i can get this ArrayList

But, in this arraylist, each row consist of two values. If our list had one string values in each row, we could say that this is a arraylist of string type.

So lets make our own class (like a type) which can store two values (like "9:00", "player")

```<code>public class EntryInfo{
    String time, player;

    public EntryInfo(String time, String player) {
        this.time = time;
        this.player = player;
    }
}
</code>```

So if we create an object of "EntryInfo" class, that object will be able to store two values - and each row of our arraylist is of this type.

so, lets sum up :

our hashmap key will be "court1, court2..."
and each key will hold values of ArrayList<EntryInfo> type.

So our hashmap will be like HashMap< String, ArrayList<EntryInfo> >

Now, lets imagine the scenario according to your diagram.

first, lets talk about usage scenario.
Say, there are several courts in your school. They are named as court1, court2, court3, ...

well, I want today's entry-log for court1.
So, i will just ask for feb9.get("court1"), and it will return a list (ArrayList), and i can traverse that array to see the log like following:

```<code>for(EntryInfo entryinfo : feb9.get("court1") ) {
    System.out.println(entryinfo.time + " : " + entryinfo.player);
}

</code>```

Yeah, thats it. If i want to get the log for court2, i will retrieve the value using key "court2"

Now, lets discuss how to make this.

well today is feb9, lets make a hashmap to store today's entry log. Lets name the hashmap "feb9"

```<code>HashMap<String, ArrayList<EntryInfo>> feb9 = new HashMap<String, ArrayList<EntryInfo>>();
</code>```

your school has 3 courts. Lets add 3 different keys to this hashmap so that it can hold 3 separate and corresponding entry-logs for each key(court)

```<code>feb9.put("court1", new ArrayList<EntryInfo>());
feb9.put("court2", new ArrayList<EntryInfo>());
feb9.put("court3", new ArrayList<EntryInfo>());
</code>```

You can relate this with creating 3 new files named court1, court2 & court3. Each file consists of an ArrayList object, which is empty for now.

Say, now at 9:00 am, player "zineryt" enters court1. Lets entry the log into our hashmap

```<code>feb9.get("court1").add(new EntryInfo("9:00", "zineryt"));
</code>```

Here feb9.get("court1") will return an ArrayList, and we used add() method to insert elements into the ArrayList.

say, at 9:50am, player "bigboy" enters court1. We can entry the log like below

```<code>feb9.get("court1").add(new EntryInfo("9:50", "bigboy"));
</code>```

and it goes like this.

For tomorrow's information, we will create another new HashMap named feb10 and will follow the same steps.

Title: Java - HashMap for booking system

Body:
I have been given an exercise to develop an appropriate data structure to implement a tennis court booking system.

A hashmap is what is required for this and I was given a diagram as a visual representation of the data structure.

From looking at the diagram, I am unclear on how the Key and Value should be defined in the HashMap. Should 'Court' be a class, which is the Key?

For the value, it shows a time, and a players name. How would the value be defined, since it has two values of time and player name?

diagram link

Body:
Say we have a HashMap named as "Date1".
Well, now i can put a value with a key in this "Date1" HashMap & later can retrieve that value with the key -> Date1.get("key")

According to your diagram, the keys will be court1, court2, ....

So that, when i will ask for Date1.get("court1"), i can get this ArrayList

But, in this arraylist, each row consist of two values. If our list had one string values in each row, we could say that this is a arraylist of string type.

So lets make our own class (like a type) which can store two values (like "9:00", "player")

public class EntryInfo{
    String time, player;

    public EntryInfo(String time, String player) {
        this.time = time;
        this.player = player;
    }
}

So if we create an object of "EntryInfo" class, that object will be able to store two values - and each row of our arraylist is of this type.

so, lets sum up :

our hashmap key will be "court1, court2..."
and each key will hold values of ArrayList<EntryInfo> type.

So our hashmap will be like HashMap< String, ArrayList<EntryInfo> >

Now, lets imagine the scenario according to your diagram.

first, lets talk about usage scenario.
Say, there are several courts in your school. They are named as court1, court2, court3, ...

well, I want today's entry-log for court1.
So, i will just ask for feb9.get("court1"), and it will return a list (ArrayList), and i can traverse that array to see the log like following:

for(EntryInfo entryinfo : feb9.get("court1") ) {
    System.out.println(entryinfo.time + " : " + entryinfo.player);
}

Yeah, thats it. If i want to get the log for court2, i will retrieve the value using key "court2"

Now, lets discuss how to make this.

well today is feb9, lets make a hashmap to store today's entry log. Lets name the hashmap "feb9"

HashMap<String, ArrayList<EntryInfo>> feb9 = new HashMap<String, ArrayList<EntryInfo>>();

your school has 3 courts. Lets add 3 different keys to this hashmap so that it can hold 3 separate and corresponding entry-logs for each key(court)

feb9.put("court1", new ArrayList<EntryInfo>());
feb9.put("court2", new ArrayList<EntryInfo>());
feb9.put("court3", new ArrayList<EntryInfo>());

You can relate this with creating 3 new files named court1, court2 & court3. Each file consists of an ArrayList object, which is empty for now.

Say, now at 9:00 am, player "zineryt" enters court1. Lets entry the log into our hashmap

feb9.get("court1").add(new EntryInfo("9:00", "zineryt"));

Here feb9.get("court1") will return an ArrayList, and we used add() method to insert elements into the ArrayList.

say, at 9:50am, player "bigboy" enters court1. We can entry the log like below

feb9.get("court1").add(new EntryInfo("9:50", "bigboy"));

and it goes like this.

For tomorrow's information, we will create another new HashMap named feb10 and will follow the same steps.