问:
How do I find the number of cores available to MPI(4PY)?
How do I find the number of cores available to MPI(4PY)?

Motivation

My Python program spawns MPI instances hierarchically.

The first spawn always happens and creates 4 instances. It doesn't make sense to increase this number due to the structure of my computations, so I hardcoded it.

Depending on the command line options to the main program, each of the 4 instances then call external Python software that scales almost linearly.

I call this external software using

```<code>N=3
child=MPI.COMM_SELF.Spawn(sys.executable,args=[`external.py`],maxprocs=N)
</code>```

At the moment, I use N=3 so that the 4 instances of the first spawn each spawn 3 instances of the external program, which yields  a total of 12 instances, matching the number of cores on my workstation.

However, for portability, I would like to do

```<code>N_avail = <MPI.N_CORES> #on my workstation: N_avail=12
N = N_avail/MPI.COMM_WORLD.Get_size() #on my workstation: N=12/4=3
</code>```

so that the number of available cores needn't be hardcoded.

Is this possible, and does it make sense?

Notes

I had hoped that not specifying maxprocs would do the job, just as mpirun with out -np spawns as many instances as available cores. However, Spawn then defaults to maxprocs=1.

The call of the external library is blocking, which is why I don't (wouldn't) subtract the 4 instances from the first spawn from N_avail.

I can't just use multiprocessing.cpu_count(), since this would only give me the cores on the current node (in a cluster setting). I am planning to run my code on a cluster using a SLURM scheduler.

答:
There is an attribute of the world communicator that might provide the total number of process expected: MPI_UNIVERSE_SIZE. See the MPI standards, http://mpi-forum.org/docs/mpi-3.1/mpi31-report/node253.htm#Node253

MPI provides an attribute on MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, that allows the application to obtain this information in a portable manner. This attribute indicates the total number of processes that are expected. ... An application typically subtracts the size of MPI_COMM_WORLD from MPI_UNIVERSE_SIZE to find out how many processes it should spawn. ...

In mpi4py, it can be printed as:

```<code>from mpi4py import MPI

version= MPI.Get_version()
print "mpi version is ",version

comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
print "size is ",size

universe_size=comm.Get_attr(MPI.UNIVERSE_SIZE)
print "universe size is ",universe_size
</code>```

Following OpenMPI mpirun universe size , this feature can be tested by trying:

```<code>mpirun -np 1 -H localhost,localhost,localhost python main.py
</code>```

If your MPI version is higher or equal to 3, the MPI_Info MPI_INFO_ENV could help you. It features two keys which might provide some pieces of information:

maxprocs   Maximum number of MPI processes to start.

soft       Allowed values for number of processors.

To use it in mpi4py, you could try:

```<code>soft=MPI.INFO_ENV.get("soft")
print soft
maxprocs=MPI.INFO_ENV.get("maxprocs")
print maxprocs
</code>```

Body:
How do I find the number of cores available to MPI(4PY)?

Motivation

My Python program spawns MPI instances hierarchically.

The first spawn always happens and creates 4 instances. It doesn't make sense to increase this number due to the structure of my computations, so I hardcoded it.

Depending on the command line options to the main program, each of the 4 instances then call external Python software that scales almost linearly.

I call this external software using

N=3
child=MPI.COMM_SELF.Spawn(sys.executable,args=[`external.py`],maxprocs=N)

At the moment, I use N=3 so that the 4 instances of the first spawn each spawn 3 instances of the external program, which yields  a total of 12 instances, matching the number of cores on my workstation.

However, for portability, I would like to do

N_avail = <MPI.N_CORES> #on my workstation: N_avail=12
N = N_avail/MPI.COMM_WORLD.Get_size() #on my workstation: N=12/4=3

so that the number of available cores needn't be hardcoded.

Is this possible, and does it make sense?

Notes

I had hoped that not specifying maxprocs would do the job, just as mpirun with out -np spawns as many instances as available cores. However, Spawn then defaults to maxprocs=1.

The call of the external library is blocking, which is why I don't (wouldn't) subtract the 4 instances from the first spawn from N_avail.

I can't just use multiprocessing.cpu_count(), since this would only give me the cores on the current node (in a cluster setting). I am planning to run my code on a cluster using a SLURM scheduler.

Body:
There is an attribute of the world communicator that might provide the total number of process expected: MPI_UNIVERSE_SIZE. See the MPI standards, http://mpi-forum.org/docs/mpi-3.1/mpi31-report/node253.htm#Node253

MPI provides an attribute on MPI_COMM_WORLD, MPI_UNIVERSE_SIZE, that allows the application to obtain this information in a portable manner. This attribute indicates the total number of processes that are expected. ... An application typically subtracts the size of MPI_COMM_WORLD from MPI_UNIVERSE_SIZE to find out how many processes it should spawn. ...

In mpi4py, it can be printed as:

from mpi4py import MPI

version= MPI.Get_version()
print "mpi version is ",version

comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
print "size is ",size

universe_size=comm.Get_attr(MPI.UNIVERSE_SIZE)
print "universe size is ",universe_size

Following OpenMPI mpirun universe size , this feature can be tested by trying:

mpirun -np 1 -H localhost,localhost,localhost python main.py

If your MPI version is higher or equal to 3, the MPI_Info MPI_INFO_ENV could help you. It features two keys which might provide some pieces of information:

maxprocs   Maximum number of MPI processes to start.

soft       Allowed values for number of processors.

To use it in mpi4py, you could try:

soft=MPI.INFO_ENV.get("soft")
print soft
maxprocs=MPI.INFO_ENV.get("maxprocs")
print maxprocs


来源: stackexchange

问:
Resize canvas to whole screen after it was drawn
I am writing a simple game in javascript which draws on a HTML canvas. The canvas has a fixed size (1280 × 720) and that is also the "room" in which the objects are drawn.

Now I want the canvas to be stretched to be 100 % of the screen. I can't do that by just setting the width and height of the canvas because the javascript would only draw in the 1280 × 720 rectangle in the top left.

What I want instead is, that it is zoomed in so that it takes up the whole screen and if the javascript draws something at (1280, 720) it should be the bottom right corner.

Can I do this without using any external libraries?

答:
If you wish to keep the rendering size at 1280x720 for the canvas, but stretch or expand it to the window size you can use the css width and height for that.

Using css will only cause the shape of the canvas to change, but the internal pixels/drawing frame are still set by the width and height attribute. (This will of course cause the image to be blurry if it is upscale to much)

With CSS:

* { margin: 0; padding: 0;}

body, html { height:100%; }

#canvasID {
    position:absolute;
    height:100%;
    /*width:100%; /* uncomment if you don't care about aspect ratio*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvasID" width=128 height=72></code>```

With a script:

$(document).ready(function() {
  function resizeCanvas() {
    var canvas = $("#canvasID");
    // original width/height from the canvas attribute
    var heightOriginal = canvas[0].height;
    var widthOriginal = canvas[0].width;

    // fill to window height while maintaining aspect ratio
    var heightNew = window.innerHeight;

    // replace with window.innerWidth if you don't care about aspect ratio
    var widthNew = heightNew / heightOriginal * widthOriginal;

    canvas.css("height", heightNew + "px");
    canvas.css("width", widthNew + "px");
  }

  // keep size when window changes size
  $(window).resize(resizeCanvas);

  // initial resize of canvas on page load
  resizeCanvas();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<canvas id="canvasID" width=128 height=72></code>```

Alternately if you wish for the internal canvas resolution/size to be able to change dynamically you can use scale to ensure that everything gets rendered to the right size.

$(document).ready(function() {
    var canvas = $("#canvasID");
    // original width/height from the canvas attribute
    var heightOriginal = canvas[0].height;
    var widthOriginal = canvas[0].width;
    // current scale (original 1 to 1)
    var verticalRatio = 1;
    var horizontalRatio = 1;

    // the canvas context
    var ctx = canvas[0].getContext('2d');

    function setScale() {
      // remove previous scale
      ctx.scale(1/horizontalRatio, 1/verticalRatio);

      // fill to window height while maintaining aspect ratio
      var heightNew = window.innerHeight;

      // not needed if you don't care about aspect ratio
      var widthNew = heightNew / heightOriginal * widthOriginal;

      // these would be the same if maintaining aspect ratio
      verticalRatio = heightNew / heightOriginal;
      horizontalRatio = widthNew / widthOriginal;

      // update drawing scale
      ctx.scale(horizontalRatio, verticalRatio);

      // update width and height of canvas
      canvas[0].height = heightNew;
      canvas[0].width = widthNew;
    }

    // keep size when window changes size
    $(window).resize(setScale);

    // initial resize of canvas on page load
    setScale();
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<canvas id="canvasID" width=128 height=72></code>```

ContentLicense: CC BY-SA 3.0

Body:
If you wish to keep the rendering size at 1280x720 for the canvas, but stretch or expand it to the window size you can use the css width and height for that.

Using css will only cause the shape of the canvas to change, but the internal pixels/drawing frame are still set by the width and height attribute. (This will of course cause the image to be blurry if it is upscale to much)

With CSS:

* { margin: 0; padding: 0;}

body, html { height:100%; }

#canvasID {
    position:absolute;
    height:100%;
    /*width:100%; /* uncomment if you don't care about aspect ratio*/
}

<canvas id="canvasID" width=128 height=72>

With a script:

$(document).ready(function() {
  function resizeCanvas() {
    var canvas = $("#canvasID");
    // original width/height from the canvas attribute
    var heightOriginal = canvas[0].height;
    var widthOriginal = canvas[0].width;

    // fill to window height while maintaining aspect ratio
    var heightNew = window.innerHeight;

    // replace with window.innerWidth if you don't care about aspect ratio
    var widthNew = heightNew / heightOriginal * widthOriginal;

    canvas.css("height", heightNew + "px");
    canvas.css("width", widthNew + "px");
  }

  // keep size when window changes size
  $(window).resize(resizeCanvas);

  // initial resize of canvas on page load
  resizeCanvas();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<canvas id="canvasID" width=128 height=72>

Alternately if you wish for the internal canvas resolution/size to be able to change dynamically you can use scale to ensure that everything gets rendered to the right size.

$(document).ready(function() {
    var canvas = $("#canvasID");
    // original width/height from the canvas attribute
    var heightOriginal = canvas[0].height;
    var widthOriginal = canvas[0].width;
    // current scale (original 1 to 1)
    var verticalRatio = 1;
    var horizontalRatio = 1;

    // the canvas context
    var ctx = canvas[0].getContext('2d');

    function setScale() {
      // remove previous scale
      ctx.scale(1/horizontalRatio, 1/verticalRatio);

      // fill to window height while maintaining aspect ratio
      var heightNew = window.innerHeight;

      // not needed if you don't care about aspect ratio
      var widthNew = heightNew / heightOriginal * widthOriginal;

      // these would be the same if maintaining aspect ratio
      verticalRatio = heightNew / heightOriginal;
      horizontalRatio = widthNew / widthOriginal;

      // update drawing scale
      ctx.scale(horizontalRatio, verticalRatio);

      // update width and height of canvas
      canvas[0].height = heightNew;
      canvas[0].width = widthNew;
    }

    // keep size when window changes size
    $(window).resize(setScale);

    // initial resize of canvas on page load
    setScale();
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<canvas id="canvasID" width=128 height=72>


问:
What does the error "Compile with /main to specify the type that contains the entry point." mean
I was troubleshooting steps I could find in relation to an IIS 502.5 error with no success.

In desperation I tried starting over using dotnet publish from the command line and got a build error telling me there were 2 entry points in the application and that I needed to "Compile with /main to specify the type that contains the entry point."  First I checked my solution to verify that there is only 1 Main() method in the project. Even though the target namespace is specified in the csproj file, I leave no stone unturned and attempt to run dotnet build with a /main switch only to be told that /main is an unknown switch.

So...what is that error message is telling me and where might I look next to discover what I am certain will be an embarrassing developer error.

答:
In desperation I went back over the commits I had made since I last was able to run the app successfully and I noticed I had upgraded my test SDK library from 15.3.0 to 15.5.0.  Since I had read several issues regarding MSTest injecting a program main into the test project, so I reverting to version 15.3.0 and my program is now fine in development again. I am not certain what changed between the two versions because Andrew Lock in this blog post describes the problem in detail with version 15.3.0.  I don't know why I was ok with version 15.3.0.

Still didn't solve my problem with the 502.5 error in IIS


问:
VueJS Array update bug
I have a JSFiddle below to explain my problem but basically I have an array called tiles which has a title. When the instance is created() I add a field to this array called active

I then output this array in an
 element and loop through it outputting the title and active objects. My problem is as you can see in the fiddle when I run v-on:click="tile.active = true" nothing happens to the active state written in the
 element

but if I run v-on:click="tile.title = 'test'" it seems to update the active object and the title object.

Its strange behaviour I can't seem to work out why. Does anyone have any ideas?

https://jsfiddle.net/jgb34dqo/

Thanks

答:
It's to do with Vue not knowing about your properties, change your array to this:

```<code>tiles: [
  {
    title: 'tile one',
    active: false
  },
  {
    title: 'tile two',
    active: false
  },
  {
    title: 'tile three',
    active: false
  }
]
</code>```

This allows Vue to know about the active property and in turn it knows to monitor that variable.

It's worth looking at this link about Vue Reactivity as it helps with understanding how and when data will change automagically.

If you must add the properties after

take a look at $set. It allows you to add props to an object that then get watched by vue. See this fiddle, notice the change:

```<code>this.tiles.forEach(function(tile) {
  // Tell vue to add and monitor an `active` prop against the tile object
  this.$set(tile, 'active',  false);
}.bind(this))
</code>```

Title: VueJS Array update bug

Body:
It's to do with Vue not knowing about your properties, change your array to this:

tiles: [
  {
    title: 'tile one',
    active: false
  },
  {
    title: 'tile two',
    active: false
  },
  {
    title: 'tile three',
    active: false
  }
]

This allows Vue to know about the active property and in turn it knows to monitor that variable.

It's worth looking at this link about Vue Reactivity as it helps with understanding how and when data will change automagically.

If you must add the properties after

take a look at $set. It allows you to add props to an object that then get watched by vue. See this fiddle, notice the change:

this.tiles.forEach(function(tile) {
  // Tell vue to add and monitor an `active` prop against the tile object
  this.$set(tile, 'active',  false);
}.bind(this))

ContentLicense: CC BY-SA 4.0


问:
ping: http://google.com: Name or service not known on minimal centos on virtual box
Installed minimal centos on virtual box. Getting this error when ping google.com.

ping: http://google.com: Name or service not known

答:
First make sure you have your network adapter enabled in virtual box settings.

Your network interface which you use it for connecting to internet might not be active.

To check this,use "sudo nmcli d" command.

If it is disconnected,use "sudo nmtui"->Edit a connection,select your network interface and
choose "Automatically connect" option(by pressing Space key) and
select OK.

Do "sudo reboot now"  After logging in,do "ping
www.google.com".

You should be able to connect now.


问:
Beginner HTML/CSS Mistake
I'm taking a beginning web design class on Treehouse, and I have a question about centering a class in HTML with CSS, It's not coming out right, even though I have checked instructions. Can someone please look at this code and tell me what I've done wrong?

Here's the HTML:

```<code><main class="flex">
  <div class="card">
    <h2>class="card-title">Background</h2>
</code>```

And, Here's the CSS:

```<code>.card-title {
   text-align:center;
}
</code>```

The output is like this: "class="card-title">Background"

I'm sure the answer is something super simple, because this is a simple course. But I'm just learning, and I'm rather nervous, so any help you can provide will be awesome!

答:
You are closing the h2 too early. Also note that when you set a parent element to display: flex - all its children are affected - you may need to set a flex value on the h2  - or rethink the use of flex (thats is assuming your class of flex is to set the display:flex on the main element and its childrent - cards). If its as simple as centering the text, you won't need to use flex. And I am assuming that you are closing the  and the div.card as well..

It should be

```<code><h2 class="card-title">Background</h2>
</code>```

Title: Beginner HTML/CSS Mistake

Body:
I'm taking a beginning web design class on Treehouse, and I have a question about centering a class in HTML with CSS, It's not coming out right, even though I have checked instructions. Can someone please look at this code and tell me what I've done wrong?

Here's the HTML:

class="card-title">Background

And, Here's the CSS:

.card-title {
   text-align:center;
}

The output is like this: "class="card-title">Background"

I'm sure the answer is something super simple, because this is a simple course. But I'm just learning, and I'm rather nervous, so any help you can provide will be awesome!

Body:
You are closing the h2 too early. Also note that when you set a parent element to display: flex - all its children are affected - you may need to set a flex value on the h2  - or rethink the use of flex (thats is assuming your class of flex is to set the display:flex on the main element and its childrent - cards). If its as simple as centering the text, you won't need to use flex. And I am assuming that you are closing the <main> and the div.card as well..

It should be

<h2 class="card-title">Background</h2>


问:
List Classes inside jar dynamically
Alright, so I have this jar file
and I'd like to retrieve all the classes inside that jar.

I've seen some other questions, but, most of them require the class name or package name.

I'd like something that doesn't need this. Maybe a method that asks for the file path "example.jar", and then it returns a list with the various class names.

By the way, I don't really now if class name is the correct term, what i need is something like this "com.name.name1".

I would use the Strings retrieved from the jar with Reflection.
The result would be loading a jar dynamically without the need of any classnames.

答:
You can use JarFile#entries to get an enumeration of the ZIP file entries, than use a URLClassLoader to get the classes:

```<code>private List<Class<?>> loadClasses(String pathToJar) throws IOException, ClassNotFoundException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    try (JarFile jarFile = new JarFile(pathToJar)) {
        URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
        URLClassLoader loader = URLClassLoader.newInstance(urls);

        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entry.isDirectory() || !entryName.endsWith(".class"))
                continue;

            String className = entryName.replaceAll("\\.class$", "").replace('/', '.');
            Class<?> clazz = loader.loadClass(className);
            classes.add(clazz);
        }
    }
    return classes;
}
</code>```

Title: List Classes inside jar dynamically

Body:
You can use JarFile#entries to get an enumeration of the ZIP file entries, than use a URLClassLoader to get the classes:

private List<Class<?>> loadClasses(String pathToJar) throws IOException, ClassNotFoundException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    try (JarFile jarFile = new JarFile(pathToJar)) {
        URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
        URLClassLoader loader = URLClassLoader.newInstance(urls);

        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entry.isDirectory() || !entryName.endsWith(".class"))
                continue;

            String className = entryName.replaceAll("\\.class$", "").replace('/', '.');
            Class<?> clazz = loader.loadClass(className);
            classes.add(clazz);
        }
    }
    return classes;
}


问:
Gnuplot X value for GPVAL_DATA_Y_MAX
How can I obtain x value for GPVAL_DATA_Y_MAX? I have data generated from FLUKA simulation (proton beam hitting water phantom), which I can't describe as a function. I would like to get something like this graph from here: Gnuplot: find x value for given y but for the maximum Y value.
Right now the GNUPLOT code is this:

```<code>max_y = GPVAL_DATA_Y_MAX
set label 2 gprintf("Maximum = %g", max_x) at 5, max_y-0.02
</code>```

And the output is this:

As you can see the maximum is around 3.

答:
You can use the stats command for this kind of analysis. For example, if you have a data file test.dat that looks like

```<code>1 1
2 2
3 3
4 10
5 5
</code>```

then you can run

```<code>stats "test.dat"
</code>```

which will set the variable STATS_pos_max_y to 4.0. See help stats for a list of available analyses.

Title: Gnuplot X value for GPVAL_DATA_Y_MAX

Body:
How can I obtain x value for GPVAL_DATA_Y_MAX? I have data generated from FLUKA simulation (proton beam hitting water phantom), which I can't describe as a function. I would like to get something like this graph from here: Gnuplot: find x value for given y but for the maximum Y value.
Right now the GNUPLOT code is this:

max_y = GPVAL_DATA_Y_MAX
set label 2 gprintf("Maximum = %g", max_x) at 5, max_y-0.02

And the output is this:

As you can see the maximum is around 3.

Body:
You can use the stats command for this kind of analysis. For example, if you have a data file test.dat that looks like

1 1
2 2
3 3
4 10
5 5

then you can run

stats "test.dat"

which will set the variable STATS_pos_max_y to 4.0. See help stats for a list of available analyses.


问:
why use xcode if monotouch is available?
if mono touch is available than why we should use mac environment(sdk,xcode+Interface Builder)?

what are the disadvantage of monotouch compare to xcode?

答:
I always prefer working in the language that is most philosophically aligned with the platform I am developing for.

That is to say, the frameworks the whole platform is built around were written for and in Objective-C.  As such, if you are working in Objective-C yourself for a while you understand why things are built the way they are, and can also anticipate calls that might exist or behaviors.

Just as I would not develop for Windows Phone 7 in anything but Silverlight, I would not program the iPhone in anything but Objective-C in order to get the most out of the platform.  New language?  That's a benefit as people should learn new languages now and then anyway.  And it's not like it saves you that much time to use a language you already know since a large majority of your time will be spent learning the frameworks (which MonoTouch lets you call into).

ContentLicense: CC BY-SA 2.5


问:
Why does '&SAMLRequest' get appended to my ADFS entrypoint URL?
I am using adfs IDP and saml for sso using passport-saml.

My entry point is as follows:

```<code>https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https://<domain-name>/saml/metadata
</code>```

When I give this URL, the adfs sso login page loads fine, but when I run the application, &SAMLRequest gets appended with this URL:

```<code>https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https%3A%2F%2F<domain-name>%2Fsaml%2Fmetadata&SAMLRequest=nVNBbtswEPyKwLskS0lQh7BsODaKGkhbw1Z76CVgyJVDgCJV7ipxfl9KtgIfGh18IrA7HM7OLGeLY22iV%2FConS1YlkzYYj5DUZuGL1t6sTv42wJSFGAWed8oWOstdwI1citqQE6S75ffH3meTHjjHTnpDIs264I93cL09uY5z%2FPptMrvIBdimrHo9%2FBguBGAiC1sLJKwFEqT7EucZXGWl%2FmE5xm%2FuUvus%2Fs%2FLNqeqR%2B0VdoexnU8n0DIv5XlNt7%2B3JcsWiKCp%2FDwyllsa%2FB78K9awq%2FdY8FeiBrkaao7IdK4VlXaACbS1SxaBw%2B0FdSLHkGmQlWYGkw3qtlYTVoQqL0%2BWGcTgc1xYdxB29LtmmKMpfM5rYGEEiTYKRDe2%2BQvkhg3QAzDsrlxUpgYjo0HxBgsaXqPtZqlF7xD6j8C0Wa9dUbL92tS%2F%2Bp8LehzdJZkfUWruOqhHGqhzVKpTlzIyBj3tvIQjCsY%2BRZYOkg77yKofjNDhgTHqzZz5epGeI1dmHAUkgaLL4lXJji4g%2Boaw0dhksuOOpS34XhzXnWLDTIMVnphsXGeztH8T8%2F81PvEjo%2Fu5e%2Bd%2FwM%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1&Signature=EdEYkblB2aOEWvoeMtmWVOkeePocMAeRu2gGBRWrjyQvx%2BEP8eekHSb4IQwodJIui%2BXw%2F%2B0ziKD%2FmwFgaIlFhmWa3ZXpiluzhG8OjK2CaH1trnXNrZM3L%2FYANlXwVl2Z4WF4GF8EP7tmIci8XxFrdP%2Fz3EZ2rlCRdELJV%2FK9wNUUiMFF6FLdExcvZieb5ug15I9wynZndhzAZL46f3cjPvMpsJ9oekR8OKIejXmYOevW0OMq%2BbGGipHKE6B1WwTSaPWGrhdEYPSTHvKpmWrz%2F%2FDscCdF9zLqv%2FGY7TgMhTg9FtlfeQ2jnqeaABBilgYaF4B5zLfCGKk5BmxqwzazGg%3D%3D
</code>```

The & symbol causes the page to  load with an error, but when I replace this symbol with any other symbol, the page loads fine. Why is that, and how can I fix it?

答: It looks like the request is a GET vs a POST.</p>

Body:
I am using adfs IDP and saml for sso using passport-saml.

My entry point is as follows:

https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https://<domain-name>/saml/metadata

When I give this URL, the adfs sso login page loads fine, but when I run the application, &SAMLRequest gets appended with this URL:

https://<domain-name>/adfs/ls/IdpInitiatedSignon.aspx?loginToRp=https%3A%2F%2F<domain-name>%2Fsaml%2Fmetadata&SAMLRequest=nVNBbtswEPyKwLskS0lQh7BsODaKGkhbw1Z76CVgyJVDgCJV7ipxfl9KtgIfGh18IrA7HM7OLGeLY22iV%2FConS1YlkzYYj5DUZuGL1t6sTv42wJSFGAWed8oWOstdwI1citqQE6S75ffH3meTHjjHTnpDIs264I93cL09uY5z%2FPptMrvIBdimrHo9%2FBguBGAiC1sLJKwFEqT7EucZXGWl%2FmE5xm%2FuUvus%2Fs%2FLNqeqR%2B0VdoexnU8n0DIv5XlNt7%2B3JcsWiKCp%2FDwyllsa%2FB78K9awq%2FdY8FeiBrkaao7IdK4VlXaACbS1SxaBw%2B0FdSLHkGmQlWYGkw3qtlYTVoQqL0%2BWGcTgc1xYdxB29LtmmKMpfM5rYGEEiTYKRDe2%2BQvkhg3QAzDsrlxUpgYjo0HxBgsaXqPtZqlF7xD6j8C0Wa9dUbL92tS%2F%2Bp8LehzdJZkfUWruOqhHGqhzVKpTlzIyBj3tvIQjCsY%2BRZYOkg77yKofjNDhgTHqzZz5epGeI1dmHAUkgaLL4lXJji4g%2Boaw0dhksuOOpS34XhzXnWLDTIMVnphsXGeztH8T8%2F81PvEjo%2Fu5e%2Bd%2FwM%3D&SigAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsig%23rsa-sha1&Signature=EdEYkblB2aOEWvoeMtmWVOkeePocMAeRu2gGBRWrjyQvx%2BEP8eekHSb4IQwodJIui%2BXw%2F%2B0ziKD%2FmwFgaIlFhmWa3ZXpiluzhG8OjK2CaH1trnXNrZM3L%2FYANlXwVl2Z4WF4GF8EP7tmIci8XxFrdP%2Fz3EZ2rlCRdELJV%2FK9wNUUiMFF6FLdExcvZieb5ug15I9wynZndhzAZL46f3cjPvMpsJ9oekR8OKIejXmYOevW0OMq%2BbGGipHKE6B1WwTSaPWGrhdEYPSTHvKpmWrz%2F%2FDscCdF9zLqv%2FGY7TgMhTg9FtlfeQ2jnqeaABBilgYaF4B5zLfCGKk5BmxqwzazGg%3D%3D

The & symbol causes the page to  load with an error, but when I replace this symbol with any other symbol, the page loads fine. Why is that, and how can I fix it?


问:
SQL Server 2008: The columns in table do not match an existing primary key or unique constraint
I need to make some changes to a SQL Server 2008 database.

This requires the creation of a new table, and inserting a foreign key in the new table that references the Primary key of an already existing table. So I want to set up a relationship between my new tblTwo, which references the primary key of tblOne.

However when I tried to do this (through SQL Server Management Studio) I got the following error:

The columns in table 'tblOne' do not
  match an existing primary key or
  UNIQUE constraint

I'm not really sure what this means, and I was wondering if there was any way around it?

答: I've found another way to get this error.  This can also happen if you are trying to make a recursive foreign key (a foreign key to the primary key in the same table) in design view in SQL Management Studio.  If you haven't yet saved the table with the primary key it will return this message.  Simply save the table then it will allow you to create the foreign key.</p>


问:
How to Invoke Click on this Button in WebBrowser
Here is the HTML Button...

```<code><div class="submitBtnContainer">

<button class="nf-btn nf-btn-primary nf-btn-solid nf-btn-align-undefined nf-btn-oversize" type="button" autocomplete="off" tabindex="0" placeholder="planSelection_button_continue"><!-- react-text: 186 -->CONTINUE<!-- /react-text --></button>

</div>
</code>```

I'm try this code...

```<code>For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("submitBtnContainer") Then
Element.InvokeMember("click")
Return
End If
Next
</code>```

答: You are requesting elements of tag "a" which is the anchor tag.  From what I can see, there are no anchor tags (URL links).  I suggest you replace "a" with "button" which is the tag of the button itself.</p>

Body:
Here is the HTML Button...

<button class="nf-btn nf-btn-primary nf-btn-solid nf-btn-align-undefined nf-btn-oversize" type="button" autocomplete="off" tabindex="0" placeholder="planSelection_button_continue">CONTINUE</button>

I'm try this code...

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("submitBtnContainer") Then
Element.InvokeMember("click")
Return
End If
Next


问:
Used C constant in Ada's modular type bound
I have a similar problem to the one present in this question.

I want to use a C constant in Ada as a range a of modular type.

Unfortunately I get an error:

```<code>linux-char_device.ads:52:27: non-static expression used for modular type bound
linux-char_device.ads:52:27: "MAJOR_NUM" is not a static constant (RM 4.9(5))
</code>```

The C code is:

```<code>const unsigned major_num = 7;
</code>```

The Ada code is:

```<code>MAJOR_NUM : constant Interfaces.C.unsigned;
pragma Import (
   Convention    => C,
   Entity        => MAJOR_NUM,
   External_Name => "major_num"
);

type Major_Type is mod MAJOR_NUM;
</code>```

答:
Compile time constants are typically directly used in the resulting assembler code and can never be imported or exported from or to any language in gcc. That is, if your C code really contains

const unsigned major_num = 7;

you wont find major_num in the resulting object file, unless perhaps you use -O0. Try nm on any object file (for C or Ada, doesn't matter) to check.

You therefore cannot import a compile time constant in Ada. If you want to create an Ada binding for some C (or C++) functions you have to redeclare the C constant as an Ada constant:

MAJOR_NUM : constant Interfaces.C.unsigned := 7;

The easiest way is to use the gcc switch -fdump-ada-spec on a C header. See Generating Ada Bindings for C and C++ headers

Body:
I have a similar problem to the one present in this question.

I want to use a C constant in Ada as a range a of modular type.

Unfortunately I get an error:

linux-char_device.ads:52:27: non-static expression used for modular type bound
linux-char_device.ads:52:27: "MAJOR_NUM" is not a static constant (RM 4.9(5))

The C code is:

const unsigned major_num = 7;

The Ada code is:

MAJOR_NUM : constant Interfaces.C.unsigned;
pragma Import (
   Convention    => C,
   Entity        => MAJOR_NUM,
   External_Name => "major_num"
);

type Major_Type is mod MAJOR_NUM;


问:
Red Hat Developer: Subscription Attachment
I installed RHEL7 for developers (NO-Cost subscription) and registered it with my username and password for the customer portal , however it doesn't want to attach the subscription.

So in order to do it manually I need to run the following command

```<code>subscription-manager attach --pool=YourID
</code>```

And in order to find my ID I have to run the command

```<code>subscription-manager list --available
</code>```

Which returns

No available subscription pools to list

I logged in in my account on developers.redhat.com and it says:

But on the customer panel it says I don't have any active subscriptions

What am I doing wrong?

Thank you in advance!!

答:
try :

$ subscription-manager register

put your username and password then :

$ subscription-manager attach --auto

Should say something like:

Installed Product Current Status :

Product Name: Red Hat Enterprise Linux

Status: Subscribed

Body:
I installed RHEL7 for developers (NO-Cost subscription) and registered it with my username and password for the customer portal , however it doesn't want to attach the subscription.

So in order to do it manually I need to run the following command

subscription-manager attach --pool=YourID

And in order to find my ID I have to run the command

subscription-manager list --available

Which returns

No available subscription pools to list

I logged in in my account on developers.redhat.com and it says:

But on the customer panel it says I don't have any active subscriptions

What am I doing wrong?

Thank you in advance!!


问:
Session being destroyed on remote server, but ok on local version of site
I have a local and remote version of a CMS I've built on top of a PHP framework - in the local version of the site, my authentication session works absolutely fine when I check it from a couple of 3rd party modules integrated into the site, however, in the remote site the session is always destroyed whenever I try to check it from any of these modules, which breaks my authentication handling. The code is identical, so I'm guessing that this isn't anything to do with the framework, more to do with the server environment.

The session config in php.ini is the same for both my local and remote servers. My local version of PHP is 5.3, while the remote version is 5.2.9, but I don't think that would be affecting this issue.

Has anyone any ideas what this could potentially be related to?

答: Can the web server write to wherever session data is configured to be stored?  (usually the /tmp directory, but could be set to a different location in the php.ini file).  Is the browser accepting the session cookie?  </p>


问:
iOS Simulator Screenshots "Wrong Size" for iTunes Connect
I am taking screenshots from my iOS Simulator and trying to put them into iTunes Connect but it continues to tell me that I have the wrong size. They are the same size with the pictures that are already in iTunes Connect. What just happened?</p>

答: If you are using Xcode 9. Window > Zoom and take screenshot.


问:
http-proxy-middleware - access to the static files
I'm trying to combine my static landing page with the express.js app (react.js single page app).

On my landing page, I set up proxy using http-proxy-middleware
My server.js for the static page looks like that:

```<code>var express = require('express');
var app = express();
var path = require('path');
var proxy = require('http-proxy-middleware');

var options = {
        target: 'http://localhost:9000', // the app
        changeOrigin: true
    };
var exampleProxy = proxy(options);

app.use('/app', exampleProxy);
app.use(express.static(__dirname + '/'))

app.listen(8080);
</code>```

The problem is that when I get to localhost:8080/app/ I have access to correct index.html, but I cannot fetch the resources, the bundle.js is being fetched like that: http://localhost:8080/bundle.js, but apparently it is available on localhost:9000, not 8080

How do I make it so as the app has access to its static files?

答:
You can use the wildcard path matching of http-proxy-middleware module. You can implement the app.use without passing the path parameter.

```<code>app.use(proxy('/*.js', exampleProxy));
app.use(proxy('/api', exampleProxy));
</code>```

This will serve your ".js" file through port 9000. Similarly, you can serve other assets as well by using this wildcard matching.

Body:
I'm trying to combine my static landing page with the express.js app (react.js single page app).

On my landing page, I set up proxy using http-proxy-middleware
My server.js for the static page looks like that:

var express = require('express');
var app = express();
var path = require('path');
var proxy = require('http-proxy-middleware');

var options = {
        target: 'http://localhost:9000', // the app
        changeOrigin: true
    };
var exampleProxy = proxy(options);

app.use('/app', exampleProxy);
app.use(express.static(__dirname + '/'))

app.listen(8080);

The problem is that when I get to localhost:8080/app/ I have access to correct index.html, but I cannot fetch the resources, the bundle.js is being fetched like that: http://localhost:8080/bundle.js, but apparently it is available on localhost:9000, not 8080

How do I make it so as the app has access to its static files?

Body:
You can use the wildcard path matching of http-proxy-middleware module. You can implement the app.use without passing the path parameter.

app.use(proxy('/*.js', exampleProxy));
app.use(proxy('/api', exampleProxy));

This will serve your ".js" file through port 9000. Similarly, you can serve other assets as well by using this wildcard matching.


问:
C# MDI Child changing size during run time?
Essentially I have a MDI Parent window, which runs my MainMenu form as a MDI Child, from the Main Menu I can go open other forms. I had the MainMenu then resize the MDI Parent to the size of the MDI Child form.
This works perfectly, however the problem is when I go back to the MainMenu form, for some reason the size property has changed to whichever form I had opened.

```<code>    private void MDI_MdiChildActivate(object sender, EventArgs e)
    {
        try
        {
            this.ClientSize = this.ActiveMdiChild.Size;
            this.CenterToScreen();
        }
        catch { }
    }
</code>```

This is the code for resizing my MDI Parent.

I am not asking about how to get the size of a Parent or child form, my code works just fine one way. The issue is that the MainMenu size property changes during run time despite me never changing the size of the MainMenu. The MainMenu form is not the MDI Parent but a child also.

答:
To make a Window as big as your Mdi parent, you should set the FormState of the Mdi Child to maximized instead.

Also, why do you modify the size when an MDI child is activated ?  Why not just setting it to Maximized on creation of the MDI child, like this:

```<code>private void button1_Click(object sender, EventArgs e)
{
    Form2 f = new Form2();

    f.MdiParent = this;
    f.WindowState = FormWindowState.Maximized;

    f.Show();
}
</code>```

If you want to have only one MDI child visible at a time, then make sure you hide the others.
You can do it like this for instance:

```<code>private Form2 _f2;
private Form3 _f3;

private void open1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (_f2 == null)
    {
        _f2 = new Form2();
    }

    ShowForm(_f2);
}

private void open2ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (_f3 == null)
    {
        _f3 = new Form3();
    }
    ShowForm(_f3);
}

private void ShowForm(Form f)
{

    var otherWindows = this.MdiChildren.Where(child => child != f);

    foreach (var o in otherWindows)
    {
        o.Hide();
    }

    f.MdiParent = this;
    f.WindowState = FormWindowState.Maximized;

    f.Show();
}
</code>```

Note that you can also choose to close the other forms, depending on what's on them and if you need to save, etc...

Body:
Essentially I have a MDI Parent window, which runs my MainMenu form as a MDI Child, from the Main Menu I can go open other forms. I had the MainMenu then resize the MDI Parent to the size of the MDI Child form.
This works perfectly, however the problem is when I go back to the MainMenu form, for some reason the size property has changed to whichever form I had opened.

    private void MDI_MdiChildActivate(object sender, EventArgs e)
    {
        try
        {
            this.ClientSize = this.ActiveMdiChild.Size;
            this.CenterToScreen();
        }
        catch { }
    }

This is the code for resizing my MDI Parent.

I am not asking about how to get the size of a Parent or child form, my code works just fine one way. The issue is that the MainMenu size property changes during run time despite me never changing the size of the MainMenu. The MainMenu form is not the MDI Parent but a child also.

Body:
To make a Window as big as your Mdi parent, you should set the FormState of the Mdi Child to maximized instead.

Also, why do you modify the size when an MDI child is activated ?  Why not just setting it to Maximized on creation of the MDI child, like this:

private void button1_Click(object sender, EventArgs e)
{
    Form2 f = new Form2();

    f.MdiParent = this;
    f.WindowState = FormWindowState.Maximized;

    f.Show();
}

If you want to have only one MDI child visible at a time, then make sure you hide the others.
You can do it like this for instance:

private Form2 _f2;
private Form3 _f3;

private void open1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (_f2 == null)
    {
        _f2 = new Form2();
    }

    ShowForm(_f2);
}

private void open2ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (_f3 == null)
    {
        _f3 = new Form3();
    }
    ShowForm(_f3);
}

private void ShowForm(Form f)
{

    var otherWindows = this.MdiChildren.Where(child => child != f);

    foreach (var o in otherWindows)
    {
        o.Hide();
    }

    f.MdiParent = this;
    f.WindowState = FormWindowState.Maximized;

    f.Show();
}

Note that you can also choose to close the other forms, depending on what's on them and if you need to save, etc...


问:
Wordpress Spotify playlist Embed, '&theme=white' gets encoded
I'm trying to get some spotify playlists on a blog with the white theme.
No idea why the ampersand of '&theme=white' gets encoded.
I have tried commenting the lines in formatting.php

```<code>//$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
</code>```

and

```<code>//$url = str_replace( '&', '&', $url );
</code>```

But it still gets encoded...
I'm using the Bridge Theme with WPBakery and Visual composer.
Are those guys messing with the encoding probably?

Here is the iframe code:

```<code><iframe src="https://open.spotify.com/embed/artist/2hbw7tsQv6Ejqc8kBDoFIK&theme=white" width="300" height="380" frameborder="0"></iframe>
</code>```

答:
& is only used between different query parameters

? is only used between the path and the query parameters

Since you only have one query parameter, just change & into a ?

Body:
I'm trying to get some spotify playlists on a blog with the white theme.
No idea why the ampersand of '&theme=white' gets encoded.
I have tried commenting the lines in formatting.php

//$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);

and

//$url = str_replace( '&', '&', $url );

But it still gets encoded...
I'm using the Bridge Theme with WPBakery and Visual composer.
Are those guys messing with the encoding probably?

Here is the iframe code:


问:
Scala main class error
My Program - HelloWorld.scala

```<code>object HelloWorld {
    def main(args: Array[String]): Unit = {
        println("Hello, world!")
    }
}
</code>```

jar cvfe HelloWorld.jar HelloWorld HelloWorld*.class

After jar file is created i tried to get the output from jar file

```<code>java -jar HelloWorld.jar
</code>```

but i got the error

```<code>    Exception in thread "main" java.lang.NoClassDefFoundError: scala/Predef$
        at HelloWorld$.main(HelloWorld.scala:12)
        at HelloWorld.main(HelloWorld.scala)
Caused by: java.lang.ClassNotFoundException: scala.Predef$
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 2 more
</code>```

答:
Add line

```<code>Class-Path: /home/dmitin/.m2/repository/org/scala-lang/scala-library/2.12.3/scala-library-2.12.3.jar
</code>```

(i.e. your location of scala-library) to HelloWorld.jar/META-INF/MANIFEST.MF.

Then

```<code>java -jar HelloWorld.jar Dmytro
</code>```

produces

```<code>Hello, Dmytro!
</code>```

Title: Scala main class error

Body:
My Program - HelloWorld.scala

object HelloWorld {
    def main(args: Array[String]): Unit = {
        println("Hello, world!")
    }
}

jar cvfe HelloWorld.jar HelloWorld HelloWorld*.class

After jar file is created i tried to get the output from jar file

java -jar HelloWorld.jar

but i got the error

    Exception in thread "main" java.lang.NoClassDefFoundError: scala/Predef$
        at HelloWorld$.main(HelloWorld.scala:12)
        at HelloWorld.main(HelloWorld.scala)
Caused by: java.lang.ClassNotFoundException: scala.Predef$
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 2 more

Body:
Add line

Class-Path: /home/dmitin/.m2/repository/org/scala-lang/scala-library/2.12.3/scala-library-2.12.3.jar

(i.e. your location of scala-library) to HelloWorld.jar/META-INF/MANIFEST.MF.

Then

java -jar HelloWorld.jar Dmytro

produces

Hello, Dmytro!


问:
Convert a string with bytes to a float array
I get a string from a socket that contains a float array as bytes. Now I want to convert this string in to a float (4bit) numpy array.

for example I get:

```<code>"\x00\x00\x00\x00\x00\x00\x00\x00"
</code>```

and I want an output like this:

```<code>[0, 0]
</code>```

答:
You can use the fromstring method and specify the number of bytes to convert to (32 bits = 4 bytes in this particular case):

```<code>np.fromstring( "\x00\x00\x00\x00\x00\x00\x00\x00", np.float32 )
</code>```

You need to ensure your string has lenght multiple of 4. Otherwise numpy will rise:

```<code>ValueError: string size must be a multiple of element size
</code>```

Body:
I get a string from a socket that contains a float array as bytes. Now I want to convert this string in to a float (4bit) numpy array.

for example I get:

"\x00\x00\x00\x00\x00\x00\x00\x00"

and I want an output like this:

[0, 0]

Body:
You can use the fromstring method and specify the number of bytes to convert to (32 bits = 4 bytes in this particular case):

np.fromstring( "\x00\x00\x00\x00\x00\x00\x00\x00", np.float32 )

You need to ensure your string has lenght multiple of 4. Otherwise numpy will rise:

ValueError: string size must be a multiple of element size


问:
Failed looking up window - different behaviors from same app on 2 galaxy nexus
I have two Galaxy Nexus phones.  The phones are the same firmware version 4.0.2, same build number, same kernel version.  When I deploy the same exact app to both of the phones using Eclipse, I see different behaviors from each.

On one phone, everything works as expected. On the other phone, the main Activity crashes when switching to another activity and back to the main one, both by back button and by other activities finishing and returning to the activity that created it.  The only clue I have to this problem is this error:

```<code>04-18 17:43:30.811: I/ActivityManager(207): Displayed org.mitre.Mobile/.Activities.QueryActivity: +430ms
04-18 17:43:30.819: I/n*.w*.w*.ZoomButtonsCo*(4962): invoke: onVisibilityChanged listener: org.osmdroid.views.MapView$MapViewZoomListener@4181ecd8
04-18 17:43:30.843: E/InputQueue-JNI(4962): channel '41d66628 Panel:org.mitre.Mobile/org.mitre.Mobile.Activities.MobileActivity (client)' ~ Publisher closed input channel or an error occurred.  events=0x8
04-18 17:43:30.843: W/WindowManager(207): Force-removing child win Window{41d66628 Panel:org.mitre.Mobile/org.mitre.Mobile.Activities.MobileActivity paused=false} from container Window{420815c8 org.mitre.Mobile/org.mitre.Mobile.Activities.MobileActivity paused=false}
04-18 17:43:30.850: W/WindowManager(207): Failed looking up window
04-18 17:43:30.850: W/WindowManager(207): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy@41f9e658 does not exist
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7029)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7020)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.WindowManagerService.removeWindow(WindowManagerService.java:2180)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.Session.remove(Session.java:149)
04-18 17:43:30.850: W/WindowManager(207):   at android.view.IWindowSession$Stub.onTransact(IWindowSession.java:124)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.Session.onTransact(Session.java:111)
04-18 17:43:30.850: W/WindowManager(207):   at android.os.Binder.execTransact(Binder.java:338)
04-18 17:43:30.850: W/WindowManager(207):   at dalvik.system.NativeStart.run(Native Method)
</code>```

I haven't really found anything useful on the internet related to this error message.  I have some experience with android, but this one has really stumped me.  I initially thought this was a nova launcher problem (the phone with the problem has it), but I installed nova on the other phone and still saw the same behaviors.

The phone with the app that doesn't work properly is my personal phone, the other is a work phone.

答:
The issue happened to me after switching build variants. Something may be messed up with your build. Try restarting Android Studio, clean and rebuild. That solved the issue for me.

Good luck!

Body:
I have two Galaxy Nexus phones.  The phones are the same firmware version 4.0.2, same build number, same kernel version.  When I deploy the same exact app to both of the phones using Eclipse, I see different behaviors from each.

On one phone, everything works as expected. On the other phone, the main Activity crashes when switching to another activity and back to the main one, both by back button and by other activities finishing and returning to the activity that created it.  The only clue I have to this problem is this error:

04-18 17:43:30.811: I/ActivityManager(207): Displayed org.mitre.Mobile/.Activities.QueryActivity: +430ms
04-18 17:43:30.819: I/n*.w*.w*.ZoomButtonsCo*(4962): invoke: onVisibilityChanged listener: org.osmdroid.views.MapView$MapViewZoomListener@4181ecd8
04-18 17:43:30.843: E/InputQueue-JNI(4962): channel '41d66628 Panel:org.mitre.Mobile/org.mitre.Mobile.Activities.MobileActivity (client)' ~ Publisher closed input channel or an error occurred.  events=0x8
04-18 17:43:30.843: W/WindowManager(207): Force-removing child win Window{41d66628 Panel:org.mitre.Mobile/org.mitre.Mobile.Activities.MobileActivity paused=false} from container Window{420815c8 org.mitre.Mobile/org.mitre.Mobile.Activities.MobileActivity paused=false}
04-18 17:43:30.850: W/WindowManager(207): Failed looking up window
04-18 17:43:30.850: W/WindowManager(207): java.lang.IllegalArgumentException: Requested window android.os.BinderProxy@41f9e658 does not exist
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7029)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.WindowManagerService.windowForClientLocked(WindowManagerService.java:7020)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.WindowManagerService.removeWindow(WindowManagerService.java:2180)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.Session.remove(Session.java:149)
04-18 17:43:30.850: W/WindowManager(207):   at android.view.IWindowSession$Stub.onTransact(IWindowSession.java:124)
04-18 17:43:30.850: W/WindowManager(207):   at com.android.server.wm.Session.onTransact(Session.java:111)
04-18 17:43:30.850: W/WindowManager(207):   at android.os.Binder.execTransact(Binder.java:338)
04-18 17:43:30.850: W/WindowManager(207):   at dalvik.system.NativeStart.run(Native Method)

I haven't really found anything useful on the internet related to this error message.  I have some experience with android, but this one has really stumped me.  I initially thought this was a nova launcher problem (the phone with the problem has it), but I installed nova on the other phone and still saw the same behaviors.

The phone with the app that doesn't work properly is my personal phone, the other is a work phone.


问:
Unit test: How to mock mongoose code when using populate?
I have a mongoose model with a static function that finds an employee document by ID and populates referenced manager and interviewer fields.

```<code>employeeSchema.statics.findAndPopulateById = function(id) {
  return this.findById(id)
    .populate("manager", "firstname lastname email")
    .populate("interviewer", "email")
    .then(employee => {
      if (!employee) {
        throw new errors.NotFoundError();
      }
      return employee;
    });
}
</code>```

I understand how to test this function when it doesn't contain the populate chain, but the populate part is throwing me for a loop.

Specifically, I am trying to test that the NotFoundError exception is thrown when no matching record is found, but I am confused how to mock the findById method so that .populate() can be called on the return value.

If I were testing this method without the .populate() chain, I would do something like

```<code>let findByIdMock = sandbox.stub(Employee, 'findById');
findByIdMock.resolves(null);

return expect(Employee.findAndPopulateById('123')).to.be.rejectedWith(errors.NotFoundError);
</code>```

But this approach, of course, doesn't work when populate is involved. I think I should be returning a mocked query or something similar, but I also need to be able to call populate again on that mock or resolve it as a promise.

How do I write a test for this code? Should my function be structured differently?

答:
Alright this ended up being easier than I anticipated, I just needed to add a call to .exec() between my final .populate() and .then() to make the test below work.

```<code>it("should throw not found exception if employee doesn't exist", () => {
  const mockQuery = {
    exec: sinon.stub().resolves(null)
  }
  mockQuery.populate = sinon.stub().returns(mockQuery);

  let findById = sandbox.stub(Employee, 'findById');
  findById.withArgs(mockId).returns(mockQuery);

  return expect(Employee.findAndPopulateById(mockId)).to.be.rejectedWith(errors.NotFoundError);
});
</code>```

Body:
I have a mongoose model with a static function that finds an employee document by ID and populates referenced manager and interviewer fields.

employeeSchema.statics.findAndPopulateById = function(id) {
  return this.findById(id)
    .populate("manager", "firstname lastname email")
    .populate("interviewer", "email")
    .then(employee => {
      if (!employee) {
        throw new errors.NotFoundError();
      }
      return employee;
    });
}

I understand how to test this function when it doesn't contain the populate chain, but the populate part is throwing me for a loop.

Specifically, I am trying to test that the NotFoundError exception is thrown when no matching record is found, but I am confused how to mock the findById method so that .populate() can be called on the return value.

If I were testing this method without the .populate() chain, I would do something like

let findByIdMock = sandbox.stub(Employee, 'findById');
findByIdMock.resolves(null);

return expect(Employee.findAndPopulateById('123')).to.be.rejectedWith(errors.NotFoundError);

But this approach, of course, doesn't work when populate is involved. I think I should be returning a mocked query or something similar, but I also need to be able to call populate again on that mock or resolve it as a promise.

How do I write a test for this code? Should my function be structured differently?

Body:
Alright this ended up being easier than I anticipated, I just needed to add a call to .exec() between my final .populate() and .then() to make the test below work.

it("should throw not found exception if employee doesn't exist", () => {
  const mockQuery = {
    exec: sinon.stub().resolves(null)
  }
  mockQuery.populate = sinon.stub().returns(mockQuery);

  let findById = sandbox.stub(Employee, 'findById');
  findById.withArgs(mockId).returns(mockQuery);

  return expect(Employee.findAndPopulateById(mockId)).to.be.rejectedWith(errors.NotFoundError);
});


问:
Remove duplicates from ArrayLists
I have an ArrayList of custom objects. I want to remove duplicate entries.

The objects have three fields: title, subtitle, and id. If a subtitle occurs multiple times, I only need the first item with thats subtitle (ignore the remaining object with that subtitle).

答:
Update for Java8:

Using Java8 streams you can also do pretty trivally.

```<code>ArrayList<String> deduped;
deduped = yourArrayList.stream()
             .distinct()
             .collect(Collectors.toCollection(ArrayList::new));
</code>```

This also has the advantage over going ArrayList  → Set   → ArrayList     of maintaining ordering.

Title: Remove duplicates from ArrayLists

Body:
Update for Java8:

Using Java8 streams you can also do pretty trivally.

ArrayList<String> deduped;
deduped = yourArrayList.stream()
             .distinct()
             .collect(Collectors.toCollection(ArrayList::new));

This also has the advantage over going ArrayList  → Set   → ArrayList     of maintaining ordering.


问:
For-Loop read and save multiple .xlsx files to one file
I am looping through multiple files where each file creates a table. I would like to save each table to a file so that I have all of the tables together. The idea is that after each file runs, the final output will append to the previous final output in a table. My current code loops through each file but only takes the data from the last file in the folder and repeatedly appends to the same output. Here is my code:

```<code>filenames <- Sys.glob("*.xlsx")
print(filenames)

final.df<-data.table()
for(i in 1:length(filenames)) {
   #... final table named "Stats"

   Stats$file <- i   #To view which file is listed
   df <- data.table(Stats)
   final.df <- rbind(final.df, df)
   drop(df)
}
</code>```

When I run the code, the file names are printed 26 times in this format:

```<code>[1] "file1.xlsx"          "file2.xlsx"
[1] "file1.xlsx"          "file2.xlsx"
[1] "file1.xlsx"          "file2.xlsx"
...
</code>```

My current output prints in this format:

```<code>X        Y        Z       File
1        10       2       file2
2        6        2       file2
1        9        2       file2
1        10       2       file2
2        6        2       file2
1        9        2       file2
</code>```

My desired output would look like the following:

```<code>X        Y        Z       File
0        4        1       file1
1        7        1       file1
0        1        1       file1
1        10       2       file2
2        6        2       file2
1        9        2       file2
</code>```

SOLUTION

```<code>files <- list.files(pattern = "\\.xlsx$")
print(files)

final.df<-list()

for(title in c(paste(files, sep="."))) {
   #... (Some data named Stats)
   Stats<-data.table(Stats)
   final.df[[title]] <- Stats
   print(final.df)
 }
 Final <- rbindlist(final.df)
</code>```

答:
Without your data, I think this should work:

```<code>listOut <- list()
for(i in 1:length(filenames)) {
  df <- data.table(filenames[i])
  listOut[[i]] <- df
}

dfFinal <- rbindlist(listOut)
</code>```

The idea is to make a dataframe and append it to a list for each of your files.  Then you can rbind all of the list elements together.  This is much more efficient than trying to append to an existing dataframe.

Body:
I am looping through multiple files where each file creates a table. I would like to save each table to a file so that I have all of the tables together. The idea is that after each file runs, the final output will append to the previous final output in a table. My current code loops through each file but only takes the data from the last file in the folder and repeatedly appends to the same output. Here is my code:

filenames <- Sys.glob("*.xlsx")
print(filenames)

final.df<-data.table()
for(i in 1:length(filenames)) {
   #... final table named "Stats"

   Stats$file <- i   #To view which file is listed
   df <- data.table(Stats)
   final.df <- rbind(final.df, df)
   drop(df)
}

When I run the code, the file names are printed 26 times in this format:

[1] "file1.xlsx"          "file2.xlsx"
[1] "file1.xlsx"          "file2.xlsx"
[1] "file1.xlsx"          "file2.xlsx"
...

My current output prints in this format:

X        Y        Z       File
1        10       2       file2
2        6        2       file2
1        9        2       file2
1        10       2       file2
2        6        2       file2
1        9        2       file2

My desired output would look like the following:

X        Y        Z       File
0        4        1       file1
1        7        1       file1
0        1        1       file1
1        10       2       file2
2        6        2       file2
1        9        2       file2

SOLUTION

files <- list.files(pattern = "\\.xlsx$")
print(files)

final.df<-list()

for(title in c(paste(files, sep="."))) {
   #... (Some data named Stats)
   Stats<-data.table(Stats)
   final.df[[title]] <- Stats
   print(final.df)
 }
 Final <- rbindlist(final.df)

Body:
Without your data, I think this should work:

listOut <- list()
for(i in 1:length(filenames)) {
  df <- data.table(filenames[i])
  listOut[[i]] <- df
}

dfFinal <- rbindlist(listOut)

The idea is to make a dataframe and append it to a list for each of your files.  Then you can rbind all of the list elements together.  This is much more efficient than trying to append to an existing dataframe.


问:
Retrieve MSSQL datetime2(7) value as Python datetime with microseconds rounded instead of truncated
If I do a CAST in T-SQL, 0397 is rounded to 040 with proper rounding, but pyodbc truncates it to 039. How can I easily do this rounding like SQL Server does it?

```<code>1> select logid, timestamputc from eventlog where logid=166944;
2> go
logid                timestamputc
-------------------- --------------------------------------
              166944            2017-05-30 08:59:37.6650397

1> select logid from eventlog
where cast(timestamputc as datetime2(6))='2017-05-30 08:59:37.665039';
2> go
logid
--------------------
(0 rows affected)

1> select logid from eventlog
where cast(timestamputc as datetime2(6))='2017-05-30 08:59:37.665040';
2> go
logid
--------------------
              166944
</code>```

with pyodbc:

```<code>[{'logid': 166944, 'timestamputc': '2017-05-30 08:59:37.665039'}]
</code>```

答:
As you've discovered, when pyodbc retrieves a datetime2(7) column as a Python datetime object its default behaviour is to truncate the seventh decimal place. If you want the datetime object to be rounded, as SQL Server would return a datetime2(7) value CAST to datetime2(6), then you can use an output converter function.

For example, if you define your output converter function as

def handle_datetime2(dt2_value):
    tup = struct.unpack("<6hI", dt2_value)  # e.g., (2017, 5, 30, 8, 59, 37, 0, 665039700)
    return datetime(tup[0], tup[1], tup[2],
                    hour=tup[3], minute=tup[4], second=tup[5],
                    microsecond=math.floor(tup[6] / 1000.0 + 0.5))
```

<p>and use it like this</p>

<pre class="lang-python prettyprint-override"><code>cnxn = pyodbc.connect(conn_str, autocommit=True)
crsr = cnxn.cursor()

cnxn.add_output_converter(pyodbc.SQL_TYPE_TIMESTAMP, handle_datetime2)

dt_string = '2017-05-30 08:59:37.6650397'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')

dt_string = '2017-05-30 08:59:37.6650395'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')

dt_string = '2017-05-30 08:59:37.6650394'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')
</code>```

the results will look like this

2017-05-30 08:59:37.6650397
 -> datetime.datetime(2017, 5, 30, 8, 59, 37, 665040)
2017-05-30 08:59:37.6650395
 -> datetime.datetime(2017, 5, 30, 8, 59, 37, 665040)
2017-05-30 08:59:37.6650394
 -> datetime.datetime(2017, 5, 30, 8, 59, 37, 665039)
```

Body:
If I do a CAST in T-SQL, 0397 is rounded to 040 with proper rounding, but pyodbc truncates it to 039. How can I easily do this rounding like SQL Server does it?

1> select logid, timestamputc from eventlog where logid=166944;
2> go
logid                timestamputc
-------------------- --------------------------------------
              166944            2017-05-30 08:59:37.6650397

1> select logid from eventlog
where cast(timestamputc as datetime2(6))='2017-05-30 08:59:37.665039';
2> go
logid
--------------------
(0 rows affected)

1> select logid from eventlog
where cast(timestamputc as datetime2(6))='2017-05-30 08:59:37.665040';
2> go
logid
--------------------
              166944

with pyodbc:

[{'logid': 166944, 'timestamputc': '2017-05-30 08:59:37.665039'}]

Body:
As you've discovered, when pyodbc retrieves a datetime2(7) column as a Python datetime object its default behaviour is to truncate the seventh decimal place. If you want the datetime object to be rounded, as SQL Server would return a datetime2(7) value CAST to datetime2(6), then you can use an output converter function.

For example, if you define your output converter function as

def handle_datetime2(dt2_value):
    tup = struct.unpack("<6hI", dt2_value)  # e.g., (2017, 5, 30, 8, 59, 37, 0, 665039700)
    return datetime(tup[0], tup[1], tup[2],
                    hour=tup[3], minute=tup[4], second=tup[5],
                    microsecond=math.floor(tup[6] / 1000.0 + 0.5))

and use it like this

cnxn = pyodbc.connect(conn_str, autocommit=True)
crsr = cnxn.cursor()

cnxn.add_output_converter(pyodbc.SQL_TYPE_TIMESTAMP, handle_datetime2)

dt_string = '2017-05-30 08:59:37.6650397'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')

dt_string = '2017-05-30 08:59:37.6650395'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')

dt_string = '2017-05-30 08:59:37.6650394'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')

the results will look like this

2017-05-30 08:59:37.6650397
 -> datetime.datetime(2017, 5, 30, 8, 59, 37, 665040)
2017-05-30 08:59:37.6650395
 -> datetime.datetime(2017, 5, 30, 8, 59, 37, 665040)
2017-05-30 08:59:37.6650394
 -> datetime.datetime(2017, 5, 30, 8, 59, 37, 665039)


问:
determine the average time to look up a key in a randomly generated balanced binary search tree in C#?
I'm trying to determine the average amount of time it takes to loop up a key in a randomly generated balanced binary search tree, as a function of the size of the tree.. I'm unable to write the code to calculate the time.. so if i can get help or at least best way to write the code i would appreciate it... its been a while since i coded</p>

答:
```<code>var startTime = DateTime.Now;
fncYourFonction();
var stopTime = DateTime.Now;

var elapsedTime = stopTime - startTime;

 string time = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            elapsedTime .Hours, elapsedTime .Minutes, elapsedTime .Seconds,
            elapsedTime .Milliseconds / 10);
Console.WriteLine(time , "Elapsed Time");
</code>```

Just replace fncYourFonction and you're done. Almost the same thing as @Eric's tutorial.

Body:
var startTime = DateTime.Now;
fncYourFonction();
var stopTime = DateTime.Now;

var elapsedTime = stopTime - startTime;

 string time = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            elapsedTime .Hours, elapsedTime .Minutes, elapsedTime .Seconds,
            elapsedTime .Milliseconds / 10);
Console.WriteLine(time , "Elapsed Time");

Just replace fncYourFonction and you're done. Almost the same thing as @Eric's tutorial.


问:
Show another div when image is hovered over
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>

  <div class="castcontainer">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div class="castcontainer">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article></code>```

答:
```<code><article>

  <div class="castcontainer" id="show1">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" class="castImg" id="CastImgRef">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div class="castcontainer" id="show2">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" class="castImg">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article>

jQuery(function ($) {
    $('#show1').hover(function () {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace('https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg', 'http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg')
        })
        $('#textChange').text('Wade Wilson');
    }, function () {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace('http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg', 'https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg')
        })
        $('#textChange').text('Ryan Reynalds');
    })
})
</code>```

Add thisjquery and it will work fine

https://jsfiddle.net/dLwxm2ox/8/

Body:
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}

Ryan Reynalds

Wade Wilson

Body:
<article>

  <div class="castcontainer" id="show1">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" class="castImg" id="CastImgRef">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div class="castcontainer" id="show2">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" class="castImg">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article>

jQuery(function ($) {
    $('#show1').hover(function () {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace('https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg', 'http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg')
        })
        $('#textChange').text('Wade Wilson');
    }, function () {
        $(this).find('img').attr('src', function (i, src) {
            return src.replace('http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg', 'https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg')
        })
        $('#textChange').text('Ryan Reynalds');
    })
})

Add thisjquery and it will work fine

https://jsfiddle.net/dLwxm2ox/8/


问:
Recipe directions to array in PHP
I'm making a recipe site. In the database I have recipes directions saved. They all have some numbering like the example below. How can i get the recipe into array based on the numbers? I was thinking of using \n as a explode value, but I instead want to use the numbers (1. 2. 3. 4. 5. etc).

My code:

```<code><?php
$get_recipe_directions = "
1. Rinse the noodles, bla bla bla.
2. Spray a bla bla blabla bla blabla bla bla.
3. Add the shrimp, bla bla blabla bla blabla bla blabla bla blabla bla blabla bla blabla bla blabla bla bla.

Serve with jam and rice.";

// I need to explode the recipe directions to array based on
// the numbers
$array = explode("??", $get_recipe_directions);

for($x=0;$x<sizeof($array);$x++){
    echo"<li>$array[$x]</li>\n";
}
?>
</code>```

答:
try

```<code>$array= preg_split('/\d+\./', $get_recipe_directions);
</code>```

;-)

it's regex-based splitting of string.

see php "preg_split"

Title: Recipe directions to array in PHP

Body:
I'm making a recipe site. In the database I have recipes directions saved. They all have some numbering like the example below. How can i get the recipe into array based on the numbers? I was thinking of using \n as a explode value, but I instead want to use the numbers (1. 2. 3. 4. 5. etc).

My code:

<?php
$get_recipe_directions = "
1. Rinse the noodles, bla bla bla.
2. Spray a bla bla blabla bla blabla bla bla.
3. Add the shrimp, bla bla blabla bla blabla bla blabla bla blabla bla blabla bla blabla bla blabla bla bla.

Serve with jam and rice.";

// I need to explode the recipe directions to array based on
// the numbers
$array = explode("??", $get_recipe_directions);

for($x=0;$x<sizeof($array);$x++){
    echo"
$array[$x]
\n";
}
?>

Body:
try

$array= preg_split('/\d+\./', $get_recipe_directions);

;-)

it's regex-based splitting of string.

see php "preg_split"


问:
When changing the title of my activity from fragments cause crash
I have an activity with viewPager called WebActivity.The viewPager use instances of a webView Fragment(the fragment contains a webview inside it).I change the title of the WebActivity to "Loading.." from the fragments inside the viewPager to indicate the webView is loading.It does not cause any problem but when i move through the pages a lot i get a crash with logs as shown below:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.setTitle(java.lang.CharSequence)' on a null object reference
  at com.example.android.gametalks.Fragments.WebViewFragment$1.onPageFinished(WebViewFragment.java:91)
  at com.android.webview.chromium.WebViewContentsClientAdapter.onPageFinished(WebViewContentsClientAdapter.java:199)
  at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:72)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:168)
  at android.app.ActivityThread.main(ActivityThread.java:5885)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
</code>```

Here is my fragment(Relevant part):

```<code>public class WebViewFragment extends Fragment {

    WebView mWebView;
    String currentUrl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        currentUrl = getArguments().getString("currentUrl");
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView =  inflater.inflate(R.layout.webview_fragment, container, false);
return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getActivity().setTitle("Web View");

        setRetainInstance(true);
        mWebView = (WebView) view.findViewById(R.id.webvieww);

        mWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                getActivity().setTitle("Loading...");
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
                getActivity().setTitle("Web View");
            }
        });

        if (savedInstanceState == null)
        {
            mWebView.loadUrl(currentUrl);
        }

    }
</code>```

答:
Short answer: check if getActivity() is returning null because accessing it.

```<code>if(getActivity() != null) {
    getActivity().setTitle("New title");
}
</code>```

Long answer: it's best to use some sort of listener to notify the Activity of a change within the fragment rather than directly using getActivity(). The Google Developer docs have a pretty good walkthrough of how to accomplish this using an interface.

Body:
I have an activity with viewPager called WebActivity.The viewPager use instances of a webView Fragment(the fragment contains a webview inside it).I change the title of the WebActivity to "Loading.." from the fragments inside the viewPager to indicate the webView is loading.It does not cause any problem but when i move through the pages a lot i get a crash with logs as shown below:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.setTitle(java.lang.CharSequence)' on a null object reference
  at com.example.android.gametalks.Fragments.WebViewFragment$1.onPageFinished(WebViewFragment.java:91)
  at com.android.webview.chromium.WebViewContentsClientAdapter.onPageFinished(WebViewContentsClientAdapter.java:199)
  at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:72)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:168)
  at android.app.ActivityThread.main(ActivityThread.java:5885)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

Here is my fragment(Relevant part):

public class WebViewFragment extends Fragment {

    WebView mWebView;
    String currentUrl;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        currentUrl = getArguments().getString("currentUrl");
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView =  inflater.inflate(R.layout.webview_fragment, container, false);
return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getActivity().setTitle("Web View");

        setRetainInstance(true);
        mWebView = (WebView) view.findViewById(R.id.webvieww);

        mWebView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                getActivity().setTitle("Loading...");
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
                getActivity().setTitle("Web View");
            }
        });

        if (savedInstanceState == null)
        {
            mWebView.loadUrl(currentUrl);
        }

    }

Body:
Short answer: check if getActivity() is returning null because accessing it.

if(getActivity() != null) {
    getActivity().setTitle("New title");
}

Long answer: it's best to use some sort of listener to notify the Activity of a change within the fragment rather than directly using getActivity(). The Google Developer docs have a pretty good walkthrough of how to accomplish this using an interface.


问:
Joomla JSON.parse: unexpected non-whitespace character after JSON data
I want to use jQuery.ajax for sending new mark(about article) to database and changind number of marks on page.
But I receive bad AJAX response from server.

```<code>{"likes":"40","dislikes":"29"}{"success":true,"message":null,"messages":null,"data":[]}
</code>```

and error:

SyntaxError: JSON.parse: unexpected non-whitespace character after
  JSON data at line 1 column 31 of the JSON data

It seems there must not be the second ajax response. But I'm not understand where it have taken.

That is my php code from Joomla plugin.

```<code>$marks = plgContentLikesHelper::getMarks($articleID);
        $data=array();
        $data['likes'] = $marks->likes;
        $data['dislikes'] = $marks->dislikes;
        echo json_encode($data);
</code>```

That is my jQuery code from Joomla plugin.

```<code>jQuery(document).ready(function(){

            jQuery('div.plg-likes > a ').click(function (e) {
                var id = jQuery(this).parent('div.plg-likes').attr('id');
                var opinion = jQuery(this).attr('id');

                jQuery.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "index.php?option=com_ajax&group=content&plugin=likes&format=json",
                    data: { articleId: id, articleOpinion: opinion },
                    success: function(data){  /* troubles are here */
                            alert(data["likes"]);
                    }
                })
                return false;
            })
        })
</code>```

答:
The answer is in the next simple code after response for page:

die();

```<code>$db->setQuery($query);
$db->execute();
$marks = plgContentLikesHelper::getMarks($articleID);
$data=array();
$data['likes'] = $marks->likes;
$data['dislikes'] = $marks->dislikes;
echo json_encode($data);
die();
</code>```

Thank you!

Body:
I want to use jQuery.ajax for sending new mark(about article) to database and changind number of marks on page.
But I receive bad AJAX response from server.

{"likes":"40","dislikes":"29"}{"success":true,"message":null,"messages":null,"data":[]}

and error:

SyntaxError: JSON.parse: unexpected non-whitespace character after
  JSON data at line 1 column 31 of the JSON data

It seems there must not be the second ajax response. But I'm not understand where it have taken.

That is my php code from Joomla plugin.

$marks = plgContentLikesHelper::getMarks($articleID);
        $data=array();
        $data['likes'] = $marks->likes;
        $data['dislikes'] = $marks->dislikes;
        echo json_encode($data);

That is my jQuery code from Joomla plugin.

jQuery(document).ready(function(){

            jQuery('div.plg-likes > a ').click(function (e) {
                var id = jQuery(this).parent('div.plg-likes').attr('id');
                var opinion = jQuery(this).attr('id');

                jQuery.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "index.php?option=com_ajax&group=content&plugin=likes&format=json",
                    data: { articleId: id, articleOpinion: opinion },
                    success: function(data){  /* troubles are here */
                            alert(data["likes"]);
                    }
                })
                return false;
            })
        })

Body:
The answer is in the next simple code after response for page:

die();

$db->setQuery($query);
$db->execute();
$marks = plgContentLikesHelper::getMarks($articleID);
$data=array();
$data['likes'] = $marks->likes;
$data['dislikes'] = $marks->dislikes;
echo json_encode($data);
die();

Thank you!


问:
Modify Global Variable Inside Closure (Swift 4)
I am trying to modify the global variable currentWeather (of type CurrentWeather) using this function, which is meant to update said variable with the information retrieved from the URL and return a bool signifying its success. However, the function is returning false, as currentWeather is still nil. I recognize that the dataTask is asynchronous, and that the task is running in the background parallel to the application, but I don't understand what this means for what I'm trying to accomplish. I also am unable to update currentWeather after the do block, as weather is no longer recognized after exiting the block. I did try using "self.currentWeather", but was told it was an unresolved identifier (perhaps because the function is also global, and there is no "self"?).

The URL is not currently valid because I took out my API key, but it is working as expected otherwise, and my CurrentWeather struct is Decodable. Printing currentWeatherUnwrapped is also consistently successful.

I did look around Stack Overflow and through Apple's official documentation and was unable to find something that answered my question, but perhaps I wasn't thorough enough. I'm sorry if this is a duplicate question. Direction to any further relevant reading is also appreciated! I apologize for the lack of conformity to best coding practices - I'm not very experienced at this point. Thank you all so much!

```<code>func getCurrentWeather () -> Bool {
let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

guard let url = URL(string: jsonUrlString) else { return false }

URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

    guard let data = data else { return }

    do {
        let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
        currentWeather = weather
        if let currentWeatherUnwrapped = currentWeather {
            print(currentWeatherUnwrapped)
        }
    } catch let jsonErr {
        print("Error serializing JSON: ", jsonErr)
    }

    // cannot update currentWeather here, as weather is local to do block

    }.resume()

return currentWeather != nil
}
</code>```

答:
As you pointed out, the data ask is async, meaning you do not know when it will be completed.

One option is to modify your wrapper function getCurrentWeather to be async as well by not providing a return value, but instead a callback/closure. Then you will have to deal with the async nature somewhere else though.

The other option which is what you probably want in your scenario is to make the data task synchronous like so:

```<code>func getCurrentWeather () -> Bool {
    let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

    guard let url = URL(string: jsonUrlString) else { return false }

    let dispatchGroup = DispatchGroup() // <===
    dispatchGroup.enter() // <===

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        // check error/response

        guard let data = data else {
            dispatchGroup.leave() // <===
            return
        }

        do {
            let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
            currentWeather = weather
            if let currentWeatherUnwrapped = currentWeather {
                print(currentWeatherUnwrapped)
            }
            dispatchGroup.leave() // <===
       } catch let jsonErr {
           print("Error serializing JSON: ", jsonErr)
           dispatchGroup.leave() // <===
       }
       // cannot update currentWeather here, as weather is local to do block

    }.resume()

    dispatchGroup.wait() // <===

    return currentWeather != nil
}
</code>```

The wait function can take parameters, which can define a timeout. https://developer.apple.com/documentation/dispatch/dispatchgroup Otherwise your app could be stuck waiting forever. You will then be able to define some action to present that to the user.

Btw I made a fully functional weather app just for learning, so check it out here on GitHub https://github.com/erikmartens/NearbyWeather. Hope the code there can help you for your project. It's also available on the app store.

EDIT: Please understand that this answer is meant to show how to make async calls synchronous. I am not saying this is good practice for handling network calls. This is a hacky solution for when you absolutely must have a return value from a function even though it uses async calls inside.

Body:
I am trying to modify the global variable currentWeather (of type CurrentWeather) using this function, which is meant to update said variable with the information retrieved from the URL and return a bool signifying its success. However, the function is returning false, as currentWeather is still nil. I recognize that the dataTask is asynchronous, and that the task is running in the background parallel to the application, but I don't understand what this means for what I'm trying to accomplish. I also am unable to update currentWeather after the do block, as weather is no longer recognized after exiting the block. I did try using "self.currentWeather", but was told it was an unresolved identifier (perhaps because the function is also global, and there is no "self"?).

The URL is not currently valid because I took out my API key, but it is working as expected otherwise, and my CurrentWeather struct is Decodable. Printing currentWeatherUnwrapped is also consistently successful.

I did look around Stack Overflow and through Apple's official documentation and was unable to find something that answered my question, but perhaps I wasn't thorough enough. I'm sorry if this is a duplicate question. Direction to any further relevant reading is also appreciated! I apologize for the lack of conformity to best coding practices - I'm not very experienced at this point. Thank you all so much!

func getCurrentWeather () -> Bool {
let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

guard let url = URL(string: jsonUrlString) else { return false }

URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

    guard let data = data else { return }

    do {
        let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
        currentWeather = weather
        if let currentWeatherUnwrapped = currentWeather {
            print(currentWeatherUnwrapped)
        }
    } catch let jsonErr {
        print("Error serializing JSON: ", jsonErr)
    }

    // cannot update currentWeather here, as weather is local to do block

    }.resume()

return currentWeather != nil
}

Body:
As you pointed out, the data ask is async, meaning you do not know when it will be completed.

One option is to modify your wrapper function getCurrentWeather to be async as well by not providing a return value, but instead a callback/closure. Then you will have to deal with the async nature somewhere else though.

The other option which is what you probably want in your scenario is to make the data task synchronous like so:

func getCurrentWeather () -> Bool {
    let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

    guard let url = URL(string: jsonUrlString) else { return false }

    let dispatchGroup = DispatchGroup() // <===
    dispatchGroup.enter() // <===

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        // check error/response

        guard let data = data else {
            dispatchGroup.leave() // <===
            return
        }

        do {
            let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
            currentWeather = weather
            if let currentWeatherUnwrapped = currentWeather {
                print(currentWeatherUnwrapped)
            }
            dispatchGroup.leave() // <===
       } catch let jsonErr {
           print("Error serializing JSON: ", jsonErr)
           dispatchGroup.leave() // <===
       }
       // cannot update currentWeather here, as weather is local to do block

    }.resume()

    dispatchGroup.wait() // <===

    return currentWeather != nil
}

The wait function can take parameters, which can define a timeout. https://developer.apple.com/documentation/dispatch/dispatchgroup Otherwise your app could be stuck waiting forever. You will then be able to define some action to present that to the user.

Btw I made a fully functional weather app just for learning, so check it out here on GitHub https://github.com/erikmartens/NearbyWeather. Hope the code there can help you for your project. It's also available on the app store.

EDIT: Please understand that this answer is meant to show how to make async calls synchronous. I am not saying this is good practice for handling network calls. This is a hacky solution for when you absolutely must have a return value from a function even though it uses async calls inside.


问:
React or express routing with React templating and ExpressJS backend?
I was wondering how to handle a react front-end working with ExpressJS backend. I am searching for good tutorial, but I do not find anything relevant which explain really well the difference between React-Routing (front-side ?) and Express-Routing (back !).

I have an application in react (create with create-app-react), I have some components, a routing with switch, etc. and it works well, I try to run that with Express and I figured out how to do that:

```<code>// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
</code>```

But right now, I am wondering how can I implement middleware with all of this ? Is the react-routing a mandatory thing ? Can I only use the Express one ? Or maybe a combo (to get some middleware...).

Sorry if it is not really clear, but I am searching for some ressource which can explain everything.

答: You don't need to implement anything other than a catch all route in express like you did already. You can use react-router alone to handle routing on the client side.</p>

Body:
I was wondering how to handle a react front-end working with ExpressJS backend. I am searching for good tutorial, but I do not find anything relevant which explain really well the difference between React-Routing (front-side ?) and Express-Routing (back !).

I have an application in react (create with create-app-react), I have some components, a routing with switch, etc. and it works well, I try to run that with Express and I figured out how to do that:

// Always return the main index.html, so react-router render the route in the client
app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});

But right now, I am wondering how can I implement middleware with all of this ? Is the react-routing a mandatory thing ? Can I only use the Express one ? Or maybe a combo (to get some middleware...).

Sorry if it is not really clear, but I am searching for some ressource which can explain everything.