问:
How to compare Double Array Set
Hi, I would really appreciate the help for this lab. I don't understand what I did wrong; for example, I don't understand the program errors displayed.

5.13 Lab 5b

Objectives

In this lab you will practice using for loops with arrays and comparing double values, using a threshold, to see if two sets of numbers are the same.

Background Reading

ZyBooks Chapter 5

Task

The first comment of your main method should be your identification comment:

```<code>//Lab5b, [Name], [mascID]
</code>```

You will need to then:

Create and populate the two sets of double values, in which the number of elements and the elements themselves are specified by the user. (i.e. the user will state how many numbers are in the first set, give the values for that set and then move on to the second set of numbers).

Iterate through the sets and compare the values. For the purposes of this lab, we will say that the order matters in determining if the sets are the same. (HINT: This also means that the lengths of the arrays must be the same).

If the arrays are the same in both length and values, print set one and set two are equal. Otherwise, print set one and set two are not equal

Comparing double values using a threshold

Recall that floating-point numbers may differ in a very small value. For example, 1.0 might actually be stored as 0.9999999... or 1.0000000002.

When comparing these values, we often use a "tolerance" level that says, "if the difference is smaller than some amount, then it is negligible and the numbers can be thought of as the same." We can achieve this by comparing the absolute value of the difference of the elements to the tolerance. For example,

```<code>if ( Math.abs( array1[0] - array2[0] ) > 0.001 ) )
    System.out.println("The values of array1[0] and array2[0] are not equal");
</code>```

Code:

import java.lang.Math;
import java.util.Scanner;

public class SetComparison {
   public static void main (String [] args) {

      Scanner scnr = new Scanner(System.in);

      int array1Elems = 0;
      int array2Elems = 0;
      int i = 0;
      int j = 0;

      array1Elems = scnr.nextInt();
      array2Elems = scnr.nextInt();

      double array1[] = new double[array1Elems];
      double array2[] = new double[array2Elems];

      for (i = 0; i < array1Elems; ++i) {
         array1[i] = scnr.nextInt;
         for (j = 0; j < array2Elems; ++j) {
            array2[j] = scnr.nextInt;
         }
         if (Math.abs(array1[i] - array2[j]) > 0.001) {
            System.out.println("set one and set two are not equal");
         }
         else if (Math.abs(array1[i] - array2[j]) < 0.001) {
            System.out.println("set one and set two are equal");
         }
      }
   }
}```

Enter program input

6
  45.24 54.67 42.55 44.61 65.29 49.75 6
  45.24 54.67 42.55 44.61 65.29 49.75

Program errors displayed here SetComparison.java:23: error: cannot
  find symbol
           array1[i] = scnr.nextInt;
                           ^   symbol:   variable nextInt   location: variable scnr of type Scanner SetComparison.java:25: error: cannot
  find symbol
              array2[j] = scnr.nextInt;
                              ^   symbol:   variable nextInt   location: variable scnr of type Scanner 2 errors

答:
Try this answer I think this will help you...</p>

```<code>import java.lang.Math;
import java.util.Scanner;

public class SetComparison {
   public static void main (String [] args) {
      Scanner scnr = new Scanner(System.in);

      int array1Elems = 0;
      int array2Elems = 0;
      int i = 0;
      int j = 0;

      array1Elems = scnr.nextInt();
      array2Elems = scnr.nextInt();

      double array1[] = new double[array1Elems];
      double array2[] = new double[array2Elems];

      for (i = 0; i < array1Elems; ++i) {
         array1[i] = scnr.nextInt();
      }
      for (j = 0; j < array2Elems; ++j) {
         array2[j] = scnr.nextInt();
      }
      for (i = 0; i < array1Elems; ++i) {
         for (j = 0; j < array2Elems; ++j) {
            if (Math.abs(array1[i] - array2[j]) > 0.001) {
               System.out.println("set one and set two are not equal");
            } else if (Math.abs(array1[i] - array2[j]) < 0.001) {
               System.out.println("set one and set two are equal");
            }
         }
      }
   }
}
</code>```

Title: How to compare Double Array Set

Body:
Hi, I would really appreciate the help for this lab. I don't understand what I did wrong; for example, I don't understand the program errors displayed.

5.13 Lab 5b

Objectives

In this lab you will practice using for loops with arrays and comparing double values, using a threshold, to see if two sets of numbers are the same.

Background Reading

ZyBooks Chapter 5

Task

The first comment of your main method should be your identification comment:

//Lab5b, [Name], [mascID]

You will need to then:

Create and populate the two sets of double values, in which the number of elements and the elements themselves are specified by the user. (i.e. the user will state how many numbers are in the first set, give the values for that set and then move on to the second set of numbers).

Iterate through the sets and compare the values. For the purposes of this lab, we will say that the order matters in determining if the sets are the same. (HINT: This also means that the lengths of the arrays must be the same).

If the arrays are the same in both length and values, print set one and set two are equal. Otherwise, print set one and set two are not equal

Comparing double values using a threshold

Recall that floating-point numbers may differ in a very small value. For example, 1.0 might actually be stored as 0.9999999... or 1.0000000002.

When comparing these values, we often use a "tolerance" level that says, "if the difference is smaller than some amount, then it is negligible and the numbers can be thought of as the same." We can achieve this by comparing the absolute value of the difference of the elements to the tolerance. For example,

if ( Math.abs( array1[0] - array2[0] ) > 0.001 ) )
    System.out.println("The values of array1[0] and array2[0] are not equal");

Code:

import java.lang.Math;
import java.util.Scanner;

public class SetComparison {
   public static void main (String [] args) {

      Scanner scnr = new Scanner(System.in);

      int array1Elems = 0;
      int array2Elems = 0;
      int i = 0;
      int j = 0;

      array1Elems = scnr.nextInt();
      array2Elems = scnr.nextInt();

      double array1[] = new double[array1Elems];
      double array2[] = new double[array2Elems];

      for (i = 0; i < array1Elems; ++i) {
         array1[i] = scnr.nextInt;
         for (j = 0; j < array2Elems; ++j) {
            array2[j] = scnr.nextInt;
         }
         if (Math.abs(array1[i] - array2[j]) > 0.001) {
            System.out.println("set one and set two are not equal");
         }
         else if (Math.abs(array1[i] - array2[j]) < 0.001) {
            System.out.println("set one and set two are equal");
         }
      }
   }
}

Enter program input

6
  45.24 54.67 42.55 44.61 65.29 49.75 6
  45.24 54.67 42.55 44.61 65.29 49.75

Program errors displayed here SetComparison.java:23: error: cannot
  find symbol
           array1[i] = scnr.nextInt;
                           ^   symbol:   variable nextInt   location: variable scnr of type Scanner SetComparison.java:25: error: cannot
  find symbol
              array2[j] = scnr.nextInt;
                              ^   symbol:   variable nextInt   location: variable scnr of type Scanner 2 errors

Body:
Try this answer I think this will help you...

import java.lang.Math;
import java.util.Scanner;

public class SetComparison {
   public static void main (String [] args) {
      Scanner scnr = new Scanner(System.in);

      int array1Elems = 0;
      int array2Elems = 0;
      int i = 0;
      int j = 0;

      array1Elems = scnr.nextInt();
      array2Elems = scnr.nextInt();

      double array1[] = new double[array1Elems];
      double array2[] = new double[array2Elems];

      for (i = 0; i < array1Elems; ++i) {
         array1[i] = scnr.nextInt();
      }
      for (j = 0; j < array2Elems; ++j) {
         array2[j] = scnr.nextInt();
      }
      for (i = 0; i < array1Elems; ++i) {
         for (j = 0; j < array2Elems; ++j) {
            if (Math.abs(array1[i] - array2[j]) > 0.001) {
               System.out.println("set one and set two are not equal");
            } else if (Math.abs(array1[i] - array2[j]) < 0.001) {
               System.out.println("set one and set two are equal");
            }
         }
      }
   }
}


来源: stackexchange

问:
Find elements by offset position with jQuery
Is there a simple method to fetch all elements at a specific offset position (by using jQuery)? Or do I have to check the offset of each element in the DOM?</p>

答: I think the only method would be to fetch all the elements. There are no other ways to retrieve a set of elements that are in a particular position</p>

ContentLicense: CC BY-SA 2.5


问:
NSPopover and adding spacing with NSStatusItem
I am working on a menubar app, that uses NSPopover. I am using the following code to present popover.

```<code>[self.mainPopover showRelativeToRect:[testView bounds] ofView:testView preferredEdge:NSMinYEdge];
</code>```

Issue is this is being present too close to status bar as shown below.

Even if i change the rect it does not have any effect and rightly so, as the documentation states

The rectangle within positioningView relative to which the popover should be positioned. Normally set to the bounds of positioningView. May be an empty rectangle, which will default to the bounds of positioningView.

Following is the screenshot from dropbox app, was just wondering how can i add some spacing in my app like dropbox.

答:
You could inset the test view bounds to add some margin between de view and popover:</p>

```<code>NSPopover *mainPopover = [self mainPopover];
NSRect bounds = CGRectInset([testView bounds], -50.0, -50.0);
[mainPopover showRelativeToRect:bounds ofView:testView preferredEdge:NSMinYEdge];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a menubar app, that uses NSPopover. I am using the following code to present popover.

[self.mainPopover showRelativeToRect:[testView bounds] ofView:testView preferredEdge:NSMinYEdge];

Issue is this is being present too close to status bar as shown below.

Even if i change the rect it does not have any effect and rightly so, as the documentation states

The rectangle within positioningView relative to which the popover should be positioned. Normally set to the bounds of positioningView. May be an empty rectangle, which will default to the bounds of positioningView.

Following is the screenshot from dropbox app, was just wondering how can i add some spacing in my app like dropbox.

Body:
You could inset the test view bounds to add some margin between de view and popover:

NSPopover *mainPopover = [self mainPopover];
NSRect bounds = CGRectInset([testView bounds], -50.0, -50.0);
[mainPopover showRelativeToRect:bounds ofView:testView preferredEdge:NSMinYEdge];


问:
JavaFX, container that can switch between two panes with transition effect
I am looking for a container in JavaFX for my Desktop Application that initially holds a listview with its width = parent's width and height as per the number of rows. Upon clicking, any of the rows (if any), the list shall hide itself with a transition effect and the container should show now a gridpane that now lists the detail of the row that was selected. If i go back(back button in gridpane), the previous listview shall become visible with a transition effect and the gridpane shall be hidden. I tried borderpane to hold both panes in its center and right but that did not go as planned. Please guide if there are any existing containers that JavaFx provides or any custom that are present on the internet. Thanks.</p>

答:
a code example of the gridpane might be very helpfull to help you.

Did you set the pane's percentages and widths? And did you use a cardlayout to switch between the listview and the selected item detail panel? The trouble is may be determing the listview width itself because the width of the listview depends on the items used inside the (scrollist) listView items


问:
linux curl redirection and authorization
i want access page require email and password so i did this command

```<code> curl -d 'email=myemail@gmail.com' -d 'password=mypass' -L https://dashboard.ngrok.com/get-started
</code>```

but it still gaves me gaves this message in command line :

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>CSRF token missing or incorrect.</p>
</code>```

so what should my  command to be

答:
The login page at https://dashboard.ngrok.com/get-started has an additional hidden input named csrf_token:

```<code><input name="csrf_token" value="1510745795.39##72db755c23c0d0bdf5e81bc77495f131d81a84b2" type="hidden">
</code>```

You would have to first open the page with the login form, parse out the token, and send it as additional post field. See also the question that @Aserre suggested as a duplicate.

Body:
i want access page require email and password so i did this command

 curl -d 'email=myemail@gmail.com' -d 'password=mypass' -L https://dashboard.ngrok.com/get-started

but it still gaves me gaves this message in command line :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>

Bad Request

CSRF token missing or incorrect.

so what should my  command to be

Body:
The login page at https://dashboard.ngrok.com/get-started has an additional hidden input named csrf_token:

<input name="csrf_token" value="1510745795.39##72db755c23c0d0bdf5e81bc77495f131d81a84b2" type="hidden">

You would have to first open the page with the login form, parse out the token, and send it as additional post field. See also the question that @Aserre suggested as a duplicate.


问:
Assign names of subfolders to corresponding images in an array
I have a root directory with many subfolders, each of them contains images. I want to load all of them to an array and assign to each image its subfolder name. Now I know how to load all images to an array of shape e.g. (10 000, 512, 512, 3), which means 10 000 images of the size 512x512 with 3 channels. After assigning the subfolder names I'd like to have a similar array, but I could say about each of the 10 000 images from which subfolder it is.

I'm trying to use os.walk. I know how to access all subfolders names and also image names, but I can't figure out how to put them together to one array.

```<code>import os
from scipy.misc import imread

images = []
for root, dirs, files in os.walk('.'):
    for name in dirs:
        print(name)

    for file in files:
        img = imread(os.path.join(root, file), mode='RGB')
        if img is not None:
            images.append(img)
</code>```

(Also it'd be great if the array didn't contain full strings of subfolder names, but just numbers (of classes/subfolders). I'm not sure if this can be done during this loading process or it'd be done after all images are loaded.)

答:
How about something like this?

```<code>import glob
import os
from scipy.misc import imread

images = {}

for file in glob.glob("./**/*.png", recursive=True):
    cwd = os.path.basename(os.path.dirname(file))
    img = imread(os.path.abspath(file), mode='RGB')
    if img is not None:
        if cwd not in images.keys():
            images[cwd] = {}
            images[cwd][file] = img
        else:
            images[cwd][file] = img

for key in images.keys():
    print("{:10s}{}".format(key, list(images[key].keys())))
</code>```

Here's an example directory structure:

```<code>.
├── f_one
│   └── one.png
├── f_two
│   ├── f_nested
│   │   └── nest.png
│   ├── three.png
│   └── two.png
├── out.txt
└── test.py

3 directories, 6 files
</code>```

and here's the output: (I didn't include the image data since the arrays are quite large)

```<code>f_two     ['./f_two/three.png', './f_two/two.png']
f_nested  ['./f_two/f_nested/nest.png']
f_one     ['./f_one/one.png']
</code>```

if you just use print(images) instead of the last loop you'll get something like this:

```<code>{'f_two': {'./f_two/three.png': array([[[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
</code>```

Some things to note about this solution:

Using dictionaries means keys have to be unique. If you have any folders with the same name, the last one to be read will be the only one present in the dict. The same goes for duplicate file names within the same directory. If you have non-unique directory or file names, try a different data structure or make sure keys are unique by using absolute paths.

Body:
I have a root directory with many subfolders, each of them contains images. I want to load all of them to an array and assign to each image its subfolder name. Now I know how to load all images to an array of shape e.g. (10 000, 512, 512, 3), which means 10 000 images of the size 512x512 with 3 channels. After assigning the subfolder names I'd like to have a similar array, but I could say about each of the 10 000 images from which subfolder it is.

I'm trying to use os.walk. I know how to access all subfolders names and also image names, but I can't figure out how to put them together to one array.

import os
from scipy.misc import imread

images = []
for root, dirs, files in os.walk('.'):
    for name in dirs:
        print(name)

    for file in files:
        img = imread(os.path.join(root, file), mode='RGB')
        if img is not None:
            images.append(img)

(Also it'd be great if the array didn't contain full strings of subfolder names, but just numbers (of classes/subfolders). I'm not sure if this can be done during this loading process or it'd be done after all images are loaded.)

Body:
How about something like this?

import glob
import os
from scipy.misc import imread

images = {}

for file in glob.glob("./**/*.png", recursive=True):
    cwd = os.path.basename(os.path.dirname(file))
    img = imread(os.path.abspath(file), mode='RGB')
    if img is not None:
        if cwd not in images.keys():
            images[cwd] = {}
            images[cwd][file] = img
        else:
            images[cwd][file] = img

for key in images.keys():
    print("{:10s}{}".format(key, list(images[key].keys())))

Here's an example directory structure:

.
├── f_one
│   └── one.png
├── f_two
│   ├── f_nested
│   │   └── nest.png
│   ├── three.png
│   └── two.png
├── out.txt
└── test.py

3 directories, 6 files

and here's the output: (I didn't include the image data since the arrays are quite large)

f_two     ['./f_two/three.png', './f_two/two.png']
f_nested  ['./f_two/f_nested/nest.png']
f_one     ['./f_one/one.png']

if you just use print(images) instead of the last loop you'll get something like this:

{'f_two': {'./f_two/three.png': array([[[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,

Some things to note about this solution:

Using dictionaries means keys have to be unique. If you have any folders with the same name, the last one to be read will be the only one present in the dict. The same goes for duplicate file names within the same directory. If you have non-unique directory or file names, try a different data structure or make sure keys are unique by using absolute paths.


问:
How to get the MSE of each pixel in two images of the same dimension
I have two images that will be identical in dimensions.

The images are numpy arrays and I am itterating the pixels and aquiring the r g b of each pixel like this:

```<code>for i in range(len(img1)):
    for j in range(len(img1[0])):
        pimg1 = img1[i][j]
        pimg2 = img2[i][j]

        r1 = pimg1[0]
        r2 = pimg2[0]
        g1 = pimg1[1]
        g2 = pimg2[1]
        b1 = pimg1[2]
        b2 = pimg2[2]
</code>```

I then acquire the MSE between the two pixels like:

```<code>mse = math.sqrt(((r1 - r2) ** 2) + ((g1 - g2) ** 2) + ((b1 - b2) ** 2))
</code>```

The problem is this is ridiculously slow. Is there a more efficient way to do this?

The final goal

I am looking to make all pixels that have a certain "thresholded" similarity, between the two images, black. And all pixels that have a larger difference the pixel of img2.

```<code>if mse > threshold:
    new_img[i][j] = pimg2
else:
    new_img[i][j] = [0, 0, 0] # black pixel
</code>```

background image

entered image

I am capturing images like:

```<code>for frame in cam.camera.capture_continuous(raw, format="rgb", use_video_port=True):
    img = frame.array
    cv2.imwrite("image.png", img)
</code>```

I am getting the images like:

```<code>dir = 'images/compare/'
bg = cv2.imread(dir+'bg.png')
img = cv2.imread(dir+'in.png')
</code>```

答:
Simply use np.linalg.norm on the differences -

```<code>mse = np.linalg.norm(img1-img2,axis=2)
</code>```

Faster one with np.einsum -

```<code>d = (img1-img2).astype(float)
mse = np.sqrt(np.einsum('...i,...i->...',d,d))
</code>```

Runtime test -

```<code>In [46]: np.random.seed(0)
    ...: m,n = 1024,1024
    ...: img1 = np.random.randint(0,255,(m,n,3)).astype(np.uint8)
    ...: img2 = np.random.randint(0,255,(m,n,3)).astype(np.uint8)

In [47]: %timeit np.linalg.norm(img1-img2,axis=2)
10 loops, best of 3: 26.6 ms per loop

In [49]: %%timeit
    ...: d = (img1-img2).astype(float)
    ...: mse = np.sqrt(np.einsum('...i,...i->...',d,d))
100 loops, best of 3: 13 ms per loop
</code>```

To create an output array that is set to black for pixels that have MSE values lesser than a certain threshold mse_thresh and select from img2 otherwise, here are the additional codes -

```<code>mask = mse >= mse_thresh
out = np.where(mask[...,None], img2, 0)
</code>```

Stitching everything together - Using einsum to compute squared MSE values and comparing against the squared MSE threshold for major improvement and assigning back the output into img2 -

```<code>d = (img1-img2).astype(float)
mse = np.einsum('...i,...i->...',d,d)
img2[mse < mse_thresh**2] = 0
</code>```

Body:
I have two images that will be identical in dimensions.

The images are numpy arrays and I am itterating the pixels and aquiring the r g b of each pixel like this:

for i in range(len(img1)):
    for j in range(len(img1[0])):
        pimg1 = img1[i][j]
        pimg2 = img2[i][j]

        r1 = pimg1[0]
        r2 = pimg2[0]
        g1 = pimg1[1]
        g2 = pimg2[1]
        b1 = pimg1[2]
        b2 = pimg2[2]

I then acquire the MSE between the two pixels like:

mse = math.sqrt(((r1 - r2) ** 2) + ((g1 - g2) ** 2) + ((b1 - b2) ** 2))

The problem is this is ridiculously slow. Is there a more efficient way to do this?

The final goal

I am looking to make all pixels that have a certain "thresholded" similarity, between the two images, black. And all pixels that have a larger difference the pixel of img2.

if mse > threshold:
    new_img[i][j] = pimg2
else:
    new_img[i][j] = [0, 0, 0] # black pixel

background image

entered image

I am capturing images like:

for frame in cam.camera.capture_continuous(raw, format="rgb", use_video_port=True):
    img = frame.array
    cv2.imwrite("image.png", img)

I am getting the images like:

dir = 'images/compare/'
bg = cv2.imread(dir+'bg.png')
img = cv2.imread(dir+'in.png')

Body:
Simply use np.linalg.norm on the differences -

mse = np.linalg.norm(img1-img2,axis=2)

Faster one with np.einsum -

d = (img1-img2).astype(float)
mse = np.sqrt(np.einsum('...i,...i->...',d,d))

Runtime test -

In [46]: np.random.seed(0)
    ...: m,n = 1024,1024
    ...: img1 = np.random.randint(0,255,(m,n,3)).astype(np.uint8)
    ...: img2 = np.random.randint(0,255,(m,n,3)).astype(np.uint8)

In [47]: %timeit np.linalg.norm(img1-img2,axis=2)
10 loops, best of 3: 26.6 ms per loop

In [49]: %%timeit
    ...: d = (img1-img2).astype(float)
    ...: mse = np.sqrt(np.einsum('...i,...i->...',d,d))
100 loops, best of 3: 13 ms per loop

To create an output array that is set to black for pixels that have MSE values lesser than a certain threshold mse_thresh and select from img2 otherwise, here are the additional codes -

mask = mse >= mse_thresh
out = np.where(mask[...,None], img2, 0)

Stitching everything together - Using einsum to compute squared MSE values and comparing against the squared MSE threshold for major improvement and assigning back the output into img2 -

d = (img1-img2).astype(float)
mse = np.einsum('...i,...i->...',d,d)
img2[mse < mse_thresh**2] = 0


问:
How do I do two has_many/belongs_to relationships between two models?
I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

```<code>class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end
</code>```

How do I make two relationships here?

答:
I think here's should be polymorphic association, something like this

```<code>class Owner < ActiveRecord::Base
  has_many :projects, :as => :person
end

class Client < ActiveRecord::Base
  has_many :projects, :as => :person
end

class Project < ActiveRecord::Base
  belongs_to :person, :polymorphic => true
end
</code>```

Now you can retrieve projects by @client.projects or @owner.projects. If you want to get person from @project you should add to Project migration this:

```<code>class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.references :person, :polymorphic => true
      t.timestamps
    end
  end
  ...
</code>```

Body:
I've got a Project model, and a Contact model. The Project model has an owner and a client, both of which are Contacts. I've obviously got something ambiguous going on, because if I have a contact and ask for its projects, Rails won't know whether I'm asking for it's projects where it's the client or where it's the owner. So far I've got this:

class Contact < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => 'Contact', :foreign_key => 'owner_id'
  belongs_to :client, :class_name => 'Contact', :foreign_key => 'client_id'
end

How do I make two relationships here?

Body:
I think here's should be polymorphic association, something like this

class Owner < ActiveRecord::Base
  has_many :projects, :as => :person
end

class Client < ActiveRecord::Base
  has_many :projects, :as => :person
end

class Project < ActiveRecord::Base
  belongs_to :person, :polymorphic => true
end

Now you can retrieve projects by @client.projects or @owner.projects. If you want to get person from @project you should add to Project migration this:

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.references :person, :polymorphic => true
      t.timestamps
    end
  end
  ...


问:
Excel VBA code to copy and paste rows to new sheet failing
Hi I have the following VBA code that I am trying to use for excel to copy and paste rows that meet a certain criteria to a new sheet.

The code runs to the point of copying the first match in the sheet but fails pasting on the second sheet with the error

Run-time error '14004': Application-defined or object-defined error

Can anyone help here?

```<code>Sub mileStone()
    Dim r As Long, pasteRowIndex As Long
    Dim lastRow As Long
    'lastRow = sht.Range("A1").CurrentRegion.Rows.Count

    lastRow = 24 ' need to include function to retrieve the last used row number

    pasteRowIndex = 1

    For r = 11 To lastRow 'Loop through sheet1 and search for your criteria

        If Cells(r, Columns("E").Column).Value = "defect resolution" Then 'Found

            'Copy the current row
            Rows(r).Select
            Selection.Copy

            'Switch to the sheet where you want to paste it & paste
            Sheets("Sheet2").Select
            Rows(pasteRowIndex).Select
            ActiveSheet.Paste

            'Next time you find a match, it will be pasted in a new row
            pasteRowIndex = pasteRowIndex + 1

            'Switch back to your table & continue to search for your criteria
            Sheets("Sheet1").Select
        End If
    Next r
End Sub
</code>```

答:
It might be enough to get rid of all those Selects which usually cause problems and are rarely needed (just need to add sheet references). However, AutoFilter or Find would be quicker methods.</p>

```<code>Sub mileStone()

Dim r As Long, pasteRowIndex As Long, v() As Long, i As Long

Dim lastRow As Long
'lastRow = sht.Range("A1").CurrentRegion.Rows.Count

lastRow = 13 '24 ' need to include function to retrieve the last used row number

pasteRowIndex = 1

With Sheets("Sheet1")
    For r = 11 To lastRow
        If .Cells(r, "E").Value Like "defect resolution*" Then
            If UBound(Split(.Cells(r, "E"), ",")) > 0 Then
                i = i + 1
                ReDim v(1 To i)
                v(i) = pasteRowIndex
            End If
            Sheets("Sheet1").Rows(r).Copy Sheets("Sheet2").Rows(pasteRowIndex)
            pasteRowIndex = pasteRowIndex + 1
        End If
    Next r
End With

With Sheets("Sheet2")
    If IsArray(v) Then
        .Columns(6).Insert shift:=xlToRight
        For i = LBound(v) To UBound(v)
            .Cells(v(i), "F") = Split(.Cells(v(i), "E"), ",")(1)
            .Cells(v(i), "E") = Split(.Cells(v(i), "E"), ",")(0)
        Next i
    End If
End With

End Sub
</code>```

Body:
Hi I have the following VBA code that I am trying to use for excel to copy and paste rows that meet a certain criteria to a new sheet.

The code runs to the point of copying the first match in the sheet but fails pasting on the second sheet with the error

Run-time error '14004': Application-defined or object-defined error

Can anyone help here?

Sub mileStone()
    Dim r As Long, pasteRowIndex As Long
    Dim lastRow As Long
    'lastRow = sht.Range("A1").CurrentRegion.Rows.Count

    lastRow = 24 ' need to include function to retrieve the last used row number

    pasteRowIndex = 1

    For r = 11 To lastRow 'Loop through sheet1 and search for your criteria

        If Cells(r, Columns("E").Column).Value = "defect resolution" Then 'Found

            'Copy the current row
            Rows(r).Select
            Selection.Copy

            'Switch to the sheet where you want to paste it & paste
            Sheets("Sheet2").Select
            Rows(pasteRowIndex).Select
            ActiveSheet.Paste

            'Next time you find a match, it will be pasted in a new row
            pasteRowIndex = pasteRowIndex + 1

            'Switch back to your table & continue to search for your criteria
            Sheets("Sheet1").Select
        End If
    Next r
End Sub

Body:
It might be enough to get rid of all those Selects which usually cause problems and are rarely needed (just need to add sheet references). However, AutoFilter or Find would be quicker methods.

Sub mileStone()

Dim r As Long, pasteRowIndex As Long, v() As Long, i As Long

Dim lastRow As Long
'lastRow = sht.Range("A1").CurrentRegion.Rows.Count

lastRow = 13 '24 ' need to include function to retrieve the last used row number

pasteRowIndex = 1

With Sheets("Sheet1")
    For r = 11 To lastRow
        If .Cells(r, "E").Value Like "defect resolution*" Then
            If UBound(Split(.Cells(r, "E"), ",")) > 0 Then
                i = i + 1
                ReDim v(1 To i)
                v(i) = pasteRowIndex
            End If
            Sheets("Sheet1").Rows(r).Copy Sheets("Sheet2").Rows(pasteRowIndex)
            pasteRowIndex = pasteRowIndex + 1
        End If
    Next r
End With

With Sheets("Sheet2")
    If IsArray(v) Then
        .Columns(6).Insert shift:=xlToRight
        For i = LBound(v) To UBound(v)
            .Cells(v(i), "F") = Split(.Cells(v(i), "E"), ",")(1)
            .Cells(v(i), "E") = Split(.Cells(v(i), "E"), ",")(0)
        Next i
    End If
End With

End Sub


问:
Python - accessing variable that is needed for function defined in different moduel
I have saved a defined function within a module, which I have then imported into a new script.

Within this function, the variable master (a pandas dataframe) is queried. However, master is not one of the arguments in the function and is a dataframe I am hoping to access regardless of the script.

When trying to use the aforementioned function in my new script, I get the following error:

```<code>NameError: name 'master' is not defined
</code>```

But when I enter master into the console, it prints with no problem or error.

I think it is something to do with local and global variables, but I am new to Python and am struggling to understand how I can fix the error.

答:
Within this function, the variable master (a pandas dataframe) is queried. However, master is not one of the arguments in the function

Then update your function to take it as an argument. You can't use a global here, since (if I understand correctly), your "master" variable is defined in your script and the function in a module that's imported by the script. In this case explicitely passing "master" to your function is the only way to make it available since Python has no true "global" namespace ("global" in Python actually means "module level").

And that's a GoodThing actually because it's the only sane way to structure your program.  As a general rule, globals (mutable globals that is) are evil, they make your code brittle, untestable, unmaintainable and unpredictable.

Body:
I have saved a defined function within a module, which I have then imported into a new script.

Within this function, the variable master (a pandas dataframe) is queried. However, master is not one of the arguments in the function and is a dataframe I am hoping to access regardless of the script.

When trying to use the aforementioned function in my new script, I get the following error:

NameError: name 'master' is not defined

But when I enter master into the console, it prints with no problem or error.

I think it is something to do with local and global variables, but I am new to Python and am struggling to understand how I can fix the error.


问:
merge arrays and convert to JSON string
I have two arrays consist of strings
["25","36","32"] and ["GradeA", "GradeB", "GradeC"]

I want to merge them all together and want to produce JSON string something like this:

{"GradeA" : "25", "GradeB" : "36", "GradeC": "32"}

How do I do this in js?

答:
Try ES6 Destructuring Assignment :

var obj = {};

var arr1 = ["25","36","32"];
var arr2 = ["GradeA", "GradeB", "GradeC"];

function f([...val1], [...val2]) {
    for (var i in val1) {
        obj[val1[i]] = val2[i];
    }
}

f(arr2, arr1);

console.log(obj);```

Title: merge arrays and convert to JSON string


问:
Pytest missing approx method
I imported the pytest package in Python 3.5.2 (through Anaconda) and it is missing the approx method.  I tried reinstalling pytest through pip, and I still have the same problem.  I have many of pytest's other methods, just not approx.

How can I fix this??

```<code>      1 import pytest
----> 2 assert 2 == pytest.approx(4.1/2)

AttributeError: module 'pytest' has no attribute 'approx'
</code>```

答:
Have you tried, from _pytest.python import approx? It works for me. If not, you can search easily with IDE. I am using PyCharm, and I just searched the word approx by double shift and got the location.
Simple !!

Title: Pytest missing approx method

Body:
I imported the pytest package in Python 3.5.2 (through Anaconda) and it is missing the approx method.  I tried reinstalling pytest through pip, and I still have the same problem.  I have many of pytest's other methods, just not approx.

How can I fix this??

      1 import pytest
----> 2 assert 2 == pytest.approx(4.1/2)

AttributeError: module 'pytest' has no attribute 'approx'


问:
How to add custom buttons to Angular UI Bootstrap Datepicker?
Like today,clear and close button, I want to add some more buttons to this datepicker but I was unable to do so with use of append as its a popup datepicker so content is not loaded until we click the icon, is there some simple way to add buttons to this datepicker.

答:
Plan A:

Good to find the ' today,clear,close' buttons and add your button code and  click event.

Plan B:
   You can use the timeout function to wait the date picker was loaded.
   Add append the code for your custom button functions.


问:
quanteda textstat_simil for text matching
Hello fellow text miners,

I am fairly new to the domain and I am trying to use quanteda's textstat_simil (R package) for assessing similarity between phrases. The steps are quite upfront - therefore I believe I m missing something obvious but I still cant get the feature selection working:

```<code>    #1 Create Corpus
myCorpus <- corpus(c("Anna, Maria, Luisa"))
checkWords <- c('Luisianna', 'anneta')
summary(myCorpus)

myDfm <- dfm(myCorpus)
myDfm # checking that features are there.
#removing stopwords & punctuation/ keep the stem
myDfmNoStop <- dfm(myCorpus, remove = stopwords("english"), stem = TRUE, remove_punct = TRUE)

sim <- textstat_simil(myDfmNoStop , checkWords, method = "cosine", margin = "features")
</code>```

Which returns the error:

"Error in textstat_simil.dfm(myDfm, checkWords, method = "cosine", margin = "features") : The features specified by 'selection' do not exist."

So, its not clear to me how can I specify the correct features/word of my coprus?

Needless to say - any feedback is more than welcome :)

Cheers,

George

答:
Try this:</p>
```<code>myCorpus <- corpus(c(check = "Luisianna, anneta",
                     target1 = "Anna, Maria, Luisa",
                     target2 = "Anna, anneta"))

myDfmNoStop <- dfm(myCorpus, remove = stopwords("english"), stem = TRUE, remove_punct = TRUE)

sim <- textstat_simil(myDfmNoStop , myDfmNoStop['check',], method = "cosine", margin = "documents")
</code>```

Body:
Hello fellow text miners,

I am fairly new to the domain and I am trying to use quanteda's textstat_simil (R package) for assessing similarity between phrases. The steps are quite upfront - therefore I believe I m missing something obvious but I still cant get the feature selection working:

    #1 Create Corpus
myCorpus <- corpus(c("Anna, Maria, Luisa"))
checkWords <- c('Luisianna', 'anneta')
summary(myCorpus)

myDfm <- dfm(myCorpus)
myDfm # checking that features are there.
#removing stopwords & punctuation/ keep the stem
myDfmNoStop <- dfm(myCorpus, remove = stopwords("english"), stem = TRUE, remove_punct = TRUE)

sim <- textstat_simil(myDfmNoStop , checkWords, method = "cosine", margin = "features")

Which returns the error:

"Error in textstat_simil.dfm(myDfm, checkWords, method = "cosine", margin = "features") : The features specified by 'selection' do not exist."

So, its not clear to me how can I specify the correct features/word of my coprus?

Needless to say - any feedback is more than welcome :)

Cheers,

George

Body:
Try this:

myCorpus <- corpus(c(check = "Luisianna, anneta",
                     target1 = "Anna, Maria, Luisa",
                     target2 = "Anna, anneta"))

myDfmNoStop <- dfm(myCorpus, remove = stopwords("english"), stem = TRUE, remove_punct = TRUE)

sim <- textstat_simil(myDfmNoStop , myDfmNoStop['check',], method = "cosine", margin = "documents")

ContentLicense: CC BY-SA 4.0


问:
Passing <select> as jQuery event's parameter
when I pass a <select> element as a parameter to jQuery event (using trigger) the event handler gets only the first <option> of that <select>. Is this a bug or am I doing something wrong?

I wrote a simple Snippet to demostrate it.
 Please see the output in the console.

var onInputMounted = function(e, data) {
  console.log("mounted", data);
};

var onInputUnmounted = function(e, data) {
  console.log("unmounted", data);
};

var observer = new MutationObserver(function(changes) {
  changes.forEach(function(element, index) {
    var allChangedNodes = [];
    var allChangedInputs = [];

    if (element.type === "childList") {
      // get all changed (added/removed) HTML nodes
      if (element.addedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.addedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "mounted"
            };
          });
      } else if (element.removedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.removedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "unmounted"
            };
          });
      }

      // get all changed (added/removed) HTML :input fields
      allChangedInputs = allChangedNodes
        .map(function(e) {
          return $(e.node)
            .find(":input")
            .addBack(":input")
            .map(function(i, input) {
              return {
                input: input,
                event: e.event
              };
            });
        })
        .reduce(function(arrLike1, arrLike2) {
          var arr1 = Array.prototype.slice.call(arrLike1);
          var arr2 = Array.prototype.slice.call(arrLike2);
          return arr1.concat(arr2);
        });
    }

    // trigger the corresponding event: mounted (for added inputs), unmounted (for removed ones)
    for (var i = 0; i < allChangedInputs.length; i++) {
      console.log("trigger", allChangedInputs[i]);
      $("#container").trigger(
        allChangedInputs[i].event,
        allChangedInputs[i].input
      );
    }
  });
});

// register events
$("#container").on("mounted", onInputMounted);
$("#container").on("unmounted", onInputUnmounted);

// observe changes on DOM
observer.observe($("#container")[0], {
  childList: true,
  subtree: true,
  attributes: false,
  characterData: false
});

// append a div with two inputs
$("#container").append(
  '
<input id="name" /><select id="gender"><option value="male">male</option><option value="female">female</option></select>
'
);```
<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>
<div id="container"></div></code>```

I trigger the events "mounted" and "unmounted" like this:

```<code>$("#container").trigger(
   allChangedInputs[i].event,
   allChangedInputs[i].input
);
</code>```

Where allChangedInputs[i].input is the HTML input has been added (mounted)/removed (unmounted)

The problem is when this input is a <select> the event handler receives it only as <option>. Any clue?

Thanks!

答:
It is because trigger method takes either an array or an object, and it is trying to convert allChangedInputs[i].input to an array.

Simply converting it to

```<code>[allChangedInputs[i].input]
</code>```

solves your problem, see demo below

var onInputMounted = function(e, data) {
  console.log("mounted", data);
};

var onInputUnmounted = function(e, data) {
  console.log("unmounted", data);
};

var observer = new MutationObserver(function(changes) {
  changes.forEach(function(element, index) {
    var allChangedNodes = [];
    var allChangedInputs = [];

    if (element.type === "childList") {
      // get all changed (added/removed) HTML nodes
      if (element.addedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.addedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "mounted"
            };
          });
      } else if (element.removedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.removedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "unmounted"
            };
          });
      }

      // get all changed (added/removed) HTML :input fields
      allChangedInputs = allChangedNodes
        .map(function(e) {
          return $(e.node)
            .find(":input")
            .addBack(":input")
            .map(function(i, input) {
              return {
                input: input,
                event: e.event
              };
            });
        })
        .reduce(function(arrLike1, arrLike2) {
          var arr1 = Array.prototype.slice.call(arrLike1);
          var arr2 = Array.prototype.slice.call(arrLike2);
          return arr1.concat(arr2);
        });
    }

    // trigger the corresponding event: mounted (for added inputs), unmounted (for removed ones)
    for (var i = 0; i < allChangedInputs.length; i++) {
      console.log("trigger", allChangedInputs[i]);
      $("#container").trigger(
        allChangedInputs[i].event,
        [allChangedInputs[i].input] //this line
      );
    }
  });
});

// register events
$("#container").on("mounted", onInputMounted);
$("#container").on("unmounted", onInputUnmounted);

// observe changes on DOM
observer.observe($("#container")[0], {
  childList: true,
  subtree: true,
  attributes: false,
  characterData: false
});

// append a div with two inputs
$("#container").append(
  '
<input id="name" /><select id="gender"><option value="male">male</option><option value="female">female</option></select>
'
);```
<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>
<div id="container"></div></code>```

Body:
when I pass a <select> element as a parameter to jQuery event (using trigger) the event handler gets only the first <option> of that <select>. Is this a bug or am I doing something wrong?

I wrote a simple Snippet to demostrate it.
 Please see the output in the console.

var onInputMounted = function(e, data) {
  console.log("mounted", data);
};

var onInputUnmounted = function(e, data) {
  console.log("unmounted", data);
};

var observer = new MutationObserver(function(changes) {
  changes.forEach(function(element, index) {
    var allChangedNodes = [];
    var allChangedInputs = [];

    if (element.type === "childList") {
      // get all changed (added/removed) HTML nodes
      if (element.addedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.addedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "mounted"
            };
          });
      } else if (element.removedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.removedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "unmounted"
            };
          });
      }

      // get all changed (added/removed) HTML :input fields
      allChangedInputs = allChangedNodes
        .map(function(e) {
          return $(e.node)
            .find(":input")
            .addBack(":input")
            .map(function(i, input) {
              return {
                input: input,
                event: e.event
              };
            });
        })
        .reduce(function(arrLike1, arrLike2) {
          var arr1 = Array.prototype.slice.call(arrLike1);
          var arr2 = Array.prototype.slice.call(arrLike2);
          return arr1.concat(arr2);
        });
    }

    // trigger the corresponding event: mounted (for added inputs), unmounted (for removed ones)
    for (var i = 0; i < allChangedInputs.length; i++) {
      console.log("trigger", allChangedInputs[i]);
      $("#container").trigger(
        allChangedInputs[i].event,
        allChangedInputs[i].input
      );
    }
  });
});

// register events
$("#container").on("mounted", onInputMounted);
$("#container").on("unmounted", onInputUnmounted);

// observe changes on DOM
observer.observe($("#container")[0], {
  childList: true,
  subtree: true,
  attributes: false,
  characterData: false
});

// append a div with two inputs
$("#container").append(
  '
<input id="name" /><select id="gender"><option value="male">male</option><option value="female">female</option></select>
'
);

I trigger the events "mounted" and "unmounted" like this:

$("#container").trigger(
   allChangedInputs[i].event,
   allChangedInputs[i].input
);

Where allChangedInputs[i].input is the HTML input has been added (mounted)/removed (unmounted)

The problem is when this input is a <select> the event handler receives it only as <option>. Any clue?

Thanks!

Body:
It is because trigger method takes either an array or an object, and it is trying to convert allChangedInputs[i].input to an array.

Simply converting it to

[allChangedInputs[i].input]

solves your problem, see demo below

var onInputMounted = function(e, data) {
  console.log("mounted", data);
};

var onInputUnmounted = function(e, data) {
  console.log("unmounted", data);
};

var observer = new MutationObserver(function(changes) {
  changes.forEach(function(element, index) {
    var allChangedNodes = [];
    var allChangedInputs = [];

    if (element.type === "childList") {
      // get all changed (added/removed) HTML nodes
      if (element.addedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.addedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "mounted"
            };
          });
      } else if (element.removedNodes.length > 0) {
        allChangedNodes = Array.prototype.slice
          .call(element.removedNodes)
          .map(function(e, i) {
            return {
              node: e,
              event: "unmounted"
            };
          });
      }

      // get all changed (added/removed) HTML :input fields
      allChangedInputs = allChangedNodes
        .map(function(e) {
          return $(e.node)
            .find(":input")
            .addBack(":input")
            .map(function(i, input) {
              return {
                input: input,
                event: e.event
              };
            });
        })
        .reduce(function(arrLike1, arrLike2) {
          var arr1 = Array.prototype.slice.call(arrLike1);
          var arr2 = Array.prototype.slice.call(arrLike2);
          return arr1.concat(arr2);
        });
    }

    // trigger the corresponding event: mounted (for added inputs), unmounted (for removed ones)
    for (var i = 0; i < allChangedInputs.length; i++) {
      console.log("trigger", allChangedInputs[i]);
      $("#container").trigger(
        allChangedInputs[i].event,
        [allChangedInputs[i].input] //this line
      );
    }
  });
});

// register events
$("#container").on("mounted", onInputMounted);
$("#container").on("unmounted", onInputUnmounted);

// observe changes on DOM
observer.observe($("#container")[0], {
  childList: true,
  subtree: true,
  attributes: false,
  characterData: false
});

// append a div with two inputs
$("#container").append(
  '<div><input id="name" /><select id="gender"><option value="male">male</option><option value="female">female</option></select></div>'
);

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


问:
Append data to json file
I have a .json file which looks like this for now:

```<code>{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}
</code>```

I want to append a line in Python directly after {"name" : "test2}.
Other questions I found will give me this solution:

```<code>{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}{"name" : "test3"} # <-- Wrong place it shouldn't be here
</code>```

This is what it should look like:

```<code>{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"},
        {"name" : "test3"}  # <-- new line here
    ]
}     # <-- not here
</code>```

答:
Here is a possible solution.</p>

```<code>import json
# your string
json_string = '{
    "users":
      [
        {"name" : "test"},
        {"name" : "test2"}
      ]
    }'
# convert it to a python dictionary
json_dict = json.loads(json_string)
# append your data as {key:value}
json_dict['users'].append({'name':'test3'})
# convert it back to string
json_string = json.dumps(json_dict)
print (json_string)
</code>```

Title: Append data to json file

Body:
I have a .json file which looks like this for now:

{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}

I want to append a line in Python directly after {"name" : "test2}.
Other questions I found will give me this solution:

{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"}
    ]
}{"name" : "test3"} # <-- Wrong place it shouldn't be here

This is what it should look like:

{
    "users":
    [
        {"name" : "test"},
        {"name" : "test2"},
        {"name" : "test3"}  # <-- new line here
    ]
}     # <-- not here

Body:
Here is a possible solution.

import json
# your string
json_string = '{
    "users":
      [
        {"name" : "test"},
        {"name" : "test2"}
      ]
    }'
# convert it to a python dictionary
json_dict = json.loads(json_string)
# append your data as {key:value}
json_dict['users'].append({'name':'test3'})
# convert it back to string
json_string = json.dumps(json_dict)
print (json_string)


问:
You must specify |clientID| for |GIDSignIn| error when trying to sign in with Google
Google sign in was working fine with Xcode 7. After updating to Xcode 8, I started getting the error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'You must specify |clientID| for |GIDSignIn|'. I have a GoogleService-Info.plist file with my CLIENT_ID.

I was able to fix it by adding the following line:

```<code>GIDSignIn.sharedInstance().clientID = "<CLIENT_ID>"
</code>```

It seems the CLIENT_ID isn't being fetched from GoogleService-Info.plist. I've made sure it's in the Copy Bundle Resources.

I shouldn't have to specify the client id in the code. How can I fix it to get the information from the GoogleService-Info.plist file?

答:
Please make sure you have these code place in sequence.

```<code>FirebaseApp.configure()

GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
</code>```

FirebaseApp.app()?.options.clientID will only able to get data from GoogleService-Info.plist after FirebaseApp.configure() is called.

Body:
Google sign in was working fine with Xcode 7. After updating to Xcode 8, I started getting the error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'You must specify |clientID| for |GIDSignIn|'. I have a GoogleService-Info.plist file with my CLIENT_ID.

I was able to fix it by adding the following line:

GIDSignIn.sharedInstance().clientID = "<CLIENT_ID>"

It seems the CLIENT_ID isn't being fetched from GoogleService-Info.plist. I've made sure it's in the Copy Bundle Resources.

I shouldn't have to specify the client id in the code. How can I fix it to get the information from the GoogleService-Info.plist file?

Body:
Please make sure you have these code place in sequence.

FirebaseApp.configure()

GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self

FirebaseApp.app()?.options.clientID will only able to get data from GoogleService-Info.plist after FirebaseApp.configure() is called.


问:
No possibilities to organize my typescript code and prevent polluting global namespace out of the box?
Now that the modules became namespaces and namespaces became deprecated as you can read here, do I have any possibilities left to organize my typescript code?

And the main question is, what possibilities do I have to prevent polluting the global namespace? Because in my opinion I have none left and that would be a huge dealbreaker in comparison to vanilla JS.

答:
Modules are by far the best way to manage your application. Modules add zero items to the global scope, and they provide many different options for loading.

Namespaces are second-best, as they add a single item to the global scope - and if you nest them, you can keep all of your namespaces within a single root meaning no matter how large your application gets, you have just one item in the global scope.

Namespaces have not been deprecated, the TSLint rule is a nudge to push people towards modules - but as with all TSLint rules - you are in charge, not the tools. If you decide that your architecture will use namespaces, you can switch off the rule with this configuration:

```<code>"no-namespace": false
</code>```

Modules, Namespaces, and Bears... oh my!

When TypeScript 0.8 came out, there were "internal modules" and "external modules". These later got renamed, so they changed like this:

Internal Modules became "Namespaces"

External Modules became "Modules"

For internal modules, it just meant changing:

```<code>module OrderProcessing {
</code>```

To:

```<code>namespace OrderProcessing {
</code>```

And for external modules, it just means referring to them as "modules" as you don't wrap external modules with anything. An external module (or "module" as it is now known) is just a file that exports something...

module.ts

```<code>export function go() {
    return 'go go go';
}
</code>```

You can use a module from another file...

```<code>import { go } from './module.js';

alert(go());
</code>```

None of the contents of module.ts makes it into the global scope.

Neither namespace or modules are deprecated, you can use either (but don't mix them). TSLint would rather you used modules.

Body:
Modules are by far the best way to manage your application. Modules add zero items to the global scope, and they provide many different options for loading.

Namespaces are second-best, as they add a single item to the global scope - and if you nest them, you can keep all of your namespaces within a single root meaning no matter how large your application gets, you have just one item in the global scope.

Namespaces have not been deprecated, the TSLint rule is a nudge to push people towards modules - but as with all TSLint rules - you are in charge, not the tools. If you decide that your architecture will use namespaces, you can switch off the rule with this configuration:

"no-namespace": false

Modules, Namespaces, and Bears... oh my!

When TypeScript 0.8 came out, there were "internal modules" and "external modules". These later got renamed, so they changed like this:

Internal Modules became "Namespaces"

External Modules became "Modules"

For internal modules, it just meant changing:

module OrderProcessing {

To:

namespace OrderProcessing {

And for external modules, it just means referring to them as "modules" as you don't wrap external modules with anything. An external module (or "module" as it is now known) is just a file that exports something...

module.ts

export function go() {
    return 'go go go';
}

You can use a module from another file...

import { go } from './module.js';

alert(go());

None of the contents of module.ts makes it into the global scope.

Neither namespace or modules are deprecated, you can use either (but don't mix them). TSLint would rather you used modules.


问:
Why does a Fortran POINTER require a TARGET?
Why does the Fortran 90 Specification specify (5.2.8) that the TARGET keyword must be used to associate a POINTER to it? Why isn't every type a valid TARGET?

For example,
```
INTEGER, POINTER :: px
INTEGER, TARGET :: x
x = 5
px => x
```
is valid syntax but
```
INTEGER, POINTER :: px
INTEGER :: x
x = 5
px => x
```
is not valid.

Why must this be?

答: Pointers in fortran are different than pointers in c. In fortran 90 pointers were provided with few restriction like having a target. This was done to address speed issue and to keep pointer usage safe. Although one call make allocatable pointers which do not need to specify a target. Dig deeper and you will find them!!</p>

Body:
Why does the Fortran 90 Specification specify (5.2.8) that the TARGET keyword must be used to associate a POINTER to it? Why isn't every type a valid TARGET?

For example,

INTEGER, POINTER :: px
INTEGER, TARGET :: x
x = 5
px => x

is valid syntax but

INTEGER, POINTER :: px
INTEGER :: x
x = 5
px => x

is not valid.

Why must this be?


问:
How to enable FULL Logging with Ganymed SSH-2
I am developing a java application that executes ssh commands using Ganymed SSH-2

I need to produce full logs for each sequence of commands, e.g. zip file transfer, unzipping, zipping etc..

Having searched the source code for ch.ethz.ssh2.log.Logger i can set the boolean public static volatile boolean enabled = false; to true

this provides the following output

```<code>Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: kex_algo=diffie-hellman-group-exchange-sha1
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: server_host_key_algo=ssh-rsa
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: enc_algo_client_to_server=aes128-ctr
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: enc_algo_server_to_client=aes128-ctr
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: mac_algo_client_to_server=hmac-sha1-96
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: mac_algo_server_to_client=hmac-sha1-96
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: comp_algo_client_to_server=none
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: comp_algo_server_to_client=none
</code>```

However I also require ALL level logging for command execution including file transfers.

How do i configure the Logger to produce all the information available?

答:
A little late answer but maybe someone still needs this info.

I managed to get the debug statements visible like this:

```<code>    public void enableFineLogging() {
    try {
        ch.ethz.ssh2.log.Logger.enabled = true;
        String name = "myDynamicFileNamePart";

        FileHandler fileHandler = new FileHandler("./logs/"
                + name + "_SFTP.log", 10000000, 1000, true);
        fileHandler.setLevel(Level.FINE);
        fileHandler.setFormatter(new SimpleFormatter());

        final Logger app = Logger.getLogger("ch.ethz");
        app.setLevel(Level.FINE);
        app.addHandler(fileHandler);
        app.setUseParentHandlers(false);

    } catch (Exception e) {
        // Catchalog
    }
}
</code>```

With result in file with:

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter info

INFO: Client identity string: SSH-2.0-SSHJ_0.19.1

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter info

INFO: Server identity string: SSH-2.0-OpenSSH_6.6.1

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Setting <> to null

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Sending SSH_MSG_KEXINIT

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Setting <> to SOME

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Awaiting <>

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Received SSH_MSG_KEXINIT

Use ConsoleHandler if you wish logs in console.
Also closing the log file needs to be considered with fileHandler.close() after you quit logging.

Tune the log level by choosing from SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL

Body:
I am developing a java application that executes ssh commands using Ganymed SSH-2

I need to produce full logs for each sequence of commands, e.g. zip file transfer, unzipping, zipping etc..

Having searched the source code for ch.ethz.ssh2.log.Logger i can set the boolean public static volatile boolean enabled = false; to true

this provides the following output

Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: kex_algo=diffie-hellman-group-exchange-sha1
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: server_host_key_algo=ssh-rsa
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: enc_algo_client_to_server=aes128-ctr
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: enc_algo_server_to_client=aes128-ctr
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: mac_algo_client_to_server=hmac-sha1-96
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: mac_algo_server_to_client=hmac-sha1-96
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: comp_algo_client_to_server=none
Mar 05, 2015 10:17:25 AM ch.ethz.ssh2.log.Logger info
INFO: comp_algo_server_to_client=none

However I also require ALL level logging for command execution including file transfers.

How do i configure the Logger to produce all the information available?

Body:
A little late answer but maybe someone still needs this info.

I managed to get the debug statements visible like this:

    public void enableFineLogging() {
    try {
        ch.ethz.ssh2.log.Logger.enabled = true;
        String name = "myDynamicFileNamePart";

        FileHandler fileHandler = new FileHandler("./logs/"
                + name + "_SFTP.log", 10000000, 1000, true);
        fileHandler.setLevel(Level.FINE);
        fileHandler.setFormatter(new SimpleFormatter());

        final Logger app = Logger.getLogger("ch.ethz");
        app.setLevel(Level.FINE);
        app.addHandler(fileHandler);
        app.setUseParentHandlers(false);

    } catch (Exception e) {
        // Catchalog
    }
}

With result in file with:

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter info

INFO: Client identity string: SSH-2.0-SSHJ_0.19.1

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter info

INFO: Server identity string: SSH-2.0-OpenSSH_6.6.1

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Setting <> to null

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Sending SSH_MSG_KEXINIT

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Setting <> to SOME

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Awaiting <>

marras 15, 2017 12:16:56 IP. org.slf4j.impl.JCLLoggerAdapter debug

FINE: Received SSH_MSG_KEXINIT

Use ConsoleHandler if you wish logs in console.
Also closing the log file needs to be considered with fileHandler.close() after you quit logging.

Tune the log level by choosing from SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL


问:
php  how to pass value to another page when click the href? and how to retrieve the value from another page?
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

```<code>                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '<label class="label1">' . $row->name . '</label><br><br>';
                    echo '<a href="#"><img src="' . $row->image . '" class="poster"></a>';
                    echo '<div class = "section3"><a href="synopsis.php?id="' . $row->id . '" >asd</a>&nbsp &nbsp <a href="">Buy Now</a>';
                }
            }

            ?>
</code>```

答:
This may help:
PHP GET method in href>

You simply add your data to the URL in your href and retrieve it on the next page by using the GET Method.

For example in your echo a href:

```<code>echo '<a href="movie.php?id="' . $row->id .'"><img src="' . $row->image . '" class="poster"></a>';
</code>```

And then in movie.php you would use

```<code>$_GET['id'];
</code>```

To fetch the selected movie.

Title: php <a href> how to pass value to another page when click the href? and how to retrieve the value from another page?

Body:
How do I pass the value with a href when click href link and go next page? Beside that, on the next page how I retrieve the value?

My code:

                <?php

            $sql = "SELECT DISTINCT movie.image, movie.name, movie.id
                                FROM movie
                                INNER JOIN movie_genre
                                ON movie.id = movie_genre.movie_id
                                INNER JOIN genre ON genre.id = movie_genre.genre_id
                                INNER JOIN movie_date ON movie_date.movie_id = movie.id
                                ORDER BY timestamp DESC LIMIT 6";

            $res = mysqli_query($conn, $sql);
            if(mysqli_num_rows($res) > 0) {
                while($row = mysqli_fetch_object($res)) {
                    echo '' . $row->name . '

';
                    echo 'image . '" class="poster">';
                    echo '
id . '" >asd&nbsp &nbsp Buy Now';
                }
            }

            ?>

Body:
This may help:
PHP GET method in <a href>

You simply add your data to the URL in your href and retrieve it on the next page by using the GET Method.

For example in your echo a href:

echo '<a href="movie.php?id="' . $row->id .'"><img src="' . $row->image . '" class="poster"></a>';

And then in movie.php you would use

$_GET['id'];

To fetch the selected movie.


问:
Dynamically add element beside inputs
Let's say I have 10 different input fields, each of them has an ID.

<input id="blue">
<input id="pink">
<input id="red">

```

<p>Next to these input fields, I want to create an <code><a></code> element whose <code>href</code> attribute should dynamically include the ID of the button right next to it:</p>

<pre class="lang-html prettyprint-override"><code><input id="blue">
<a/>

<input id="pink">
href="mylink.com/pink"><a/>

<input id="red">
href="mylink.com/red"><a/>
</code>```

This is the simple code I am working with:

$('input').prepend('href="mylink.com/'+ID of the element next to this a tag+'/'');```

答:
$.fn.preprend method you are trying to use is not the right tool for this problem, since it inserts content into element, while you want to ippend it next to it as sibling.

When you need to operate on set of elements in similar way, you should consider giving them the same class name for easy DOM querying. Then it would be very easy with the help of $.fn.after method:

// $('input') will also work of course
$('.input').after(function () {
  return $('', {
    href: 'http://mylink.com/' + this.id,
    text: this.id
  })
  // or return string:
  // return '' + this.id + ''
})```
<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>

<input id="blue" class="input">
<input id="pink" class="input">
<input id="red" class="input"></code>```

Title: Dynamically add element beside inputs

Body:
Let's say I have 10 different input fields, each of them has an ID.

<input id="blue">
<input id="pink">
<input id="red">

Next to these input fields, I want to create an  element whose href attribute should dynamically include the ID of the button right next to it:

<input id="blue">

<input id="pink">

<input id="red">

This is the simple code I am working with:

$('input').prepend('<a href="mylink.com/'+ID of the element next to this a tag+'/'');

Body:
$.fn.preprend method you are trying to use is not the right tool for this problem, since it inserts content into element, while you want to ippend it next to it as sibling.

When you need to operate on set of elements in similar way, you should consider giving them the same class name for easy DOM querying. Then it would be very easy with the help of $.fn.after method:

// $('input') will also work of course
$('.input').after(function () {
  return $('<a>', {
    href: 'http://mylink.com/' + this.id,
    text: this.id
  })
  // or return string:
  // return '<a href="http://mylink.com/' + this.id + '">' + this.id + '</a>'
})

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

<input id="blue" class="input">
<input id="pink" class="input">
<input id="red" class="input">


问:
Create async version of sync method
I'm currently writing an component where I already have a synchronous method to download files from a server. Here's the signature:

```<code>public Stream DownloadFile(IData data)
</code>```

Now I wanted to have an async version of this method and tried this:

```<code> public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      DownloadFile(data);
    });
    return stream;
 }
</code>```

But resharper is showing me a squiggle line under return stream; "expression is always null". Can somebody tell me what is wrong with my code?

What I want to do is run the DownloadFile method in background and return controlflow to the caller.

EDIT: here is the DownloadFile method:

```<code>var ms = new MemoryStream();

  using (var dtService = new DataTransferService(mConnectionInfo))
  {
    int bytesRead;
    do
    {
      var buffer = new byte[data.ChunkSize];
      bytesRead = dtService.Read(data, buffer);

      if (bytesRead == 0)
      {
        break;
      }

      data.Offset += bytesRead;
      ms.Write(buffer, 0, buffer.Length);
    } while (bytesRead > 0);
  }

  return ms;
</code>```

Thanks

答:
Best option would be to rewrite the DownloadFile() method using async I/O, for instance with HttpClient.

Making the current DownloadFile() async with a wrapper is pointless.

If you are stuck between a requirement and the given infrastructure then just fake it while doing the least amount of damage:

```<code>public Task<Stream> DownloadFileAsync(IData data)  // not 'async', just Task<>
{
    return Task.FromResult(DownloadFile(data));
}
</code>```

Title: Create async version of sync method

Body:
I'm currently writing an component where I already have a synchronous method to download files from a server. Here's the signature:

public Stream DownloadFile(IData data)

Now I wanted to have an async version of this method and tried this:

 public async Task<Stream> DownloadFileAsync(IData data)
 {
    Stream stream = null;
    await Task.Run(() =>
    {
      DownloadFile(data);
    });
    return stream;
 }

But resharper is showing me a squiggle line under return stream; "expression is always null". Can somebody tell me what is wrong with my code?

What I want to do is run the DownloadFile method in background and return controlflow to the caller.

EDIT: here is the DownloadFile method:

var ms = new MemoryStream();

  using (var dtService = new DataTransferService(mConnectionInfo))
  {
    int bytesRead;
    do
    {
      var buffer = new byte[data.ChunkSize];
      bytesRead = dtService.Read(data, buffer);

      if (bytesRead == 0)
      {
        break;
      }

      data.Offset += bytesRead;
      ms.Write(buffer, 0, buffer.Length);
    } while (bytesRead > 0);
  }

  return ms;

Thanks

Body:
Best option would be to rewrite the DownloadFile() method using async I/O, for instance with HttpClient.

Making the current DownloadFile() async with a wrapper is pointless.

If you are stuck between a requirement and the given infrastructure then just fake it while doing the least amount of damage:

public Task<Stream> DownloadFileAsync(IData data)  // not 'async', just Task<>
{
    return Task.FromResult(DownloadFile(data));
}


问:
Convert date in ISO YYYY-MM-DDThh:mm:ss.sTZD format
I want to format date in ISO YYYY-MM-DDThh:mm:ss.sTZD format using javascript.

I can convert current date string in  yyyy-MM-dd'T'HH:mm:ss.SSSZ format. For example 2016-01-11T02:40:33.117Z. But I want to get like 2016-01-11T02:40:33.117+1100.

Is it possible in javascript?

答:
```<code>function getCurrentDateFormated() {
  var date = new Date();
  date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
  var timeZoneHours = date.getTimezoneOffset() / 60;
  var finalHours = Math.abs(timeZoneHours) < 10 ?
    timeZoneHours < 0 ? '-0' + timeZoneHours.toString().substring(1)
    : '+0' + timeZoneHours.toString().substring(1)
    : timeZoneHours;
  var timeZoneMin = ((timeZoneHours - Math.floor(timeZoneHours)) * 60) < 10 ?
    '0' + (timeZoneHours - Math.floor(timeZoneHours)) * 60 : (timeZoneHours - Math.floor(timeZoneHours)) * 60;
  var timeZone = finalHours + timeZoneMin;
  return date.toISOString().substring(0, 20) + date.getMilliseconds() + timeZone;
}
</code>```


问:
PEG grammar to suppress execution in if command
I want to create a grammar parsing some commands. Most is working flawless but the "if(condition,then-value,else-value)" is not working together with "out" command to show some value.
It works fine in case the output-command is outside the if-command:

```<code>out(if(1,42,43))
</code>```

→ output and return 42 as expected OK

But at the moment the output-command is inside then- and else-part (which is required to be more intuitive) it fails:

```<code>if(1,out(42),out(43))
</code>```

→ still return only 42 as expected OK, but the output function is called twice with 42 and 43

I'm working under C with the peg/leg parser generator here
The problem is also reproducible with PEG.js online parser generator here when using the following very much simplified grammar:

```<code>Expression
  = Int
  / "if(" cond:Expression "," ok:Expression "," nok:Expression ")" { return cond?ok:nok; }
  / "out(" num:Expression ")" { window.alert(num); return num;}

Int = [0-9]+ { return parseInt(text(), 10); }
</code>```

The "window.alert()" is only a placeholder for the needed output function, but for this problem it acts the same.
It looks like the scanner have to match the full if-command with then-
 and else-value until the closing bracket ")". So it matches both out-commands and they both execute the defined function - which is not what I expect.

Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?

(I've already experimented with "&" predicate element without success)

(Maybe left-recursion vs. right-recursion could help here, but used peg/leg-generator seems to only supports right-recursion)

答:
An solution could be using a predicate expression "& {expression}" (not to be confused by predicate element "& element")

```<code>Expression
  = Function

Function
  = Int
  / "if(" IfCond "," ok:Function "," nok:FunctionDisabled ")" { return ok; }
  / "if(" FunctionDisabled "," ok:FunctionDisabled "," nok:Function ")" { return nok; }
  / "out(" num:Function ")" { window.alert("Out:"+num); return num;}

FunctionDisabled
  = Int
  / "if(" IfCond "," ok:FunctionDisabled "," nok:FunctionDisabled ")" { return ok; }
  / "if(" FunctionDisabled "," ok:FunctionDisabled "," nok:FunctionDisabled ")" { return nok; }

  / "out(" num:FunctionDisabled ")" { return num;}

IfCond
  = cond:FunctionDisabled   &{ return cond; }

Int = [0-9]+ { return parseInt(text(), 10); }
</code>```

The idea is to define the out() twice, once really doing something and a second time disabled without output.
The condition of the if-command is evaluated using the code inside {}, so if the condition is false, the whole expression match failes.

Visible drawback is the redundant definition of the if-command for then and else and recursive disabled

Body:
I want to create a grammar parsing some commands. Most is working flawless but the "if(condition,then-value,else-value)" is not working together with "out" command to show some value.
It works fine in case the output-command is outside the if-command:

out(if(1,42,43))

→ output and return 42 as expected OK

But at the moment the output-command is inside then- and else-part (which is required to be more intuitive) it fails:

if(1,out(42),out(43))

→ still return only 42 as expected OK, but the output function is called twice with 42 and 43

I'm working under C with the peg/leg parser generator here
The problem is also reproducible with PEG.js online parser generator here when using the following very much simplified grammar:

Expression
  = Int
  / "if(" cond:Expression "," ok:Expression "," nok:Expression ")" { return cond?ok:nok; }
  / "out(" num:Expression ")" { window.alert(num); return num;}

Int = [0-9]+ { return parseInt(text(), 10); }

The "window.alert()" is only a placeholder for the needed output function, but for this problem it acts the same.
It looks like the scanner have to match the full if-command with then-
 and else-value until the closing bracket ")". So it matches both out-commands and they both execute the defined function - which is not what I expect.

Is there a way in peg/leg to match some characters but suppress execution of the according function under some circumstances?

(I've already experimented with "&" predicate element without success)

(Maybe left-recursion vs. right-recursion could help here, but used peg/leg-generator seems to only supports right-recursion)

Body:
An solution could be using a predicate expression "& {expression}" (not to be confused by predicate element "& element")

Expression
  = Function

Function
  = Int
  / "if(" IfCond "," ok:Function "," nok:FunctionDisabled ")" { return ok; }
  / "if(" FunctionDisabled "," ok:FunctionDisabled "," nok:Function ")" { return nok; }
  / "out(" num:Function ")" { window.alert("Out:"+num); return num;}

FunctionDisabled
  = Int
  / "if(" IfCond "," ok:FunctionDisabled "," nok:FunctionDisabled ")" { return ok; }
  / "if(" FunctionDisabled "," ok:FunctionDisabled "," nok:FunctionDisabled ")" { return nok; }

  / "out(" num:FunctionDisabled ")" { return num;}

IfCond
  = cond:FunctionDisabled   &{ return cond; }

Int = [0-9]+ { return parseInt(text(), 10); }

The idea is to define the out() twice, once really doing something and a second time disabled without output.
The condition of the if-command is evaluated using the code inside {}, so if the condition is false, the whole expression match failes.

Visible drawback is the redundant definition of the if-command for then and else and recursive disabled


问:
Recurring "PermGen" in Tomcat 6
I keep getting a "PermGen" error on my Tomcat 6 server.

I know what application is causing the problem, but I am not sure why it is doing so.  The application is using MySQL 5 and running on JDK 6.

Are there any tools/suggestions to diagnosis or analyze the underlying issue(s) with the specific application?

Thanks

答:
The PermGen is used to store class definitions and the interned string pool. Your code could be filling it (if it calls intern needlessly), but more likely is that the default is undersized for your application.

This is because Tomcat will load new classes every time you deploy a WAR -- or, if you are working in a development environment, every time you edit a JSP. Those should eventually get cleaned up, but in an active development environment you can have periods where there are both old and new instances loaded. Or, if you're in a production environment and have a large web-app, you might simply need more space.

To set the permgen size, use -XX:MaxPermSize=SIZE

The following links may be helpful: tuning GC (this is the 1.5 edition), GC FAQ (1.4.2 edition), Hotspot VM options (I believe this is 1.6)

OwnerDisplayName: Berek Bryan

Title: Recurring "PermGen" in Tomcat 6

OwnerDisplayName: kdgregory

LastEditorDisplayName: kdgregory


问:
Zend framework admin module and other modules
I want to build a CMS based on Zend Framework for my needs which has admin module with authentication and other modules (pages, users, news) which can be used as plugin modules based on the appliaction needs.

I want every module to have specific frontend and backend code, so that it could be accessed like e.g. http://localhost/mycms/pages/view/5 to view a certain page from the pages module by calling Pages controller, view action. The backend for every plugin needs to be tied to the admin and require authentication, it could be accessed like http://localhost/mycms/admin/pages/add.

The problem is that the solution I found involves removing default routes and writing custom routing for every controller action inside the plugin modules like:

```<code>  $router->removeDefaultRoutes();

  $route = new Zend_Controller_Router_Route_Static(
      'admin/pages/add',
      array(
       'module' => 'pages',
       'controller' => 'Pages',
       'action' => 'add'
      )
  );

  $router->addRoute('pages_pages_add', $route);

  $route = new Zend_Controller_Router_Route_Regex(
      'pages/view/(\d+)',
      array(
       'module' => 'pages',
       'controller' => 'Pages',
       'action' => 'view'
      ),
      array(
       '1' => 'page_id'
      )
  );

  $router->addRoute('pages_pages_view', $route);
</code>```

Do you have any ideas how I can avoid this custom routing?

答:
Have a look at Front Controller Plugins, they may give you more flexibility...

http://framework.zend.com/manual/en/zend.controller.plugins.html

```<code>class Controller_Plugin_Foo extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch( Zend_Controller_Request_Abstract $request )
    {
        $frontController = Zend_Controller_Front::getInstance();
        ...
    }
}
</code>```

Body:
I want to build a CMS based on Zend Framework for my needs which has admin module with authentication and other modules (pages, users, news) which can be used as plugin modules based on the appliaction needs.

I want every module to have specific frontend and backend code, so that it could be accessed like e.g. http://localhost/mycms/pages/view/5 to view a certain page from the pages module by calling Pages controller, view action. The backend for every plugin needs to be tied to the admin and require authentication, it could be accessed like http://localhost/mycms/admin/pages/add.

The problem is that the solution I found involves removing default routes and writing custom routing for every controller action inside the plugin modules like:

  $router->removeDefaultRoutes();

  $route = new Zend_Controller_Router_Route_Static(
      'admin/pages/add',
      array(
       'module' => 'pages',
       'controller' => 'Pages',
       'action' => 'add'
      )
  );

  $router->addRoute('pages_pages_add', $route);

  $route = new Zend_Controller_Router_Route_Regex(
      'pages/view/(\d+)',
      array(
       'module' => 'pages',
       'controller' => 'Pages',
       'action' => 'view'
      ),
      array(
       '1' => 'page_id'
      )
  );

  $router->addRoute('pages_pages_view', $route);

Do you have any ideas how I can avoid this custom routing?

Body:
Have a look at Front Controller Plugins, they may give you more flexibility...

http://framework.zend.com/manual/en/zend.controller.plugins.html

class Controller_Plugin_Foo extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch( Zend_Controller_Request_Abstract $request )
    {
        $frontController = Zend_Controller_Front::getInstance();
        ...
    }
}


问:
How to change the order of words with alphabetic order
I got a dataset with a list of keywords (1 keyword / row).

I m looking for a way to create a new column (ALPHABETICAL) based on the KEYWORD column. The value of the ALPHABETICAL column should be auto generated based on the keyword, but words should be ordered alphabetically.

Like this :

```<code> | KEYWORD            | ALPHABETICAL       |
 | house blue         | blue house         |
 | blue house         | blue house         |
 | my blue house      | blue house my      |
 | this house is blue | blue house is this |
 | sky orange         | orange sky         |
 | orange sky         | orange sky         |
 | the orange sky     | orange sky the     |
</code>```

Thanks for your help!

答:
```<code>df$ALPHABETICAL <- sapply(strsplit(df$KEYWORD," "),function(x) paste(sort(x),collapse=" "))

df
#              KEYWORD       ALPHABETICAL
# 1         house blue         blue house
# 2         blue house         blue house
# 3      my blue house      blue house my
# 4 this house is blue blue house is this
# 5         sky orange         orange sky
# 6         orange sky         orange sky
# 7     the orange sky     orange sky the
</code>```

data

```<code>df <- data.frame(KEYWORD = c(
  'house blue',
  'blue house',
  'my blue house',
  'this house is blue',
  'sky orange',
  'orange sky',
  'the orange sky'),stringsAsFactors = FALSE)
</code>```

Body:
I got a dataset with a list of keywords (1 keyword / row).

I m looking for a way to create a new column (ALPHABETICAL) based on the KEYWORD column. The value of the ALPHABETICAL column should be auto generated based on the keyword, but words should be ordered alphabetically.

Like this :

 | KEYWORD            | ALPHABETICAL       |
 | house blue         | blue house         |
 | blue house         | blue house         |
 | my blue house      | blue house my      |
 | this house is blue | blue house is this |
 | sky orange         | orange sky         |
 | orange sky         | orange sky         |
 | the orange sky     | orange sky the     |

Thanks for your help!

Body:
df$ALPHABETICAL <- sapply(strsplit(df$KEYWORD," "),function(x) paste(sort(x),collapse=" "))

df
#              KEYWORD       ALPHABETICAL
# 1         house blue         blue house
# 2         blue house         blue house
# 3      my blue house      blue house my
# 4 this house is blue blue house is this
# 5         sky orange         orange sky
# 6         orange sky         orange sky
# 7     the orange sky     orange sky the

data

df <- data.frame(KEYWORD = c(
  'house blue',
  'blue house',
  'my blue house',
  'this house is blue',
  'sky orange',
  'orange sky',
  'the orange sky'),stringsAsFactors = FALSE)


问:
Is there a way to use npm scripts to run tsc -watch && nodemon --watch?
I'm looking for a way to use npm scripts to run tsc --watch && nodemon --watch at the same time. I can run these commands independently, but when I want run both of them, only the first one is executed.
eg:

```<code>"scripts": {
    "runDeb": "set NODE_ENV=development&& tsc --watch && nodemon --watch"
  }
</code>```

tsc --watch is executed but nodemon is never called, and vice versa.

答:
I have been using AlterX's solution for a while now and it has worked perfectly, but I have found it to be rather slow. Instead, I am now using tsc-watch. It makes tsc use incremental compilation similar to the -w flag, making the restart of the application much faster.

It's as easy as putting something similar to this in your package.json:

```<code>"scripts": {
  "start": "tsc-watch --onSuccess \"node .\""
}
</code>```

Body:
I'm looking for a way to use npm scripts to run tsc --watch && nodemon --watch at the same time. I can run these commands independently, but when I want run both of them, only the first one is executed.
eg:

"scripts": {
    "runDeb": "set NODE_ENV=development&& tsc --watch && nodemon --watch"
  }

tsc --watch is executed but nodemon is never called, and vice versa.

Body:
I have been using AlterX's solution for a while now and it has worked perfectly, but I have found it to be rather slow. Instead, I am now using tsc-watch. It makes tsc use incremental compilation similar to the -w flag, making the restart of the application much faster.

It's as easy as putting something similar to this in your package.json:

"scripts": {
  "start": "tsc-watch --onSuccess \"node .\""
}


问:
How to send sms using Textlocal API?
I am trying to implement the send message functionality using third party api. API-https://api.txtlocal.com/send/

But when we are testing the implementation, we are facing an issue with error code 3 and giving a message as "invalid user details."

C# code:

```<code>string UserId = "1234";
    String message = HttpUtility.UrlEncode("OTP");
    using (var wb = new WebClient())
    {
        byte[] response = wb.UploadValues("https://api.txtlocal.com/send/", new NameValueCollection()
            {
            {"username" , "<TextLocal UserName>"},
            {"hash" , "<API has key>"},
            {"sender" , "<Unique sender ID>"},
            {"numbers" , "<receiver number>"},
            {"message" , "Text message"}
            });
        string result = System.Text.Encoding.UTF8.GetString(response);
        //return result;
</code>```

Error Details:

```<code> {
    "errors": [{
        "code": 3,
        "message": "Invalid login details"
    }],
    "status": "failure"
}
</code>```

Even though I am passing valid credentials.

Please assist me and let me know in case you require any more details.

Thanks and appreciate your help in advance.

答:
I believe you should either send the API Key OR the username and password.

Remove the username from your request and just leave the API key, sender, numbers and message. All should work OK then.

Title: How to send sms using Textlocal API?

Body:
I am trying to implement the send message functionality using third party api. API-https://api.txtlocal.com/send/

But when we are testing the implementation, we are facing an issue with error code 3 and giving a message as "invalid user details."

C# code:

string UserId = "1234";
    String message = HttpUtility.UrlEncode("OTP");
    using (var wb = new WebClient())
    {
        byte[] response = wb.UploadValues("https://api.txtlocal.com/send/", new NameValueCollection()
            {
            {"username" , "<TextLocal UserName>"},
            {"hash" , "<API has key>"},
            {"sender" , "<Unique sender ID>"},
            {"numbers" , "<receiver number>"},
            {"message" , "Text message"}
            });
        string result = System.Text.Encoding.UTF8.GetString(response);
        //return result;

Error Details:

 {
    "errors": [{
        "code": 3,
        "message": "Invalid login details"
    }],
    "status": "failure"
}

Even though I am passing valid credentials.

Please assist me and let me know in case you require any more details.

Thanks and appreciate your help in advance.