问:
How to get domain/referer name from POST form that action points to other domain
I have a form on domain-x.com. Which sends the form data to another domain-y.com service which handles it.

```<code><form method="POST" action="http://domain-y.com/">
  <input type="email" name="email" placeholder="Your email">
  <button type="submit">Send</button>
</form>
</code>```

How can i get the referer or to be sure that this form's request comes from domain-x.com?

I use Symfony\Component\HttpFoundation\Request, but it not contains any information about domain-x.com

$_SERVER['HTTP_REFERER'] does not work

EDIT:
I don't want to change my form. The problem is somehow via request i should be able where the request comes from...

答:
You could add in a hidden field.

```<code><input type='hidden' name='referrer' value='<?=$_SERVER['SERVER_NAME']?>'/>
</code>```

It seems quite unorthodox to be posting a form to an entirely different domain however.

You can spoof $_SERVER['HTTP_REFERER'] so either way isn't entirely reliable

Documentation on HTTP_REFERER

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

https://php.net/manual/en/reserved.variables.server.php

Body:
I have a form on domain-x.com. Which sends the form data to another domain-y.com service which handles it.

<form method="POST" action="http://domain-y.com/">
  <input type="email" name="email" placeholder="Your email">
  <button type="submit">Send</button>
</form>

How can i get the referer or to be sure that this form's request comes from domain-x.com?

I use Symfony\Component\HttpFoundation\Request, but it not contains any information about domain-x.com

$_SERVER['HTTP_REFERER'] does not work

EDIT:
I don't want to change my form. The problem is somehow via request i should be able where the request comes from...

Body:
You could add in a hidden field.

<input type='hidden' name='referrer' value='<?=$_SERVER['SERVER_NAME']?>'/>

It seems quite unorthodox to be posting a form to an entirely different domain however.

You can spoof $_SERVER['HTTP_REFERER'] so either way isn't entirely reliable

Documentation on HTTP_REFERER

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

https://php.net/manual/en/reserved.variables.server.php


来源: stackexchange

问:
Dockerize - Rails application curl: (7) Failed to connect to localhost
I have a ruby on rails application. It works on my mac machine. I want to dockerize it.

Docker file is below:

```<code>....
EXPOSE 3000

# Start the main process.
CMD ["rails", "server"]
</code>```

I build the app and it works fine.

```<code>$docker build -t my-rails-app .
</code>```

Docker image id

```<code>$docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
1f02e0e60da5        my-rails-app        "rails server"      5 minutes ago       Up 5 minutes        0.0.0.0:3000->3000/tcp   dazzling_hamilton
</code>```

Get ip address

```<code>$docker inspect 1f02e0e60da5 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",
</code>```

No response for http request
$ curl 172.17.0.2:3000

```<code>curl: (7) Failed to connect to 172.17.0.2 port 3000: Operation timed out
</code>```

答:
Update Dockerfile

```<code>...
EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]
</code>```

run command:

```<code>curl -X GET   http://localhost:3000
</code>```

It works for me!

ContentLicense: CC BY-SA 4.0

Body:
I have a ruby on rails application. It works on my mac machine. I want to dockerize it.

Docker file is below:

....
EXPOSE 3000

# Start the main process.
CMD ["rails", "server"]

I build the app and it works fine.

$docker build -t my-rails-app .

Docker image id

$docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
1f02e0e60da5        my-rails-app        "rails server"      5 minutes ago       Up 5 minutes        0.0.0.0:3000->3000/tcp   dazzling_hamilton

Get ip address

$docker inspect 1f02e0e60da5 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

No response for http request
$ curl 172.17.0.2:3000

curl: (7) Failed to connect to 172.17.0.2 port 3000: Operation timed out

Body:
Update Dockerfile

...
EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

run command:

curl -X GET   http://localhost:3000

It works for me!


问:
Laravel Include Blade
Good day,

Here is my directory structure for blades.

```<code>resources/views/red/main.blade.php
resources/views/red/include_me.blade.php
resources/views/blue/main.blade.php
resources/views/blue/include_me.blade.php
</code>```

This is the include in the red main.blade.php...

```<code>@include('red.include_me')
</code>```

This is the include in the blue main.blade.php...

```<code>@include('blue.include_me')
</code>```

Is there a way to include it so I no longer have to specify red or blue?

```<code>@include('include_me')
</code>```

答:
You can use this</p>

```<code>@php $part = (condition) ?  'red' : 'blue'; @endphp
@include($part . '.include_me')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Laravel Include Blade

Body:
Good day,

Here is my directory structure for blades.

resources/views/red/main.blade.php
resources/views/red/include_me.blade.php
resources/views/blue/main.blade.php
resources/views/blue/include_me.blade.php

This is the include in the red main.blade.php...

@include('red.include_me')

This is the include in the blue main.blade.php...

@include('blue.include_me')

Is there a way to include it so I no longer have to specify red or blue?

@include('include_me')

Body:
You can use this

@php $part = (condition) ?  'red' : 'blue'; @endphp
@include($part . '.include_me')


问:
C++ - Speed up installs using vcpkg
I am new to C++ and needed to download a package, so I thought I would use vcpkg. The problem is vcpkg was slower than I expected. Here is my syntax:

```<code>vcpkg install <PACKAGE>
</code>```

Vcpkg takes a lot of time, which makes me wonder if there is a flag to speed up the vcpkg download speed.

答:
vcpkg does not download pre-built binaries; it downloads source files and does the builds on your machine.

Therefore, it is most likely not the download that is taking up a lot of time, but the build itself. There is no flag that can speed up the builds, but it is possible to export binaries, so you really only have to build a specific set of libraries only once.

If you are interested in why vcpkg chooses to be source-based as opposed to binary-based, you can consult this

Title: C++ - Speed up installs using vcpkg

Body:
I am new to C++ and needed to download a package, so I thought I would use vcpkg. The problem is vcpkg was slower than I expected. Here is my syntax:

vcpkg install <PACKAGE>

Vcpkg takes a lot of time, which makes me wonder if there is a flag to speed up the vcpkg download speed.


问:
Proper way to spawn a gameobject that grows in scale from 0 to 1
The menu system in the game I'm working on has a "pop" animation where it grows from scale 0 to scale 1 when it spawns.  When the player gets a game over, the menu is instantiated and then the "pop" animation is triggered, causing the menu to pop in from the center of the screen.

This works fine most of the time. However, sometimes the menu will appear for a single frame at full size after it's instantiated. Then, the animation gets triggered which causes it to snap back to scale 0 and grow back to scale 1.

I've come up with a workaround for this which is to save the menu prefab at scale 0, so when the menu is instantiated it's already at scale 0 before the animation begins. The downside to this is that when I'm working on the menu in the editor, I have to go back and set the scale of the menu to 1 so I can work on it and then remember to set it back to 0 when I'm done.

Is there any way around this?

As seen below, the Game_Over_Open ("pop") animation sets the scale to 0 on the first frame.

Here is the animator that controls the "pop" animation.  There are actually 2 different animations that need to be called based on a condition, so I cannot set this animation to be the entry state. Instead, the entry state is an empty state I have labeled as "Idle."

I tried setting the scale of the menu to 0 in the Awake() of the menu script, but that did not fix it. There is still a single frame where the menu appears at full size.

答: I solved this issue by setting the empty "Idle" entry state of the animator to an animation that set the scale of the menu to 0 on the first frame.</p>


问:
Need to add multiple elements to search for a particular class with jQuery
I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?

Here's my current code:

```<code>$findRed = $("p.red", "#main");

if ( $findRed.length >= 1 ) {
    greater or equal to one
}
</code>```

I need to change it so it will look for .red in either a p, div, or span tag.

Any help would be appreciate.

答:
try this:</p>

```<code>$findRed = $("p.red", $("#main, #main2, #main3"));
//will look in main, main2 and main3

if ( $findRed.length >= 1 ) {
    greater or equal to one
}
</code>```

Body:
I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?

Here's my current code:

$findRed = $("p.red", "#main");

if ( $findRed.length >= 1 ) {
    greater or equal to one
}

I need to change it so it will look for .red in either a p, div, or span tag.

Any help would be appreciate.

Body:
try this:

$findRed = $("p.red", $("#main, #main2, #main3"));
//will look in main, main2 and main3

if ( $findRed.length >= 1 ) {
    greater or equal to one
}


问:
add ajax button in django to update user`s choice
I have followed the tutorial by Mozilla described here and have made some modifications to make it into a movie library.

I would like to add the option for a user when he opens a movie to be able to mark it as "seen". I would like to do that using ajax so the button the user would click would change as well without refreshing the page.

This is the model used to store the user choice

```<code>class Seenit(models.Model):
    username = models.CharField(max_length=150)
    movieid = models.ForeignKey('Movie', on_delete=models.CASCADE)
    haveyouseenit = models.BooleanField(default=False, null=True, blank=True)

    def __str__(self):
        return f"{self.username}|{self.movieid.id}"
</code>```

this is from the urls.py

```<code>re_path(r'^add_to_seen/(?P<pk>.*)', views.Addseen.as_view(), name='add_to_seen')
</code>```

This is from the views.py

```<code>class Addseen(generic.DetailView):
    model = Seenit

    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            check = get_object_or_404(Seenit, movieid=id, username=request.user.get_username())
            if not check.haveyouseenit:
                check.haveyouseenit == True
                check.save()
                return HttpResponse("1")
            else:
                check.haveyouseenit == False
                check.save()
                return HttpResponse("0")
</code>```

and this is from the movie_details.html showing the button along with an attempt I made for the ajax button.

```<code>    <div id="seen">
        {%  if user.is_authenticated  %}
            <button class="add_button" id="seen">Have seen</button>
            <b style="color: #3b97f4" id="message"></b>
            {%  if seen %}
                <script>
                    $("#seen").css({"background-color": "#f4b6e0", "color": "white"});
                </script>
            {% endif %}
        {% endif %}
                    <script>
                    $(document).ready(function () {
                        $("#seen").click(function () {
                            $.get("/add_to_seen/{{ movie.id }}", function (msg) {
                                if (msg === "1") {
                                    $("#seen").css({"background-color": "#f4f15f", "color": "white"});
                                    $("#message").html("Added to Seen!").fadeIn("fast").fadeOut("slow");
                                }
                                if (msg === "0") {
                                    $("#seen").css({"background-color": "white", "color": "black"});
                                    $("#message").html("Deleted from Seen!").fadeIn("fast").fadeOut("slow");
                                }
                            });
                        });
                    });
                </script>
    </div>
</code>```

The button appears when i visit a movie, but it does not do anything. I am very novice with django and javascript/ajax so any information you might provide please explain it.

答:
```<code><button class="add_button" id="seen" onclick="Seen({{movie.id}})">Have seen</button>
</code>```

in javascript:

```<code>function Seen(n){
var patch = '{% url "add_to_seen" %}'
info = {'pk':n, 'csrfmiddlewaretoken':"{{ csrf_token }}"}

$.ajax({
  type: "POST",
  url: patch,
  data:info,
    datatype:'json',

success: function(){

console.log('success')
return

}

})
}
</code>```

views:

```<code> def Addseen(request):
    if request.method == 'POST':
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        pk = data['pk']
           #do whatever you have to do with the model.

       return JsonResponse(safe=False)
</code>```

If you need further help, lemme know.

Body:
I have followed the tutorial by Mozilla described here and have made some modifications to make it into a movie library.

I would like to add the option for a user when he opens a movie to be able to mark it as "seen". I would like to do that using ajax so the button the user would click would change as well without refreshing the page.

This is the model used to store the user choice

class Seenit(models.Model):
    username = models.CharField(max_length=150)
    movieid = models.ForeignKey('Movie', on_delete=models.CASCADE)
    haveyouseenit = models.BooleanField(default=False, null=True, blank=True)

    def __str__(self):
        return f"{self.username}|{self.movieid.id}"

this is from the urls.py

re_path(r'^add_to_seen/(?P<pk>.*)', views.Addseen.as_view(), name='add_to_seen')

This is from the views.py

class Addseen(generic.DetailView):
    model = Seenit

    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            check = get_object_or_404(Seenit, movieid=id, username=request.user.get_username())
            if not check.haveyouseenit:
                check.haveyouseenit == True
                check.save()
                return HttpResponse("1")
            else:
                check.haveyouseenit == False
                check.save()
                return HttpResponse("0")

and this is from the movie_details.html showing the button along with an attempt I made for the ajax button.

        {%  if user.is_authenticated  %}
            <button class="add_button" id="seen">Have seen</button>

            {%  if seen %}

            {% endif %}
        {% endif %}

The button appears when i visit a movie, but it does not do anything. I am very novice with django and javascript/ajax so any information you might provide please explain it.

Body:
<button class="add_button" id="seen" onclick="Seen({{movie.id}})">Have seen</button>

in javascript:

function Seen(n){
var patch = '{% url "add_to_seen" %}'
info = {'pk':n, 'csrfmiddlewaretoken':"{{ csrf_token }}"}

$.ajax({
  type: "POST",
  url: patch,
  data:info,
    datatype:'json',

success: function(){

console.log('success')
return

}

})
}

views:

 def Addseen(request):
    if request.method == 'POST':
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        pk = data['pk']
           #do whatever you have to do with the model.

       return JsonResponse(safe=False)

If you need further help, lemme know.


答:
Change your CMD for this one

```<code>CMD rails s -p 3000 -b '0.0.0.0'
</code>```

You dont need to get the docker ip because it is being exposed on the localhost, so you can just do

curl localhost:3000

Title: Dockerize - Rails application curl: (7) Failed to connect to localhost

Body:
Change your CMD for this one

CMD rails s -p 3000 -b '0.0.0.0'

You dont need to get the docker ip because it is being exposed on the localhost, so you can just do

curl localhost:3000


问:
Why exit code 141 with grep -q?
Can someone explain why I get exit code 141 from the below?

```<code>#!/usr/bin/bash

set -o pipefail

zfs list | grep tank
echo a ${PIPESTATUS[@]}

zfs list | grep -q tank
echo b ${PIPESTATUS[@]}

cat /etc/passwd | grep -q root
echo c ${PIPESTATUS[@]}
</code>```

I get

```<code>...
a 0 0
b 141 0
c 0 0
</code>```

From my understanding exit code 141 is a failure, but the line above gives zero, so it should be success, I would say.

答:
Another option would be to not use a pipe, but use a process substitution:

grep -q tank <(zfs list)

Update: I guess is the same thing, as the process run inside parentheses will also receive sigpipe.

Title: Why exit code 141 with grep -q?

Body:
Can someone explain why I get exit code 141 from the below?

#!/usr/bin/bash

set -o pipefail

zfs list | grep tank
echo a ${PIPESTATUS[@]}

zfs list | grep -q tank
echo b ${PIPESTATUS[@]}

cat /etc/passwd | grep -q root
echo c ${PIPESTATUS[@]}

I get

...
a 0 0
b 141 0
c 0 0

From my understanding exit code 141 is a failure, but the line above gives zero, so it should be success, I would say.


问:
How to open a specific web page once submit button is clicked in the form?
I would like the submit button to display a specific page once it's clicked.

I know how to process the data sent from the form, but after processing the data I want to go to a specific page like "homepage" which I have already created before.

答:
You can add an action attribute to the <form> tag like this:

```<code>  <form action="homepage.php">
       <input type="submit" value="Submit" />
  </form>
</code>```

When you click on the submit button, you will be navigated to homepage.php page. I think this is what you need.

Body:
You can add an action attribute to the <form> tag like this:

  <form action="homepage.php">
       <input type="submit" value="Submit" />
  </form>

When you click on the submit button, you will be navigated to homepage.php page. I think this is what you need.


问:
»function windowResized()« on smartphones
I work with p5.js. To adjust sketches for different window sizes this helps:

```<code>function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}
</code>```

But: It seems that it does not work on smartphones. I have a new iPhone with Google Chrome installed. If I hold my phone vertical, the Sketches run, if I tilt then my phone horizontal, the Sketch area is much smaller.

Is there a way to solve this? I have this problem also with paper.js.

Love

答:
Solution:</p>

```<code>if (window.DeviceOrientationEvent) { window.addEventListener('orientationchange', function() { location.reload(); }, false); }
</code>```

Body:
I work with p5.js. To adjust sketches for different window sizes this helps:

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

But: It seems that it does not work on smartphones. I have a new iPhone with Google Chrome installed. If I hold my phone vertical, the Sketches run, if I tilt then my phone horizontal, the Sketch area is much smaller.

Is there a way to solve this? I have this problem also with paper.js.

Love

Body:
Solution:

if (window.DeviceOrientationEvent) { window.addEventListener('orientationchange', function() { location.reload(); }, false); }


问:
how could I recover deleted forked branch for pull request
I created a new pull request on github, and I happened to deleted the forked branch in my github account. Now the reviewers ask me modify something in the code, but I find my pr is isolated and I cannot modify it directly.

I got to find this document, but I do not know what the step of $ git fetch origin pull/ID/head:BRANCHNAME mean.

Suppose my pr ID is #708 and the repository that I submit my pr into is https://github.com/facebookresearch/maskrcnn-benchmark and I would like to have my pr merged into the master branch.

I tried to use git fetch origin pull/#708/https://github.com/facebookresearch/maskrcnn-benchmark:master, but it failed.

How could I continue to commit my pr please?

by the way, if I have a pr under-reviewing, how could I submit another pr without deleting the existing fork?

答:
Italics are crucial in the document you found. Everything not in italics is literal, which includes head. The ID only refers to the digits (no #, the included screenshot is a little unlucky):

```<code>$ git fetch origin pull/708/head:foobar
</code>```

will do the job, with foobar being your new local branch name for the pull request.

Body:
Italics are crucial in the document you found. Everything not in italics is literal, which includes head. The ID only refers to the digits (no #, the included screenshot is a little unlucky):

$ git fetch origin pull/708/head:foobar

will do the job, with foobar being your new local branch name for the pull request.


问:
Different ways to install numpy, scipy, and matplotlib on macOS via homebrew
Today I decided to install python and the scipy stack manually, instead of using Anaconda (or Canopy) as I had previously done. I use homebrew on my mac and have python2 and python3 (2.7 and 3.6) installed via homebrew. But reading through the documentation, there are multiple ways to install the scipy stack and I want to know what the differences are. I have tested they independently and they all work.

From the Homebrew documentation:

python2 -m pip install numpy scipy matplotlib

python3 -m pip install numpy scipy matplotlib

These are the same two commands that the Matplotlib installation docuentation lists for how to install matplotlib through homebrew. Why does this use pip (the system Python 2.7.x's pip) instead of pip2 and pip3 respectively? Is it because you call python2/python3 first?

However, the SciPy documentation for installing these modules when using homebrew is different:

brew tap homebrew/science && brew install numpy scipy matplotlib

(NOTE: the matplotlib formula is located in the homebrew/science repository, which is why you need to use brew tap.)

Finally, from the command line readout when installing python2 and python3 via homebrew:

pip2 install numpy scipy matplotlib

pip3 install numpy scipy matplotlib

which are based on the following readouts:

```<code>Pip and setuptools have been installed. To update them
  pip2 install --upgrade pip setuptools

You can install Python packages with
  pip2 install <package>

They will install into the site-package directory
  /usr/local/lib/python2.7/site-packages

See: https://docs.brew.sh/Homebrew-and-Python.html

...

Pip, setuptools, and wheel have been installed. To update them
  pip3 install --upgrade pip setuptools wheel

You can install Python packages with
  pip3 install <package>

They will install into the site-package directory
  /usr/local/lib/python3.6/site-packages

See: https://docs.brew.sh/Homebrew-and-Python.html
</code>```

So between four sources of documentation, there are three different ways to install scipy when using homebrew and they all work; but how is each different and should one be preferred?

From what I can tell, the first and third methods, which both invoke pip (pip2/pip3), are functionally equivalent - both invoke Homebrew's Python X.X.X's pip - but one implicitly, the other explicitly. I assume this means both methods install the pre-built binary packages from pip in the form of wheels. For the second method, I think it installs homebrew's own formulae for these packages (i.e. maintained separately by homebrew in it's repository).

If this is true, then I assume one should use the second method if you are using a version of python which is maintained by homebrew (i.e. installed via brew install python or python3). My reasoning is that if you later decide to install another formula via homebrew that has any of the scipy stack as a dependency, it will install those modules again from homebrew's repository if you installed them using pip previously.

As mentioned, I am not sure if my understanding is correct and I have not been able to find any answers, so any insights or confirmations would be appreciated.

答:
Your analysis seems correct: variants 1 and 3 will install numpy/scipy from the python package index (PyPI) and will use pre-built wheels (if available for your platform, which they most likely are).
Variant 2 installs the brew formula.

As mentioned by @Evhz, the conda packages for numpy and scipy use the Intel Math Kernel library, which can provide significant speedups (not just on Intel processors) versus the packages installed from PyPI or brew, both of which are linked against OpenBLAS.

Concerning which method to prefer: it's not entirely straightforward.

Yes, on the surface, using brew to manage both the python interpreter and the python packages would seem consistent.

However, homebrew only provides formulae for a handful of python packages, so you'll end up needing to mix with pip in any case.

If you want performance, you go with conda, which will be managing both the interpreter and python packages.

However, also anaconda / conda-forge still have some catching up to do with PyPI, so you'll likely need to mix with pip again.

In the end, there is no perfect solution but as long as you knowingly decide for one, you're unlikely to run into issues.

Body:
Today I decided to install python and the scipy stack manually, instead of using Anaconda (or Canopy) as I had previously done. I use homebrew on my mac and have python2 and python3 (2.7 and 3.6) installed via homebrew. But reading through the documentation, there are multiple ways to install the scipy stack and I want to know what the differences are. I have tested they independently and they all work.

From the Homebrew documentation:

python2 -m pip install numpy scipy matplotlib

python3 -m pip install numpy scipy matplotlib

These are the same two commands that the Matplotlib installation docuentation lists for how to install matplotlib through homebrew. Why does this use pip (the system Python 2.7.x's pip) instead of pip2 and pip3 respectively? Is it because you call python2/python3 first?

However, the SciPy documentation for installing these modules when using homebrew is different:

brew tap homebrew/science && brew install numpy scipy matplotlib

(NOTE: the matplotlib formula is located in the homebrew/science repository, which is why you need to use brew tap.)

Finally, from the command line readout when installing python2 and python3 via homebrew:

pip2 install numpy scipy matplotlib

pip3 install numpy scipy matplotlib

which are based on the following readouts:

Pip and setuptools have been installed. To update them
  pip2 install --upgrade pip setuptools

You can install Python packages with
  pip2 install <package>

They will install into the site-package directory
  /usr/local/lib/python2.7/site-packages

See: https://docs.brew.sh/Homebrew-and-Python.html

...

Pip, setuptools, and wheel have been installed. To update them
  pip3 install --upgrade pip setuptools wheel

You can install Python packages with
  pip3 install <package>

They will install into the site-package directory
  /usr/local/lib/python3.6/site-packages

See: https://docs.brew.sh/Homebrew-and-Python.html

So between four sources of documentation, there are three different ways to install scipy when using homebrew and they all work; but how is each different and should one be preferred?

From what I can tell, the first and third methods, which both invoke pip (pip2/pip3), are functionally equivalent - both invoke Homebrew's Python X.X.X's pip - but one implicitly, the other explicitly. I assume this means both methods install the pre-built binary packages from pip in the form of wheels. For the second method, I think it installs homebrew's own formulae for these packages (i.e. maintained separately by homebrew in it's repository).

If this is true, then I assume one should use the second method if you are using a version of python which is maintained by homebrew (i.e. installed via brew install python or python3). My reasoning is that if you later decide to install another formula via homebrew that has any of the scipy stack as a dependency, it will install those modules again from homebrew's repository if you installed them using pip previously.

As mentioned, I am not sure if my understanding is correct and I have not been able to find any answers, so any insights or confirmations would be appreciated.


问:
How to return the value of execute in PDO wrapper
Beneath is my PDO wrapper. I want to be able to use the run method however, I want to be able to check if the execution has been successful such as:

if($sth->execute())
{
   ...
}
```

<p>However, as you can see within the wrapper, the run command only returns the <code>prepare</code> statement, what would be the most efficient way to achieve this?</p>

<pre class="lang-php prettyprint-override"><code><?php

class Database {

    const hostname = 'localhost';
    const user = 'root';
    const password = '';
    const charset = 'utf8';
    const database = 'syn_v2';

    protected static $instance;
    protected $pdo;

    protected function __construct()
    {
        $opt = array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
            PDO::ATTR_EMULATE_PREPARES => false
        );

        $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', self::hostname, self::database, self::charset);

        $this->pdo = new PDO($dsn, self::user, self::password);
    }

    public static function instance()
    {
        if(self::$instance === null)
        {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public function __call($method, $args)
    {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    public function run($sql, $args = [])
    {
        if(!$args)
        {
            return $this->query($sql);
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);

        return $stmt;
    }

}

?>
</code>```

答:
Since PDOStatement::execute returns true/false and your current run method is returning a PDOStatement on success and false on failure. I suggest checking prepare and execute are not false and return the PDOStatement on success or false otherwise, as is the case with PDO::prepare and PDO::query.

Functional Example https://3v4l.org/OnDdn

```<code>/**
 * @return PDOStatement|false
 */
public function run($sql, $args = [])
{
    if (!$args) {
        return $this->pdo->query($sql);
    }
    if ($stmt = $this->pdo->prepare($sql)) {
        if ($stmt->execute($args)) {
            return $stmt;
        }
    }

    return false; //either prepare or execute failed
}
</code>```

```<code>$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])); //false
</code>```

An alternative approach would be to store the last execute value in a property, for later retrieval.

Example https://3v4l.org/UbM1N

```<code>class Database
{

    protected $lastExecute;

   //...

    /**
     * @return PDOStatement|false
     */
    public function run($sql, $args = [])
    {
        if (!$args) {
            return $this->pdo->query($sql);
        }
        if ($stmt = $this->pdo->prepare($sql)) {
            $this->lastExecute = $stmt->execute($args);
        }

        return $stmt;
    }

    /**
     * @return null|bool
     */
    public function getLastExecute()
    {
       return $this->lastExecute;
    }
}
</code>```

```<code>$db = Database::instance();
$db->run('SELECT ?', ['foo', 'bar']);
var_dump($db->getLastExecute()); //false
</code>```

To address the best-practices comments below in regard to the issue of determining when PDO::execute method specifically fails from within the Database::run method by using Exception handling.

Please keep in mind Best-Practices are not about right or wrong, "they are simply recommended methods of writing code." Referring to an approach of programming that is commonly preferred in professional application development. Always use what works best for you, the environment you are developing for and your application requirements.

Generally speaking StackOverlow is not an appropriate place to discuss or evaluate an author's application of
best-practices. Those types of discussions or critiques should be reserved for CodeReview. StackOverflow is
intended to answer the author's specific
question, or provide a viable alternative method to accomplish what the user is asking for. Not infer the user has asked the wrong question.

To use exceptions you need to enable PDO::ERRMODE_EXCEPTION (see below Database class).

The issue with using try/catch with a PDO wrapper method, is that PDO will only throw a single Exception object PDOException, which does not provide you with the ability to determine which PDO method call specifically failed. Leaving you to read the PDOException::getMessage() or PDOException::getTrace(), to determine the cause.

A simple approach would be to check the PDOException::trace for the function name that caused the exception.

Functional Example (PHP 5.6+): https://3v4l.org/fDnBI

```<code>try {
   $db = Database::instance();
   var_dump($db->run('SELECT ?', ['foo', 'bar'])->fetch());
} catch(\PDOException $e) {
   if ('execute' === $e->getTrace()[0]['function']) {
       echo 'PDO::execute() failed';
       //Handle the execute exception
   }
   throw $e;
}
</code>```

Please see the answer on PDO mysql: How to know if insert was
successful by Your
Common Sense for a more generalized approach to PDOException
handling.

The above approach prevents you from handling only specific exception types within the Database::run method, requiring you to use throw $e; after your conditional, when the exception is unexpected.

To account for this issue, another approach would be to create custom Exception classes. You can do this by extending the base PDOException class to be compliant with other exception handling methods or to catch any of them.

In order to catch any of the run specific exceptions, an empty interface can be used that is then implemented on the extended PDOException classes.

```<code>interface DatabaseRunException{}
</code>```

Then create a new exception class for each of the specific PDO methods you would like to handle, that implements the DatabaseRunException interface.

```<code>class PDOPrepareException extends PDOException implements DatabaseRunException{}

class PDOExecuteException extends PDOException implements DatabaseRunException{}

class PDOQueryException extends PDOException implements DatabaseRunException{}
</code>```

To use the custom exceptions to determine which PDO method failed, you need to handle the PDOException(s) within the Database::run() method and throw one of the custom exceptions.

I have removed certain portions for brevity, commented out things that would alter your current configuration, made some best-practices and optimization changes for PHP 5.6+.

```<code>class Database
{

    private const OPTIONS = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        // PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
        // PDO::ATTR_EMULATE_PREPARES => false
    ];

    //...

    protected function __construct()
    {
        $this->pdo = new PDO($dsn, self::user, self::password, self::OPTIONS);
    }

    public static function instance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public function __call($method, $args)
    {
        //always ensure the desired method is callable!
        if (is_callable([$this->pdo, $method])) {
            //php 5.6+ variadic optimization (aka splat operator)
            return $this->pdo->$method(...$args);

            //php <= 5.5
            //return call_user_func_array(array($this->pdo, $method), $args);
        }
        throw new \BadMethodCallException(sprintf('Unknown method PDO::%s called!', $method));
    }

    public function run($sql, $args = [])
    {
        if (!$args) {
            try {
                return $this->query($sql);
            } catch(\PDOException $e) {
                 throw new \PDOQueryException($e->getMessage(), (int) $e->getCode(), $e);
            }
        }
        try {
            $stmt = $this->prepare($sql);
        } catch(\PDOException $e) {
            throw new \PDOPrepareException($e->getMessage(), (int) $e->getCode(), $e);
        }
        try {
            $stmt->execute($args);

            return $stmt;
        } catch(\PDOException $e) {
            throw new \PDOExecuteException($e->getMessage(), (int) $e->getCode(), $e);
        }

        throw new \LogicException('Unknown error occurred');
    }

}
</code>```

Functional Example (PHP 5.6+): https://3v4l.org/8QoRF

You will now be able to handle each of the exceptions for any of the specific types.

```<code>try {
   $db = Database::instance();
   $db->run('SELECT ?', ['foo', 'bar']);
} catch(\PDOExecuteException $e) {
    echo 'PDO::execute() failed';
    //Handle the execute exception
    throw $e;
}
</code>```

In PHP 7.1+ you can catch multiple exceptions.

```<code>try {
   $db = Database::instance();
   $db->run('SELECT ?', ['foo', 'bar']);
} catch(\PDOQueryException $e) {
    //Handle the query exception
    throw $e;
} catch(\PDOPrepareException $e) {
    //Handle the prepare exception
    throw $e;
} catch(\PDOExecuteException $e) {
    echo 'PDO::execute() failed';
    //Handle the execute exception
    throw $e;
}
</code>```

In PHP <= 7.0 you can use the DatabaseRunException interface to catch and check the specific exceptions caused by Database::run() with instanceof to determine which exception was actually thrown.

```<code>$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])); //false
</code>```0

As you can see, this increases the code complexity and will be up to you on determining what best suits your application needs.

It is important to note, that variables declared in the try section will not be declared if an exception occurs prior to the declaration.

```<code>$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])); //false
</code>```1

Body:
Beneath is my PDO wrapper. I want to be able to use the run method however, I want to be able to check if the execution has been successful such as:

if($sth->execute())
{
   ...
}

However, as you can see within the wrapper, the run command only returns the prepare statement, what would be the most efficient way to achieve this?

<?php

class Database {

    const hostname = 'localhost';
    const user = 'root';
    const password = '';
    const charset = 'utf8';
    const database = 'syn_v2';

    protected static $instance;
    protected $pdo;

    protected function __construct()
    {
        $opt = array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
            PDO::ATTR_EMULATE_PREPARES => false
        );

        $dsn = sprintf('mysql:host=%s;dbname=%s;charset=%s', self::hostname, self::database, self::charset);

        $this->pdo = new PDO($dsn, self::user, self::password);
    }

    public static function instance()
    {
        if(self::$instance === null)
        {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public function __call($method, $args)
    {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    public function run($sql, $args = [])
    {
        if(!$args)
        {
            return $this->query($sql);
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);

        return $stmt;
    }

}

?>

Body:
Since PDOStatement::execute returns true/false and your current run method is returning a PDOStatement on success and false on failure. I suggest checking prepare and execute are not false and return the PDOStatement on success or false otherwise, as is the case with PDO::prepare and PDO::query.

Functional Example https://3v4l.org/OnDdn

/**
 * @return PDOStatement|false
 */
public function run($sql, $args = [])
{
    if (!$args) {
        return $this->pdo->query($sql);
    }
    if ($stmt = $this->pdo->prepare($sql)) {
        if ($stmt->execute($args)) {
            return $stmt;
        }
    }

    return false; //either prepare or execute failed
}

$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])); //false

An alternative approach would be to store the last execute value in a property, for later retrieval.

Example https://3v4l.org/UbM1N

class Database
{

    protected $lastExecute;

   //...

    /**
     * @return PDOStatement|false
     */
    public function run($sql, $args = [])
    {
        if (!$args) {
            return $this->pdo->query($sql);
        }
        if ($stmt = $this->pdo->prepare($sql)) {
            $this->lastExecute = $stmt->execute($args);
        }

        return $stmt;
    }

    /**
     * @return null|bool
     */
    public function getLastExecute()
    {
       return $this->lastExecute;
    }
}

$db = Database::instance();
$db->run('SELECT ?', ['foo', 'bar']);
var_dump($db->getLastExecute()); //false

To address the best-practices comments below in regard to the issue of determining when PDO::execute method specifically fails from within the Database::run method by using Exception handling.

Please keep in mind Best-Practices are not about right or wrong, "they are simply recommended methods of writing code." Referring to an approach of programming that is commonly preferred in professional application development. Always use what works best for you, the environment you are developing for and your application requirements.

Generally speaking StackOverlow is not an appropriate place to discuss or evaluate an author's application of
best-practices. Those types of discussions or critiques should be reserved for CodeReview. StackOverflow is
intended to answer the author's specific
question, or provide a viable alternative method to accomplish what the user is asking for. Not infer the user has asked the wrong question.

To use exceptions you need to enable PDO::ERRMODE_EXCEPTION (see below Database class).

The issue with using try/catch with a PDO wrapper method, is that PDO will only throw a single Exception object PDOException, which does not provide you with the ability to determine which PDO method call specifically failed. Leaving you to read the PDOException::getMessage() or PDOException::getTrace(), to determine the cause.

A simple approach would be to check the PDOException::trace for the function name that caused the exception.

Functional Example (PHP 5.6+): https://3v4l.org/fDnBI

try {
   $db = Database::instance();
   var_dump($db->run('SELECT ?', ['foo', 'bar'])->fetch());
} catch(\PDOException $e) {
   if ('execute' === $e->getTrace()[0]['function']) {
       echo 'PDO::execute() failed';
       //Handle the execute exception
   }
   throw $e;
}

Please see the answer on PDO mysql: How to know if insert was
successful by Your
Common Sense for a more generalized approach to PDOException
handling.

The above approach prevents you from handling only specific exception types within the Database::run method, requiring you to use throw $e; after your conditional, when the exception is unexpected.

To account for this issue, another approach would be to create custom Exception classes. You can do this by extending the base PDOException class to be compliant with other exception handling methods or to catch any of them.

In order to catch any of the run specific exceptions, an empty interface can be used that is then implemented on the extended PDOException classes.

interface DatabaseRunException{}

Then create a new exception class for each of the specific PDO methods you would like to handle, that implements the DatabaseRunException interface.

class PDOPrepareException extends PDOException implements DatabaseRunException{}

class PDOExecuteException extends PDOException implements DatabaseRunException{}

class PDOQueryException extends PDOException implements DatabaseRunException{}

To use the custom exceptions to determine which PDO method failed, you need to handle the PDOException(s) within the Database::run() method and throw one of the custom exceptions.

I have removed certain portions for brevity, commented out things that would alter your current configuration, made some best-practices and optimization changes for PHP 5.6+.

class Database
{

    private const OPTIONS = [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        // PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
        // PDO::ATTR_EMULATE_PREPARES => false
    ];

    //...

    protected function __construct()
    {
        $this->pdo = new PDO($dsn, self::user, self::password, self::OPTIONS);
    }

    public static function instance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    public function __call($method, $args)
    {
        //always ensure the desired method is callable!
        if (is_callable([$this->pdo, $method])) {
            //php 5.6+ variadic optimization (aka splat operator)
            return $this->pdo->$method(...$args);

            //php <= 5.5
            //return call_user_func_array(array($this->pdo, $method), $args);
        }
        throw new \BadMethodCallException(sprintf('Unknown method PDO::%s called!', $method));
    }

    public function run($sql, $args = [])
    {
        if (!$args) {
            try {
                return $this->query($sql);
            } catch(\PDOException $e) {
                 throw new \PDOQueryException($e->getMessage(), (int) $e->getCode(), $e);
            }
        }
        try {
            $stmt = $this->prepare($sql);
        } catch(\PDOException $e) {
            throw new \PDOPrepareException($e->getMessage(), (int) $e->getCode(), $e);
        }
        try {
            $stmt->execute($args);

            return $stmt;
        } catch(\PDOException $e) {
            throw new \PDOExecuteException($e->getMessage(), (int) $e->getCode(), $e);
        }

        throw new \LogicException('Unknown error occurred');
    }

}

Functional Example (PHP 5.6+): https://3v4l.org/8QoRF

You will now be able to handle each of the exceptions for any of the specific types.

try {
   $db = Database::instance();
   $db->run('SELECT ?', ['foo', 'bar']);
} catch(\PDOExecuteException $e) {
    echo 'PDO::execute() failed';
    //Handle the execute exception
    throw $e;
}

In PHP 7.1+ you can catch multiple exceptions.

try {
   $db = Database::instance();
   $db->run('SELECT ?', ['foo', 'bar']);
} catch(\PDOQueryException $e) {
    //Handle the query exception
    throw $e;
} catch(\PDOPrepareException $e) {
    //Handle the prepare exception
    throw $e;
} catch(\PDOExecuteException $e) {
    echo 'PDO::execute() failed';
    //Handle the execute exception
    throw $e;
}

In PHP <= 7.0 you can use the DatabaseRunException interface to catch and check the specific exceptions caused by Database::run() with instanceof to determine which exception was actually thrown.

try {
   $db = Database::instance();
   $db->run('SELECT ?', ['foo', 'bar']);
} catch(\DatabaseRunException $e) {
    if ($e instanceof \PDOQueryException) {
       //Handle the query exception
    } elseif ($e instanceof \PDOPrepareException) {
       //Handle the prepare exception
    } elseif ($e instanceof \PDOExecuteException) {
       echo 'PDO::execute() failed';
       //Handle the execute exception
    }
    throw $e;
}

As you can see, this increases the code complexity and will be up to you on determining what best suits your application needs.

It is important to note, that variables declared in the try section will not be declared if an exception occurs prior to the declaration.

try {
  throw new \Exception('FooBar');
  $foo = 'foo';
} catch(\Exception $e) {
   var_dump(isset($foo)); //false
}
var_dump(isset($foo)); //false


问:
How to get file content in java?
to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

```<code>Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();
}
</code>```

Does the java api provide a way to get the content with one line of code like:

```<code>String content = FileUtils.readFileToString(new File("file.txt"))
</code>```

答:
With Java 7 there is an API along those lines.

Files.readAllLines(Path path, Charset cs)

Title: How to get file content in java?

Body:
to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();
}

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))


问:
Neo4j/Py2Neo timeout issue when importing large CSV files
When importing data from large CSV files (>200MB) into Neo4j, the response ends up hanging. The query does complete, and all records are imported, however there seems to be some sort of response timeout which results in no indication that the import query has completed. This is an issue as we cannot automate importing multiple files into Neo4j, since the script continues waiting for the query to finish, even though it already has.

Importing 1 file takes around 10-15 minutes.

No errors are thrown anywhere in the pipeline, everything simply hangs. I can only tell when the process has completed as the VM CPU activity dies down.

This process does work on smaller files, and does send back an acknowledgement when the previous file has finished being imported, and moves onto the next.

I have tried running the scripts from both Jupyter notebook as well as a python script directly on the console. I have also even tried running the query directly on Neo4j through the browser console. Each way results in hanging queries, therefore I am not sure if the issue is coming from Neo4j or Py2Neo.

Example query:

```<code>USING PERIODIC COMMIT 1000
LOAD CSV FROM {csvfile}  AS line
MERGE (:Author { authorid: line[0], name: line[1] } )
</code>```

Modified python script using Py2Neo:

from azure.storage.blob import BlockBlobService
blob_service = BlockBlobService(account_name="<name>",account_key="<key>")
generator = blob_service.list_blobs("parsed-csv-files")

for blob in generator:
    print(blob.name)
    csv_file_base = "http://<base_uri>/parsed-csv-files/"
    csvfile = csv_file_base + blob.name
    params = { "csvfile":csvfile }
    mygraph.run(query, parameters=params )
```

<p>Neo4j debug.log does not seem to be recording any errors.</p>

<p>Sample debug.log:</p>

```2019-05-30 05:44:32.022+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job finished: descriptor=IndexRule[id=16, descriptor=Index( UNIQUE, :label[5](property[5]) ), provider={key=native-btree, version=1.0}, owner=42], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/16/index-16 Number of pages visited: 598507, Number of cleaned crashed pointers: 0, Time spent: 2m 25s 235ms
2019-05-30 05:44:32.071+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job closed: descriptor=IndexRule[id=16, descriptor=Index( UNIQUE, :label[5](property[5]) ), provider={key=native-btree, version=1.0}, owner=42], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/16/index-16
2019-05-30 05:44:32.071+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job started: descriptor=IndexRule[id=19, descriptor=Index( UNIQUE, :label[6](property[6]) ), provider={key=native-btree, version=1.0}, owner=46], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/19/index-19
2019-05-30 05:44:57.126+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job finished: descriptor=IndexRule[id=19, descriptor=Index( UNIQUE, :label[6](property[6]) ), provider={key=native-btree, version=1.0}, owner=46], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/19/index-19 Number of pages visited: 96042, Number of cleaned crashed pointers: 0, Time spent: 25s 55ms
2019-05-30 05:44:57.127+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job closed: descriptor=IndexRule[id=19, descriptor=Index( UNIQUE, :label[6](property[6]) ), provider={key=native-btree, version=1.0}, owner=46], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/19/index-19
```

EDIT: used simpler query which still gives same issue

答:
Since the query would take lot of time to complete on DB side, may be py2neo is having issues with waiting.

There should not be any issues with periodic commit.

Have you tried the Python neo4j driver and read csv from python and execute the query that way?

Here's sample code with neo4j driver.

```<code>import pandas as pd
from neo4j import GraphDatabase

driver = GraphDatabase.driver(serveruri, auth=(user,pwd))
with driver.session() as session:
    file = config['spins_file']
    row_chunks = pd.read_csv(file, sep=',', error_bad_lines=False,
                       index_col=False,
                       low_memory=False,
                       chunksize=config['chunk_size'])
    for i, rows in enumerate(row_chunks):
        print("Chunk {}".format(i))
        rows_dict = {'rows': rows.fillna(value="").to_dict('records')}
        session.run(statement="""
                    unwind data.rows as row
                    MERGE (:Author { authorid: line[0], name: line[1] } )
                    """,
                    dict=rows_dict)
</code>```

Body:
When importing data from large CSV files (>200MB) into Neo4j, the response ends up hanging. The query does complete, and all records are imported, however there seems to be some sort of response timeout which results in no indication that the import query has completed. This is an issue as we cannot automate importing multiple files into Neo4j, since the script continues waiting for the query to finish, even though it already has.

Importing 1 file takes around 10-15 minutes.

No errors are thrown anywhere in the pipeline, everything simply hangs. I can only tell when the process has completed as the VM CPU activity dies down.

This process does work on smaller files, and does send back an acknowledgement when the previous file has finished being imported, and moves onto the next.

I have tried running the scripts from both Jupyter notebook as well as a python script directly on the console. I have also even tried running the query directly on Neo4j through the browser console. Each way results in hanging queries, therefore I am not sure if the issue is coming from Neo4j or Py2Neo.

Example query:

USING PERIODIC COMMIT 1000
LOAD CSV FROM {csvfile}  AS line
MERGE (:Author { authorid: line[0], name: line[1] } )

Modified python script using Py2Neo:

from azure.storage.blob import BlockBlobService
blob_service = BlockBlobService(account_name="<name>",account_key="<key>")
generator = blob_service.list_blobs("parsed-csv-files")

for blob in generator:
    print(blob.name)
    csv_file_base = "http://<base_uri>/parsed-csv-files/"
    csvfile = csv_file_base + blob.name
    params = { "csvfile":csvfile }
    mygraph.run(query, parameters=params )

Neo4j debug.log does not seem to be recording any errors.

Sample debug.log:

2019-05-30 05:44:32.022+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job finished: descriptor=IndexRule[id=16, descriptor=Index( UNIQUE, :label[5](property[5]) ), provider={key=native-btree, version=1.0}, owner=42], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/16/index-16 Number of pages visited: 598507, Number of cleaned crashed pointers: 0, Time spent: 2m 25s 235ms
2019-05-30 05:44:32.071+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job closed: descriptor=IndexRule[id=16, descriptor=Index( UNIQUE, :label[5](property[5]) ), provider={key=native-btree, version=1.0}, owner=42], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/16/index-16
2019-05-30 05:44:32.071+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job started: descriptor=IndexRule[id=19, descriptor=Index( UNIQUE, :label[6](property[6]) ), provider={key=native-btree, version=1.0}, owner=46], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/19/index-19
2019-05-30 05:44:57.126+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job finished: descriptor=IndexRule[id=19, descriptor=Index( UNIQUE, :label[6](property[6]) ), provider={key=native-btree, version=1.0}, owner=46], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/19/index-19 Number of pages visited: 96042, Number of cleaned crashed pointers: 0, Time spent: 25s 55ms
2019-05-30 05:44:57.127+0000 INFO [o.n.k.i.i.s.GenericNativeIndexProvider] Schema index cleanup job closed: descriptor=IndexRule[id=19, descriptor=Index( UNIQUE, :label[6](property[6]) ), provider={key=native-btree, version=1.0}, owner=46], indexFile=/data/databases/graph.db/schema/index/native-btree-1.0/19/index-19

EDIT: used simpler query which still gives same issue

Body:
Since the query would take lot of time to complete on DB side, may be py2neo is having issues with waiting.

There should not be any issues with periodic commit.

Have you tried the Python neo4j driver and read csv from python and execute the query that way?

Here's sample code with neo4j driver.

import pandas as pd
from neo4j import GraphDatabase

driver = GraphDatabase.driver(serveruri, auth=(user,pwd))
with driver.session() as session:
    file = config['spins_file']
    row_chunks = pd.read_csv(file, sep=',', error_bad_lines=False,
                       index_col=False,
                       low_memory=False,
                       chunksize=config['chunk_size'])
    for i, rows in enumerate(row_chunks):
        print("Chunk {}".format(i))
        rows_dict = {'rows': rows.fillna(value="").to_dict('records')}
        session.run(statement="""
                    unwind data.rows as row
                    MERGE (:Author { authorid: line[0], name: line[1] } )
                    """,
                    dict=rows_dict)


问:
Can I connect a wifi only one time?
I connect wifi programmatically in my app like that

```<code>private void WPA(String networkSSID, String networkPass, WifiManager wifiManager, String command) {
    WifiConfiguration wc = new WifiConfiguration();
    wc.SSID = "\"" + networkSSID + "\"";
    wc.preSharedKey = "\"" + networkPass + "\"";
    wc.status = WifiConfiguration.Status.ENABLED;
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    if (command.equals(ADD)) {
        addNetwork(wifiManager, wc);
    } else if (command.equals(REMOVE)) {
        removeNetwork(wifiManager, wc);
    }

}

private void addNetwork(WifiManager wifiManager, WifiConfiguration wc) {
    if (!wifiManager.isWifiEnabled()) enableWifi();
    int id = wifiManager.addNetwork(wc);
    if (id > -1) {
        wifiManager.disconnect();
        wifiManager.enableNetwork(id, true);
        wifiManager.reconnect();
        wifiManager.saveConfiguration();
    }
}
</code>```

I want to know if it's possible in Android to connect a wifi without saving password that when wifi is disconnected, user can not connect again without entering password? If it is possible, how can I do that programmatically?

答:
Have a look at this post how to extract wifi pass

and then modify it in your program to remove the desired config and save it back.

Title: Can I connect a wifi only one time?

Body:
I connect wifi programmatically in my app like that

private void WPA(String networkSSID, String networkPass, WifiManager wifiManager, String command) {
    WifiConfiguration wc = new WifiConfiguration();
    wc.SSID = "\"" + networkSSID + "\"";
    wc.preSharedKey = "\"" + networkPass + "\"";
    wc.status = WifiConfiguration.Status.ENABLED;
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    if (command.equals(ADD)) {
        addNetwork(wifiManager, wc);
    } else if (command.equals(REMOVE)) {
        removeNetwork(wifiManager, wc);
    }

}

private void addNetwork(WifiManager wifiManager, WifiConfiguration wc) {
    if (!wifiManager.isWifiEnabled()) enableWifi();
    int id = wifiManager.addNetwork(wc);
    if (id > -1) {
        wifiManager.disconnect();
        wifiManager.enableNetwork(id, true);
        wifiManager.reconnect();
        wifiManager.saveConfiguration();
    }
}

I want to know if it's possible in Android to connect a wifi without saving password that when wifi is disconnected, user can not connect again without entering password? If it is possible, how can I do that programmatically?


问:
How do I use setTimeout or setInterval while iterating over an array?
I need to continuously iterate over an array (which actually contains ids used to generate canvax images).

So I need to iterate over the array of keys over and over again, with ids being set with a delay.

```<code>function animateCanvas() {
    keys = getKeys();
    let offset = 0;
    keys.forEach(function(key){
        setTimeout(function(){
            animateFrame(key);
        }, 2000 + offset);
        offset += 2000;
        keys = [];
    });
}

function animateFrame(id) {
    const animationCanvas = document.querySelector(`.canvas-animation`);
    const animationContext = animationCanvas.getContext('2d');
    const canvas1 = document.getElementById(id);
    animationContext.clearRect(0, 0, animationCanvas.width, animationCanvas.height);
    animationContext.drawImage(canvas1, 0,0, 170, 170, 0, 0 , 150, 150);
}
</code>```

Expected result would be endless setting another image to canvas via animateFrame(key) with a delay of 2 seconds

答:
Have you considered using .requestAnimationFrame() rather than a loop? It is actually quite ideal for your use case.

This is what it would look like. Note the comment about where to add the image to the canvas.

const data = ["

", "

", "

"];
// Set delay to 5000 for 5 seconds
const delay = 2000;
// set previousCall to 1 to wait for first or -(delay) to start immediately
let previousCall = -(delay);

function animateCanvas(now) {
  if (now - previousCall >= delay) {
    // grab data from array in some fashion
    let id = parseInt(now/3 % 3);
    animateFrame(id);
    previousCall = now;
  }
  requestAnimationFrame(animateCanvas);
}
requestAnimationFrame(animateCanvas);

function animateFrame(id) {
    document.body.innerHTML += data[id];
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div, section, article {
  width: 50px;
  height: 50px;
  background-color: blue;
  margin: 3px;
}
div {
  background-color: blue;

}
section {
  background-color: yellow;

}
article {
  background-color: orange;

}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

```

Body:
I need to continuously iterate over an array (which actually contains ids used to generate canvax images).

So I need to iterate over the array of keys over and over again, with ids being set with a delay.

function animateCanvas() {
    keys = getKeys();
    let offset = 0;
    keys.forEach(function(key){
        setTimeout(function(){
            animateFrame(key);
        }, 2000 + offset);
        offset += 2000;
        keys = [];
    });
}

function animateFrame(id) {
    const animationCanvas = document.querySelector(`.canvas-animation`);
    const animationContext = animationCanvas.getContext('2d');
    const canvas1 = document.getElementById(id);
    animationContext.clearRect(0, 0, animationCanvas.width, animationCanvas.height);
    animationContext.drawImage(canvas1, 0,0, 170, 170, 0, 0 , 150, 150);
}

Expected result would be endless setting another image to canvas via animateFrame(key) with a delay of 2 seconds

Body:
Have you considered using .requestAnimationFrame() rather than a loop? It is actually quite ideal for your use case.

This is what it would look like. Note the comment about where to add the image to the canvas.

const data = ["<div></div>", "<section></section>", "<article></article>"];
// Set delay to 5000 for 5 seconds
const delay = 2000;
// set previousCall to 1 to wait for first or -(delay) to start immediately
let previousCall = -(delay);

function animateCanvas(now) {
  if (now - previousCall >= delay) {
    // grab data from array in some fashion
    let id = parseInt(now/3 % 3);
    animateFrame(id);
    previousCall = now;
  }
  requestAnimationFrame(animateCanvas);
}
requestAnimationFrame(animateCanvas);

function animateFrame(id) {
    document.body.innerHTML += data[id];
}

div, section, article {
  width: 50px;
  height: 50px;
  background-color: blue;
  margin: 3px;
}
div {
  background-color: blue;

}
section {
  background-color: yellow;

}
article {
  background-color: orange;

}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
</body>

</html>


问:
Select a duplicate row with one unique_id and second unique_id diferent ORACLE
Suppose that you have this table:

```<code>ID  |   DOC |   DOC_ID  |   TYPE
1   |   A   |   B       |   A
2   |   A   |   B       |   B
3   |   BB  |   CC      |   A
4   |   BB  |   DD      |   A
5   |   E   |   F       |   A
6   |   E   |   F       |   B
7   |   E   |   F       |   B
8   |   G   |   H       |   A
9   |   G   |   I       |   A
10  |   G   |   I       |   B
11  |   G   |   H       |   B
</code>```

I need to identify the information in this table with all of this cincuntanses:

DOC field has to be the same

DOC_ID field has to be different

Have more than 2 rows per DOC register

How to get the information like the next table?

```<code>ID  |   DOC |   DOC_ID  |   TYPE
3   |   BB  |   CC      |   A
4   |   BB  |   DD      |   A
10  |   G   |   I       |   B
11  |   G   |   H       |   B
</code>```

Ive tried to do with Group by, count(doc_id), and couldnt get the result

答:
I'm thinking window functions.  These are the rules you describe:

```<code>select t.*
from (select t.*,
             row_number() over (partition by doc, doc_id order by doc_id) as seqnum,
             count(*) over (partition by doc) as cnt
      from t
     ) t
where seqnum = 1 and cnt >= 2;
</code>```

I think these are the rules you want:

```<code>select t.*
from (select t.*,
             row_number() over (partition by doc, doc_id order by doc_id) as seqnum,
             count(distinct doc_id) over (partition by doc) as cnt
      from t
     ) t
where seqnum = 1 and cnt >= 2;
</code>```

Body:
Suppose that you have this table:

ID  |   DOC |   DOC_ID  |   TYPE
1   |   A   |   B       |   A
2   |   A   |   B       |   B
3   |   BB  |   CC      |   A
4   |   BB  |   DD      |   A
5   |   E   |   F       |   A
6   |   E   |   F       |   B
7   |   E   |   F       |   B
8   |   G   |   H       |   A
9   |   G   |   I       |   A
10  |   G   |   I       |   B
11  |   G   |   H       |   B

I need to identify the information in this table with all of this cincuntanses:

DOC field has to be the same

DOC_ID field has to be different

Have more than 2 rows per DOC register

How to get the information like the next table?

ID  |   DOC |   DOC_ID  |   TYPE
3   |   BB  |   CC      |   A
4   |   BB  |   DD      |   A
10  |   G   |   I       |   B
11  |   G   |   H       |   B

Ive tried to do with Group by, count(doc_id), and couldnt get the result

Body:
I'm thinking window functions.  These are the rules you describe:

select t.*
from (select t.*,
             row_number() over (partition by doc, doc_id order by doc_id) as seqnum,
             count(*) over (partition by doc) as cnt
      from t
     ) t
where seqnum = 1 and cnt >= 2;

I think these are the rules you want:

select t.*
from (select t.*,
             row_number() over (partition by doc, doc_id order by doc_id) as seqnum,
             count(distinct doc_id) over (partition by doc) as cnt
      from t
     ) t
where seqnum = 1 and cnt >= 2;


问:
Pseudo random number generator using the Blum Blum Shub algorithm
We're required to implement Blum Blum Shub Algorithm in a pseudo random number generator. I tried searching for implementations in c# to get an idea but was unsuccessful. Some methods we're required to implement are not clear enough (or maybe I'm not getting exactly what they're asking).

Anyone could provide some help with either the code or maybe an example in a similar fashion? I have a harder time grasping concepts from text.Any help would be greatly accepted!

First, I tried following the logic of the question. With little progress, I began searching on-line for better explanations and possibly finding implementations to better understanding. Finally, I attempted to fill in some of the requested methods with what I thought made sense.

```<code>static long seed = 6367859;
static long p = 3263849;
static long q = 1302498943;
static long m = p*q;

// Generates a random bit i.e. 0 or 1 using the Blum Blum Shub Algorithm and the Least Significant Bit
private byte generateRandomBit(){ }

// Method to generate a single positive 32 bit random number using the Blum Blum Shub Algorithm.
// The generateRandomBit() method is used to generate the random bits that make up the random number
// Not complete!!
public int GenerateNextRandomNumber()
{
    int nextRandomNumber = (int)((p * seed + q) % m);

    seed = nextRandomNumber;

    return nextRandomNumber;
}

// Generates a random number between min and max.
// The GenerateNextRandomNumber() method must be used to generate the initial random number which must then be manipulated (if necessary) to be between min and max
public int GenerateNextRandomNumber(int min, int max){ }

// Uses the GenerateNextRandomNumber Method to generate a sequence of Random Numbers between the minimum and the maximum value using the Blum Blum Shub Algorithm
public int[] GenerateRadmonSequence(int n, int min, int max)
{
    int[] sequence = new int[n];

    for (int i = 0; i < n; i++)
    {
        int randNum = Math.Abs(GenerateNextRandomNumber());

        randNum = min + randNum % (max + 1 +- min);
        sequence[i] = randNum;
    }

    return sequence;
}
</code>```

The result should be to generate a sequence of numbers from min to max.

答:
What about this implementation:

```<code>public class BlumBlumShub
{
    private readonly ulong m;
    private ulong x;

    public BlumBlumShub(int m, int seed)
    {
        this.m = (ulong) m;
        x = (ulong)seed;
    }

    public int Next()
    {
        x = (x * x) % m;
        return (int)x;
    }
}
</code>```

reference

Edit: If you really need very large number you can adapt it easily:

```<code>public class BlumBlumShub
{
    private readonly BigInteger m;
    private BigInteger x;

    public BlumBlumShub(BigInteger m, BigInteger seed)
    {
        this.m = m;
        x = seed;
    }

    public BigInteger Next()
    {
        x = (x * x) % m;
        return x;
    }
}
</code>```

Body:
We're required to implement Blum Blum Shub Algorithm in a pseudo random number generator. I tried searching for implementations in c# to get an idea but was unsuccessful. Some methods we're required to implement are not clear enough (or maybe I'm not getting exactly what they're asking).

Anyone could provide some help with either the code or maybe an example in a similar fashion? I have a harder time grasping concepts from text.Any help would be greatly accepted!

First, I tried following the logic of the question. With little progress, I began searching on-line for better explanations and possibly finding implementations to better understanding. Finally, I attempted to fill in some of the requested methods with what I thought made sense.

static long seed = 6367859;
static long p = 3263849;
static long q = 1302498943;
static long m = p*q;

// Generates a random bit i.e. 0 or 1 using the Blum Blum Shub Algorithm and the Least Significant Bit
private byte generateRandomBit(){ }

// Method to generate a single positive 32 bit random number using the Blum Blum Shub Algorithm.
// The generateRandomBit() method is used to generate the random bits that make up the random number
// Not complete!!
public int GenerateNextRandomNumber()
{
    int nextRandomNumber = (int)((p * seed + q) % m);

    seed = nextRandomNumber;

    return nextRandomNumber;
}

// Generates a random number between min and max.
// The GenerateNextRandomNumber() method must be used to generate the initial random number which must then be manipulated (if necessary) to be between min and max
public int GenerateNextRandomNumber(int min, int max){ }

// Uses the GenerateNextRandomNumber Method to generate a sequence of Random Numbers between the minimum and the maximum value using the Blum Blum Shub Algorithm
public int[] GenerateRadmonSequence(int n, int min, int max)
{
    int[] sequence = new int[n];

    for (int i = 0; i < n; i++)
    {
        int randNum = Math.Abs(GenerateNextRandomNumber());

        randNum = min + randNum % (max + 1 +- min);
        sequence[i] = randNum;
    }

    return sequence;
}

The result should be to generate a sequence of numbers from min to max.

Body:
What about this implementation:

public class BlumBlumShub
{
    private readonly ulong m;
    private ulong x;

    public BlumBlumShub(int m, int seed)
    {
        this.m = (ulong) m;
        x = (ulong)seed;
    }

    public int Next()
    {
        x = (x * x) % m;
        return (int)x;
    }
}

reference

Edit: If you really need very large number you can adapt it easily:

public class BlumBlumShub
{
    private readonly BigInteger m;
    private BigInteger x;

    public BlumBlumShub(BigInteger m, BigInteger seed)
    {
        this.m = m;
        x = seed;
    }

    public BigInteger Next()
    {
        x = (x * x) % m;
        return x;
    }
}


Title: Need to add multiple elements to search for a particular class with jQuery

Body:
I am using jQuery and am currently looking in one type of element for a particular class. I need to update it to look in three different elements, but am not sure how to do this since I assume I will need to use an array?

Here's my current code:

$findRed = $("p.red", "#main");

if ( $findRed.length >= 1 ) {
    greater or equal to one
}

I need to change it so it will look for .red in either a p, div, or span tag.

Any help would be appreciate.

Body: var $findRd = $(":has(.red)", $("p, div, span", $("#main")));


问:
Swap out old project with new one
I have an existing project, quite old, with its own support system: in-app purchases, links on web pages, etc.

I would like to overhaul the app significantly front and back end, so much so that basically none of the original code will remain. Maybe even write it in Swift instead of Objective-C, mostly because it's getting harder and harder to find Objective-C documentation.

Is it possible to set up the new app in Xcode so that for all intents and purposes, the app store just considers it to be a new version of the existing app? The in-app purchases work with it, the links to the app store still work, etc.

答: Yes, no problem. As long as the new app has the same bundle ID as the old app (CFBundleIdentifier in the Info.plist), it is the same app in the eyes of the App Store and Apple. You can change everything else about it and they won't care: icons, user-facing name (CFBundleDisplayName), underlying language, interface, major functionality even. The in-app purchases are attached to that bundle ID so they just keep on working; the links to the app store won't change. You can start a completely new project, from scratch, and as long as the bundle ID is the old bundle ID, it's the same app.

Title: Swap out old project with new one


问:
Rexx, Parse a file for a single line
I'm trying to find a way to parse a file in Rexx. Each line has two words and an IP address.

Example

Location Name 10.0.0.1

I have looked over a lot of documentation and i can get it to print all the lines in the file but i cannot figure out how to search an entire file and print a specific line by using a match operator.

答:
```<code>filename = 'MY.DATA.SET'
if sysdsn(''''filename'''') <> 'OK' then exit

address 'TSO'
"ALLOCATE FILE(INDD) DATASET('"filename"') SHR REUSE"
"EXECIO DISKR * INDD(STEM file. FINIS)"
"CLOSE FILE(INDD)"

target = 'My Location'
found = 1==0 /* false */
do i = 1 to file.0
  card = file.i
  parse var card loc1 loc2 ip_address .
  found = loc1' 'loc2 == target
  if found then leave
  end i
if found then
  say 'IP address of 'target' is 'ip_address
else
  say 'No IP address found for 'target

exit
</code>```

Title: Rexx, Parse a file for a single line


问:
download pdf file of blade instead of view in browser
I would like the browser to download file on button click of blade page. The following is used in controller and and added in provider file, but its showing in browser console but not downloading file.    </p>

```<code>use PDF;

// this controller
function sensorChartPDF(){

     $pdf = PDF::loadView('sensorchartpdf');

    return $pdf->download('invoice.pdf')->header('Content-Type','application/pdf');;

    }
</code>```

<p>///// sensorchartpdf.blade.php  this is view ///
https://canvasjs.com/javascript-charts/multi-series-spline-chart/ </p>

<p>chart static code appened in this file </p>

答:
To signify to the web browser that the file should be downloaded and not displayed in line you have to specify the content-disposition header with a value of attachment.

Your question, however, does not appear to be purely a question regarding Dompdf. With Dompdf you would merely use the following:

```<code>$dompdf->stream("output.pdf", array('Attachment' => 1));
</code>```

I'm providing this for anyone looking for similar issue when working with the library directly.

Since you're not using Dompdf directly but via another library so you'll need to specify exactly which library or framework you're using before somebody can provide an accurate answer.

Body:
I would like the browser to download file on button click of blade page. The following is used in controller and and added in provider file, but its showing in browser console but not downloading file.

use PDF;

// this controller
function sensorChartPDF(){

     $pdf = PDF::loadView('sensorchartpdf');

    return $pdf->download('invoice.pdf')->header('Content-Type','application/pdf');;

    }

///// sensorchartpdf.blade.php  this is view ///
https://canvasjs.com/javascript-charts/multi-series-spline-chart/

chart static code appened in this file

Body:
To signify to the web browser that the file should be downloaded and not displayed in line you have to specify the content-disposition header with a value of attachment.

Your question, however, does not appear to be purely a question regarding Dompdf. With Dompdf you would merely use the following:

$dompdf->stream("output.pdf", array('Attachment' => 1));

I'm providing this for anyone looking for similar issue when working with the library directly.

Since you're not using Dompdf directly but via another library so you'll need to specify exactly which library or framework you're using before somebody can provide an accurate answer.


问:
Xamarin.iOS Object Losing Property Members
I have a Xamarin Forms project with UWP, Android and iOS. I use a SQL Database hosted in Azure on the back end and a user can search for foods and get the different measures and nutrient values that go with the food. The issue is that I use a foreach loop to loop through a list of the queried foods and create and object to hold the higher level food properties (like name and measure) and combine a second list that contains all the nutrients and nutrient values for that food. In the process of creating the object, only on iOS, the Measure property is not getting set when there is data in the looping object and in debugging mode I see the value for Measure as {...} and the property Measure acutally disappears from the instantiated object. This only happens on iOS, not UWP or Android. Here is a picture of it in debugging:
Food item with data
Here is the new object instantiated missing properties:
NewFood without some properties
Here is the Measure property with something I have never seen:
Measure Property

Here is the food object class

public class FoodNutrients : BindableObject
    {
        public string NDB { get; set; }
        public string Food { get; set; }
        public string Measure { get; set; }
        public string MeasureType { get; set; }
        public string MeasureAmount { get; set; }
        public double Protein { get; set; }
        public double Sodium { get; set; }
        public double Potassium { get; set; }
        public double Phosphorus { get; set; }
        public double Carbs { get; set; }
        public double Fat { get; set; }
        public double SaturatedFat { get; set; }
        public double Calories { get; set; }
        public string SodiumRec { get; set; }
        public string ProteinRec { get; set; }
        public string PotassiumRec { get; set; }
        public string PhosphorusRec { get; set; }
        public string CarbsRec { get; set; }
        public string FatRec { get; set; }
        public string SatFatRec { get; set; }
        public string CaloriesRec { get; set; }
        public string Recommendation { get; set; }
        public string RecColor { get; set; }
}
```

<p>Here is the foreach loop</p>

<pre class="lang-cs prettyprint-override"><code>foreach (var food in foodList1)
                {
                    FoodNutrients newFood = new FoodNutrients();
                    string measureString = "- " + food.MeasureAmount + " " + food.Measure;
                    newFood.NDB = food.NDB;
                    newFood.Food = food.Food;
                    newFood.MeasureType = food.Measure;
                    newFood.MeasureAmount = food.MeasureAmount;
                    newFood.Measure = measureString;
                    newFood.Protein = FoodNutrients.GetProteinValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Sodium = FoodNutrients.GetSodiumValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Potassium = FoodNutrients.GetPotassiumValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Phosphorus = FoodNutrients.GetPhosphorusValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Carbs = FoodNutrients.GetCarbValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Fat = FoodNutrients.GetFatValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.SaturatedFat = FoodNutrients.GetSatFatValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Calories = FoodNutrients.GetCalorieValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood = DailyAllowanceController.GetRecommendation(newFood, user);
                    foodList.Add(newFood);
                }
</code>```

Again, there are no syntax errors and this code words perfectly in Android and UWP. Please look at the images in the above description as they provide some real details.

答: I found out that you need to set the Linker in the iOS Build settings Link SDK assemblies only. Then save and rebuild and redeploy and that fixed my issue. Very confusing.</p>

Body:
I have a Xamarin Forms project with UWP, Android and iOS. I use a SQL Database hosted in Azure on the back end and a user can search for foods and get the different measures and nutrient values that go with the food. The issue is that I use a foreach loop to loop through a list of the queried foods and create and object to hold the higher level food properties (like name and measure) and combine a second list that contains all the nutrients and nutrient values for that food. In the process of creating the object, only on iOS, the Measure property is not getting set when there is data in the looping object and in debugging mode I see the value for Measure as {...} and the property Measure acutally disappears from the instantiated object. This only happens on iOS, not UWP or Android. Here is a picture of it in debugging:
Food item with data
Here is the new object instantiated missing properties:
NewFood without some properties
Here is the Measure property with something I have never seen:
Measure Property

Here is the food object class

public class FoodNutrients : BindableObject
    {
        public string NDB { get; set; }
        public string Food { get; set; }
        public string Measure { get; set; }
        public string MeasureType { get; set; }
        public string MeasureAmount { get; set; }
        public double Protein { get; set; }
        public double Sodium { get; set; }
        public double Potassium { get; set; }
        public double Phosphorus { get; set; }
        public double Carbs { get; set; }
        public double Fat { get; set; }
        public double SaturatedFat { get; set; }
        public double Calories { get; set; }
        public string SodiumRec { get; set; }
        public string ProteinRec { get; set; }
        public string PotassiumRec { get; set; }
        public string PhosphorusRec { get; set; }
        public string CarbsRec { get; set; }
        public string FatRec { get; set; }
        public string SatFatRec { get; set; }
        public string CaloriesRec { get; set; }
        public string Recommendation { get; set; }
        public string RecColor { get; set; }
}

Here is the foreach loop

foreach (var food in foodList1)
                {
                    FoodNutrients newFood = new FoodNutrients();
                    string measureString = "- " + food.MeasureAmount + " " + food.Measure;
                    newFood.NDB = food.NDB;
                    newFood.Food = food.Food;
                    newFood.MeasureType = food.Measure;
                    newFood.MeasureAmount = food.MeasureAmount;
                    newFood.Measure = measureString;
                    newFood.Protein = FoodNutrients.GetProteinValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Sodium = FoodNutrients.GetSodiumValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Potassium = FoodNutrients.GetPotassiumValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Phosphorus = FoodNutrients.GetPhosphorusValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Carbs = FoodNutrients.GetCarbValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Fat = FoodNutrients.GetFatValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.SaturatedFat = FoodNutrients.GetSatFatValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood.Calories = FoodNutrients.GetCalorieValue(foodList2, food.NDB, (double)food.MeasureWeightGrams);
                    newFood = DailyAllowanceController.GetRecommendation(newFood, user);
                    foodList.Add(newFood);
                }

Again, there are no syntax errors and this code words perfectly in Android and UWP. Please look at the images in the above description as they provide some real details.


问:
How to show the same DIV container and different content based on the link click
I am attempting to have a hidden DIV that is displayed based on a link clicked in the table and it shows the associated information about that specific link click. A different link click should show that same table, however different information that is associated only with that link click.

I have tried utilizing some jquery. And everything works, as in showing the div and hiding content behind it. But it only shows the first content, not the second if I click the second link.

  <div id="link"
Link Table and DIV

          Link 1
       Link 1 Description

       href="#" value="link_2">Link 2
       Link 2 Description

href="">

 blah blah blah

 blah blah blah blah

```

答:
you can create a global object to put value:description.
Eg.

```<code>const data = [{link_1:'LINK 1 Description'},{link_2: 'LINK 2 Description'}];
</code>```

When you click in row, with JS you get current link and other variable.

In your view, create a generic structure to show a Description and with JS, appendToHtml value

```<code>document.getElementById('#whatever').innetHTML = data.currentValue
</code>```

Body:
I am attempting to have a hidden DIV that is displayed based on a link clicked in the table and it shows the associated information about that specific link click. A different link click should show that same table, however different information that is associated only with that link click.

I have tried utilizing some jquery. And everything works, as in showing the div and hiding content behind it. But it only shows the first content, not the second if I click the second link.

  <div id="link"
Link Table and DIV

          Link 1
       Link 1 Description

       Link 2
       Link 2 Description

 blah blah blah

 blah blah blah blah

Body:
you can create a global object to put value:description.
Eg.

const data = [{link_1:'LINK 1 Description'},{link_2: 'LINK 2 Description'}];

When you click in row, with JS you get current link and other variable.

In your view, create a generic structure to show a Description and with JS, appendToHtml value

document.getElementById('#whatever').innetHTML = data.currentValue


问:
Is there a way to use postfix notation to call a function in Rust without defining a new trait?
Perhaps my terminology is wrong, but is there a way to use postfix notation to call a function in Rust without defining a new trait?  Basically, I have a vector of &str and I'd like to convert them into a string with the notation myvec.as_string().  Currently, I can do this with the code

```<code>trait Foo {
    fn as_string(&self) -> String;
}

impl Foo for Vec<&str> {
    fn as_string(&self) -> String {
        let mut mystr = self
            .iter()
            .fold(String::new(),|sum,s| format!("{}{}:", sum, s));
        mystr.pop();
        mystr
    }
}

fn main() {
    let my_vec = vec!["bar", "buz", "baz"];
    use crate::Foo;
    println!("{}", my_vec.as_string());
}
</code>```

That said, in order to make this work, I needed to define a trait called Foo that I don't really care about and the trait needed to be opened with use crate::Foo prior to the call to as_string.  Is there a better way to accomplish this?  And, to be clear, I'd like to avoid the notation as_string(myvec) if possible because the postfix notation has been nice for chaining together commands.

答:
This is a common pattern!

If you want to add methods to a type that is defined in another crate, the official way to do so is it define a trait and implement it for that type. If the type is from another crate then this is the only way to do it.

A ubiquitous example of this is the crate itertools which uses a trait to add useful methods to every existing implementation of std::iter::Iterator.

Itertools works just as you describe. There is a trait which declares a number of methods:

```<code>pub trait Itertools : Iterator {
    fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter>
        where J: IntoIterator<Item = Self::Item>,
              Self: Sized
    {
        interleave(self, other)
    }

    // etc...
}
</code>```

It is defined for all Iterators:

```<code>impl<T: ?Sized> Itertools for T where T: Iterator { }
</code>```

And, whenever you want to use these extra methods, you import it:

```<code>use itertools::Itertools;

let it = (1..7).interleave(vec![-1, -2]);
itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);
</code>```

Body:
Perhaps my terminology is wrong, but is there a way to use postfix notation to call a function in Rust without defining a new trait?  Basically, I have a vector of &str and I'd like to convert them into a string with the notation myvec.as_string().  Currently, I can do this with the code

trait Foo {
    fn as_string(&self) -> String;
}

impl Foo for Vec<&str> {
    fn as_string(&self) -> String {
        let mut mystr = self
            .iter()
            .fold(String::new(),|sum,s| format!("{}{}:", sum, s));
        mystr.pop();
        mystr
    }
}

fn main() {
    let my_vec = vec!["bar", "buz", "baz"];
    use crate::Foo;
    println!("{}", my_vec.as_string());
}

That said, in order to make this work, I needed to define a trait called Foo that I don't really care about and the trait needed to be opened with use crate::Foo prior to the call to as_string.  Is there a better way to accomplish this?  And, to be clear, I'd like to avoid the notation as_string(myvec) if possible because the postfix notation has been nice for chaining together commands.

Body:
This is a common pattern!

If you want to add methods to a type that is defined in another crate, the official way to do so is it define a trait and implement it for that type. If the type is from another crate then this is the only way to do it.

A ubiquitous example of this is the crate itertools which uses a trait to add useful methods to every existing implementation of std::iter::Iterator.

Itertools works just as you describe. There is a trait which declares a number of methods:

pub trait Itertools : Iterator {
    fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter>
        where J: IntoIterator<Item = Self::Item>,
              Self: Sized
    {
        interleave(self, other)
    }

    // etc...
}

It is defined for all Iterators:

impl<T: ?Sized> Itertools for T where T: Iterator { }

And, whenever you want to use these extra methods, you import it:

use itertools::Itertools;

let it = (1..7).interleave(vec![-1, -2]);
itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);