问:
Pseudo-WYSIWYG Emacs
With just the few lines in a file file.adoc

```<code>////
-*-iimage-mode-*-
////

.A PNG smiley
image::smiley.png[]
</code>```

I can generate HTML using asciidoctor and MS-word .doc using pandoc.
This toolchain doesn't handle SVG, and so it's not perfect, but it works well, and
it's free.

file.html

There is a snag though:

I'd like iimage-mode to be enabled when I load file.adoc. My attempt (the first three lines in the source above) doesn't work. Can you think of a way that will?

.emacs

```<code>(set-foreground-color "white")
(set-background-color "black")

(require 'adoc-mode)
(setq auto-mode-alist (cons '("\\.adoc\\'" . adoc-mode) auto-mode-alist))
</code>```

Comments

I am writing these comments here to be able to typeset.

Asciidoctor
(I'm using to the superior implementation of the asciidoc syntax written in Ruby) does have (now?) line comments in addition to block comments.

Using

// -- mode: iimage --

on the first line works (thanks, Nick). But it replaces the adoc major mode (thanks, phils).

Adding at the bottom of the file:

//// Local Variables:

eval: (iimage-mode 1)

End:

////

switches to minor mode iimage while the major mode remains adoc.

phils's suggestion to use my-adoc-mode-hook works well.

I'm forking the second part to a separate question. This discussion is already long enough for one question.

Update

Using asciidoctor + pandoc may produce a .doc file that is handled correctly with a recent version of MS-Word. Comments welcome. MS-Word 2011 on OS X opens the resulting .doc file fine, but shows an error message in the place of SVG images.

If this works, it will (finally) be a way to send a .doc file to all those people who insist on them, while editing in an environment as flexible as Emacs.

答:
I tried with a JPG that I had lying around and I don't get any artifacts at all.

The spec is -*- mode: iimage -*- and it's got to be on the first line of the file (it can be on the second if the first line specifies an interpreter, e.g. #! /bin bash).

If that does not work for you, you can use a file variable at the end of the file:

```<code>//// Local Variables:
//// mode: iimage
//// End:
</code>```

See File Variables.

EDIT: See @phils's answer for a more correct description of how to handle minor modes.

Title: Pseudo-WYSIWYG Emacs

Body:
With just the few lines in a file file.adoc

////
-*-iimage-mode-*-
////

.A PNG smiley
image::smiley.png[]

I can generate HTML using asciidoctor and MS-word .doc using pandoc.
This toolchain doesn't handle SVG, and so it's not perfect, but it works well, and
it's free.

file.html

There is a snag though:

I'd like iimage-mode to be enabled when I load file.adoc. My attempt (the first three lines in the source above) doesn't work. Can you think of a way that will?

.emacs

(set-foreground-color "white")
(set-background-color "black")

(require 'adoc-mode)
(setq auto-mode-alist (cons '("\\.adoc\\'" . adoc-mode) auto-mode-alist))

Comments

I am writing these comments here to be able to typeset.

Asciidoctor
(I'm using to the superior implementation of the asciidoc syntax written in Ruby) does have (now?) line comments in addition to block comments.

Using

// -- mode: iimage --

on the first line works (thanks, Nick). But it replaces the adoc major mode (thanks, phils).

Adding at the bottom of the file:

//// Local Variables:

eval: (iimage-mode 1)

End:

////

switches to minor mode iimage while the major mode remains adoc.

phils's suggestion to use my-adoc-mode-hook works well.

I'm forking the second part to a separate question. This discussion is already long enough for one question.

Update

Using asciidoctor + pandoc may produce a .doc file that is handled correctly with a recent version of MS-Word. Comments welcome. MS-Word 2011 on OS X opens the resulting .doc file fine, but shows an error message in the place of SVG images.

If this works, it will (finally) be a way to send a .doc file to all those people who insist on them, while editing in an environment as flexible as Emacs.

Body:
I tried with a JPG that I had lying around and I don't get any artifacts at all.

The spec is -*- mode: iimage -*- and it's got to be on the first line of the file (it can be on the second if the first line specifies an interpreter, e.g. #! /bin bash).

If that does not work for you, you can use a file variable at the end of the file:

//// Local Variables:
//// mode: iimage
//// End:

See File Variables.

EDIT: See @phils's answer for a more correct description of how to handle minor modes.


来源: stackexchange

问:
Change parameters in Convolution neural network
I'm praticing CNNs. I read some papers about training MNIST dataset use CNNs.size of image is 28x28 and use architecture 5 layers: input>conv1-maxpool1>conv2-maxpool2>fully connected>output

```<code>Convolutional Layer #1
- Computes 32 features using a 5x5 filter with ReLU activation.
- Padding is added to preserve width and height.
- Input Tensor Shape: [batch_size, 28, 28, 1]
- Output Tensor Shape: [batch_size, 28, 28, 32]
Pooling Layer #1
- First max pooling layer with a 2x2 filter and stride of 2
- Input Tensor Shape: [batch_size, 28, 28, 32]
- Output Tensor Shape: [batch_size, 14, 14, 32]
Convolutional Layer #2
- Computes 64 features using a 5x5 filter.
- Padding is added to preserve width and height.
- Input Tensor Shape: [batch_size, 14, 14, 32]
- Output Tensor Shape: [batch_size, 14, 14, 64]
Pooling Layer #2
- Second max pooling layer with a 2x2 filter and stride of 2
- Input Tensor Shape: [batch_size, 14, 14, 64]
- Output Tensor Shape: [batch_size, 7, 7, 64]
Flatten tensor into a batch of vectors
- Input Tensor Shape: [batch_size, 7, 7, 64]
- Output Tensor Shape: [batch_size, 7 * 7 * 64]
Fully Connected Layer
- Densely connected layer with 1024 neurons
- Input Tensor Shape: [batch_size, 7 * 7 * 64]
- Output Tensor Shape: [batch_size, 1024] Output layer
- Input Tensor Shape: [batch_size, 1024]
- Output Tensor Shape: [batch_size, 10]
</code>```

In conv1, with 1 input computates 32 features using a 5x5 filter and in conv2 with 32 input from conv1 computates 64 features using same filter. What are parameters such as 32,64,2x2 filter chosen based on? Do they based on size of image?

If size of images is larger than 28x28 such as 128x128. Should I increse the number of layers over 5 layers? How are above parameters changed with other size of images?

Thank advance

答:
At it's base level, those inputs are called HyperParameters and are not typically defined by any particular set of rules. That said, often we use rules of thumb (heuristics) to choose a set of hyper parameters and then use hyperparameter optimisation to increase performance or efficiency etc.

A great explanation of this is Here

Edit:
Further info in this paper - it's a widely studied problem, look into Arxiv and Stats.Stackexchange for more info but here is a great paper I used when I was learning Here

ContentLicense: CC BY-SA 3.0

Body:
I'm praticing CNNs. I read some papers about training MNIST dataset use CNNs.size of image is 28x28 and use architecture 5 layers: input>conv1-maxpool1>conv2-maxpool2>fully connected>output

Convolutional Layer #1
- Computes 32 features using a 5x5 filter with ReLU activation.
- Padding is added to preserve width and height.
- Input Tensor Shape: [batch_size, 28, 28, 1]
- Output Tensor Shape: [batch_size, 28, 28, 32]
Pooling Layer #1
- First max pooling layer with a 2x2 filter and stride of 2
- Input Tensor Shape: [batch_size, 28, 28, 32]
- Output Tensor Shape: [batch_size, 14, 14, 32]
Convolutional Layer #2
- Computes 64 features using a 5x5 filter.
- Padding is added to preserve width and height.
- Input Tensor Shape: [batch_size, 14, 14, 32]
- Output Tensor Shape: [batch_size, 14, 14, 64]
Pooling Layer #2
- Second max pooling layer with a 2x2 filter and stride of 2
- Input Tensor Shape: [batch_size, 14, 14, 64]
- Output Tensor Shape: [batch_size, 7, 7, 64]
Flatten tensor into a batch of vectors
- Input Tensor Shape: [batch_size, 7, 7, 64]
- Output Tensor Shape: [batch_size, 7 * 7 * 64]
Fully Connected Layer
- Densely connected layer with 1024 neurons
- Input Tensor Shape: [batch_size, 7 * 7 * 64]
- Output Tensor Shape: [batch_size, 1024] Output layer
- Input Tensor Shape: [batch_size, 1024]
- Output Tensor Shape: [batch_size, 10]

In conv1, with 1 input computates 32 features using a 5x5 filter and in conv2 with 32 input from conv1 computates 64 features using same filter. What are parameters such as 32,64,2x2 filter chosen based on? Do they based on size of image?

If size of images is larger than 28x28 such as 128x128. Should I increse the number of layers over 5 layers? How are above parameters changed with other size of images?

Thank advance


问:
Calculate the percentage for python dictionary
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

```<code>from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()
</code>```

Body:
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()

Body:
you can use list comp.

In[2]: my_dict = {key: key for key in range(5)}
In[3]: values = my_dict.values()
In[4]: values
Out[4]: [0, 1, 2, 3, 4]
In[5]: total = sum(values)
In[6]: new = [value * 100. / total for value in values]
In[7]: new
Out[7]: [0.0, 10.0, 20.0, 30.0, 40.0]

or you can use np.array

In[8]: import numpy as np
In[9]: x = np.array([1, 2, 3, 4])
In[10]: x
Out[10]: array([1, 2, 3, 4])
In[11]: x/3.4
Out[11]: array([ 0.29411765,  0.58823529,  0.88235294,  1.17647059])


问:
Ffmpeg on Windows: use mp3 as audio codec to create mp4 files
I'm using ffmpeg on Windows to create mp4 files for web distribution. As libfaac isn't available, I use libmp3lame to encode the audio tracks. The mp4 are played back with a falsh player (JWPlayer)

I was wondering if there were any shortcomings to use mp3 instead of aac on certain devices?

答: If JWPlayer can handle it, it's fine. MP3 is a more open and portable format to begin with.</p>

ContentLicense: CC BY-SA 2.5


问:
How do I iterate over a list of URLs to extract JSON data
I have MS SQL Server (2014) and what I need is to pull a bunch of JSON metadata off a web API.  Unfortunately the API is limited to returning only 30 records (and I have 7400 records to pull).  So I was going to just iterate over a bunch of URLs and import the data but I got stuck.

I have imported JSON data into SQL Server in the past adapting this method (Passing filename as variable in OPENROWSET(BULK filename)) and using parseJSON

This method works fine if I have the data local to my machine (e.g. on my C drive) but does not work when I use the URL - I get the following error:

```<code>(1 row(s) affected)
Msg 4861, Level 16, State 1, Line 1
Cannot bulk load because the file "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow" could not be opened. Operating system error code 123(The filename, directory name, or volume label syntax is incorrect.).
Msg 8115, Level 16, State 2, Line 45
Arithmetic overflow error converting expression to data type nvarchar.
</code>```

How can I fix my code to work with a file on the internet?

```<code>--    SET @JSON_FILE= 'C:\Temp\SO.json'  --  If I save the data on my harddrive the following code works.
    SET @JSON_FILE= 'https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow'

    /* http://www.sqlservercentral.com/Forums/Topic982066-338-1.aspx
    Read the JSON file into the varchar variable.  This is done via a bulk insert using the OPENROWSET() function.   Because this stored proc is to be re-used with different JSON files, ideally you want to pass the JSON file path as a variable.  However, because the OPENROWSET() function won't accept variables as a parameter, the command needs to be built as a string and then passed to the sp_executesql system stored procedure.  The results are then passed back by an output variable.
    */
    -- Setup varchar variable to be used to hold contents of JSON file.
    DECLARE @txt varchar(max)

    -- The command line
    DECLARE @COMMAND NVARCHAR(MAX)
    -- The definition of the parameters used within the command line
    DECLARE @PARAM_DEF NVARCHAR(500)
    -- The parameter used to pass the file name into the command
    DECLARE @FILEVAR NVARCHAR(MAX)
    -- The output variable that holds the results of the OPENROWSET()
    DECLARE @JSON_OUT VARCHAR(MAX)

    SET @FILEVAR = @JSON_FILE
    SET @PARAM_DEF = N'@JSON_FILE NVARCHAR(MAX), @JSON_OUT VARCHAR(MAX) OUTPUT'
    SET @COMMAND = N'SELECT @JSON_OUT = BulkColumn FROM OPENROWSET(BULK ''' +  @JSON_FILE + ''', SINGLE_BLOB) ROW_SET';

    EXEC sp_executesql @COMMAND, @PARAM_DEF, @JSON_FILE = @FILEVAR, @JSON_OUT = @txt OUTPUT;
    --parseJSON function from https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/
    SELECT * FROM parseJSON(@txt)
</code>```

答:
It turns out it was infinitely easier just to use Microsoft Powershell to download all the JSONs and then just use my code to import the data in.

I set up a simple spreadsheet with

Column A going from 1 to the end,

Column B adding 30 to the sequence

Column C to a formula that makes the URL string =CONCAT("$resource",A2,"='myURL/retrieve.php?query=&coll=cxr&m=",B2,"&n=",B2+30,"'")

Column D then queries the site with the URL string  =CONCAT(" Invoke-RestMethod -Method Get -Uri $resource",A2,"  -Outfile ",A2,".json")

Then I just copy/paste all of Column C (to seed $resourceN) then copy/paste Column D to download the JSON to be injested into SQL.

Body:
I have MS SQL Server (2014) and what I need is to pull a bunch of JSON metadata off a web API.  Unfortunately the API is limited to returning only 30 records (and I have 7400 records to pull).  So I was going to just iterate over a bunch of URLs and import the data but I got stuck.

I have imported JSON data into SQL Server in the past adapting this method (Passing filename as variable in OPENROWSET(BULK filename)) and using parseJSON

This method works fine if I have the data local to my machine (e.g. on my C drive) but does not work when I use the URL - I get the following error:

(1 row(s) affected)
Msg 4861, Level 16, State 1, Line 1
Cannot bulk load because the file "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow" could not be opened. Operating system error code 123(The filename, directory name, or volume label syntax is incorrect.).
Msg 8115, Level 16, State 2, Line 45
Arithmetic overflow error converting expression to data type nvarchar.

How can I fix my code to work with a file on the internet?

--    SET @JSON_FILE= 'C:\Temp\SO.json'  --  If I save the data on my harddrive the following code works.
    SET @JSON_FILE= 'https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow'

    /* http://www.sqlservercentral.com/Forums/Topic982066-338-1.aspx
    Read the JSON file into the varchar variable.  This is done via a bulk insert using the OPENROWSET() function.   Because this stored proc is to be re-used with different JSON files, ideally you want to pass the JSON file path as a variable.  However, because the OPENROWSET() function won't accept variables as a parameter, the command needs to be built as a string and then passed to the sp_executesql system stored procedure.  The results are then passed back by an output variable.
    */
    -- Setup varchar variable to be used to hold contents of JSON file.
    DECLARE @txt varchar(max)

    -- The command line
    DECLARE @COMMAND NVARCHAR(MAX)
    -- The definition of the parameters used within the command line
    DECLARE @PARAM_DEF NVARCHAR(500)
    -- The parameter used to pass the file name into the command
    DECLARE @FILEVAR NVARCHAR(MAX)
    -- The output variable that holds the results of the OPENROWSET()
    DECLARE @JSON_OUT VARCHAR(MAX)

    SET @FILEVAR = @JSON_FILE
    SET @PARAM_DEF = N'@JSON_FILE NVARCHAR(MAX), @JSON_OUT VARCHAR(MAX) OUTPUT'
    SET @COMMAND = N'SELECT @JSON_OUT = BulkColumn FROM OPENROWSET(BULK ''' +  @JSON_FILE + ''', SINGLE_BLOB) ROW_SET';

    EXEC sp_executesql @COMMAND, @PARAM_DEF, @JSON_FILE = @FILEVAR, @JSON_OUT = @txt OUTPUT;
    --parseJSON function from https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/
    SELECT * FROM parseJSON(@txt)


问:
Cucumber Java - How to use returned String from a step in next step?
I need to automate some webservices, i create some methods for that and i want to use Cucumber for that but i can't figure how to use returned value in next step.

So, i have this Feature:

```<code>Feature: Create Client and place order

  Scenario: Syntax
    Given I create client type: "66"
    And I create for client: "OUTPUTVALUEfromGiven" an account type "123"
    And I create for client: "OUTPUTVALUEfromGiven" an account type "321"
    And I want to place order for: "outputvalueFromAnd1"
</code>```

and i have this Steps:

```<code>public class CreateClientSteps {

@Given("^I create client type: \"([^\"]*)\"$")
public static String iCreateClient(String clientType) {

    String clientID = "";
    System.out.println(clientType);
    try {
      clientID = util.createClient(clientType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return clientID;

}

@And("^I create for client: \"([^\"]*)\" an account type \"([^\"]*)\"$")
public static String createAccount(String clientID, String accountType) {

    String orderID = "";
    try {
        orderID = util.createAccount(clientID,accountType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return orderID;
    }
}
</code>```

It's any way to use the returned values from step to step?

Thank you!

答:
Sharing state between steps, which is how I interpret your question, is not done by examining a returned value. It is done by setting the value in an instance variable and later read that instance variable in another step.

I would change your steps to this in order to achieve that:

```<code>public class CreateClientSteps {
    private String clientID;
    private String orderID;

    @Given("^I create client type: \"([^\"]*)\"$")
    public void iCreateClient(String clientType) {
        System.out.println(clientType);
        try {
            clientID = util.createClient(clientType);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @And("^I create for client: \"([^\"]*)\" an account type \"([^\"]*)\"$")
    public void createAccount(String clientID, String accountType) {
        try {
            orderID = util.createAccount(clientID, accountType);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

The things I changed are

Two fields for sharing state - other steps can read the values later

Non static methods - Cucumber recreates the step class for every scenario, therefore I don't want the fields to be static since that would mean that their values would leak between scenarios

This is how you share state between steps in the same class. Sharing state between steps in different classes can also be done. It is a bit more complicated. Ask if you are interested.

Body:
I need to automate some webservices, i create some methods for that and i want to use Cucumber for that but i can't figure how to use returned value in next step.

So, i have this Feature:

Feature: Create Client and place order

  Scenario: Syntax
    Given I create client type: "66"
    And I create for client: "OUTPUTVALUEfromGiven" an account type "123"
    And I create for client: "OUTPUTVALUEfromGiven" an account type "321"
    And I want to place order for: "outputvalueFromAnd1"

and i have this Steps:

public class CreateClientSteps {

@Given("^I create client type: \"([^\"]*)\"$")
public static String iCreateClient(String clientType) {

    String clientID = "";
    System.out.println(clientType);
    try {
      clientID = util.createClient(clientType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return clientID;

}

@And("^I create for client: \"([^\"]*)\" an account type \"([^\"]*)\"$")
public static String createAccount(String clientID, String accountType) {

    String orderID = "";
    try {
        orderID = util.createAccount(clientID,accountType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return orderID;
    }
}

It's any way to use the returned values from step to step?

Thank you!

Body:
Sharing state between steps, which is how I interpret your question, is not done by examining a returned value. It is done by setting the value in an instance variable and later read that instance variable in another step.

I would change your steps to this in order to achieve that:

public class CreateClientSteps {
    private String clientID;
    private String orderID;

    @Given("^I create client type: \"([^\"]*)\"$")
    public void iCreateClient(String clientType) {
        System.out.println(clientType);
        try {
            clientID = util.createClient(clientType);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @And("^I create for client: \"([^\"]*)\" an account type \"([^\"]*)\"$")
    public void createAccount(String clientID, String accountType) {
        try {
            orderID = util.createAccount(clientID, accountType);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The things I changed are

Two fields for sharing state - other steps can read the values later

Non static methods - Cucumber recreates the step class for every scenario, therefore I don't want the fields to be static since that would mean that their values would leak between scenarios

This is how you share state between steps in the same class. Sharing state between steps in different classes can also be done. It is a bit more complicated. Ask if you are interested.


问:
Setting Xcode linker up correctly: library not found, but in "Link Binary With Libraries" list
I have a issue with dependencies in my dylibs.

I currently get the follwing error message:

```<code>dyld: Library not loaded: /opt/local/lib/libgvc.6.dylib
  Referenced from: /Users/klauskneupner/Library/Developer/Xcode/DerivedData/Visual_Thinking-bvgfcqjwnobabodenabpggrwnoet/Build/Products/Debug/Visual Thinking.app/Contents/Frameworks/libgvplugin_dot_layout.6.dylib
  Reason: image not found
</code>```

The funny part is that I have that library (libgvc.6) in the list of dependencies.

But in this case, the libgvc.6 is in a project directory and not in /opt/local/lib.

What do I need to do? Many thanks in advance!

答:
At build time the static linker on OS X, ld, writes the shared library identifier of each library that your application links against in to the application binary. At run time the dynamic linker, dyld, attempts to load each shared library from the paths specified in the application binary. You can see this information using otool -L YourApp.app/Contents/MacOS/YourApp.

The reference to /opt/local/lib/libgvc.6.dylib in your crash output indicates that is the shared library identifier of libgvc.6.dylib in your project. To include the library in your .app bundle in a way that your application will use it rather than looking in /opt/local/lib you need to:

Change the shared library identifier of libgvc.6.dylib so that dyld will look for the binary within your application bundle. This is typically done by running install_name_tool -id @rpath/libgvc.6.dylib libgvc.6.dylib. The @rpath placeholder tells dyld to try substituting each of the entries in the runpath search path of the binary that is loading the library. By default your app bundle's Frameworks directory is on this search path.

Update any existing prebuilt libraries that link to libgvc.6.dylib to refer to it via the new name (the change made in step 1 only takes effect when a new binary is built against the library, so it may not be necessary if it is only prebuilt libraries that link against it). You can use install_name_tool -change /opt/local/lib/libgvc.6.dylib @rpath/libgvc.6.dylib path/to/other.dylib to update these other libraries. Your crash output shows that libgvplugin_dot_layout.6.dylib is one such library that would need updated. It may not be the only one.

Ensure that your modified libraries are being copied in to the Frameworks subdirectory in your application bundle. This is typically done using a Copy Files build phase in your Xcode project.

Body:
I have a issue with dependencies in my dylibs.

I currently get the follwing error message:

dyld: Library not loaded: /opt/local/lib/libgvc.6.dylib
  Referenced from: /Users/klauskneupner/Library/Developer/Xcode/DerivedData/Visual_Thinking-bvgfcqjwnobabodenabpggrwnoet/Build/Products/Debug/Visual Thinking.app/Contents/Frameworks/libgvplugin_dot_layout.6.dylib
  Reason: image not found

The funny part is that I have that library (libgvc.6) in the list of dependencies.

But in this case, the libgvc.6 is in a project directory and not in /opt/local/lib.

What do I need to do? Many thanks in advance!


问:
Change image with MouseOver
I'm new to javascript and Html , Typed a code that changes the image when the mouse hovers over, it works but i was wondering if there is any better solution because it is very long and repetitive ;
Here is the code : </p>

```<code><doctype html>
<html>
<head>
</head>
<body>
    <table>
        <tr>
            <td>
                <img src="image1.jpg" height="200px" width="300px"
onmouseover="rollover(this)" onmouseout="mouseaway(this)/>
            </td>
            <td>
                <img src="image2.jpg" height="200px" width="300px"
onmouseover="rollover1(this)" onmouseout="mouseaway1(this)"/>
            </td>
        </tr>
        <tr>
            <td>
                <img src="image3.jpg" height="200px" width="300px"
onmouseover="rollover2(this)" onmouseout="mouseaway2(this)"/>
            </td>
            <td>
                <img src="image4.jpg" height="200px" width="300px"
onmouseover="rollover3(this)" onmouseout="mouseaway3(this)"/>
            </td>
        </tr>
    </table>
<script language="javascript">
function rollover(img1)
{
    img1.src = 'image2.jpg';
}
function mouseaway(img1)
{
    img1.src = "image1.jpg";
}
function rollover1(img2)
{
    img2.src='image3.jpg';
}
function mouseaway1(img2)
{
    img2.src='image2.jpg'
}
function rollover2(img3)
{
    img3.src='image4.jpg';
}
function mouseaway2(img3)
{
    img3.src='image3.jpg'
}
function rollover3(img4)
{
    img4.src='image1.jpg';
}
function mouseaway3(img4)
{
    img4.src='image4.jpg'
}

</script>
</body>
</html>
</code>```

答:
You could store all the information required in each image tag, that way you wouldn't have to create extra functions for each one.

For example

document.addEventListener('DOMContentLoaded', () => {
  Array.from(document.querySelectorAll('img[data-src-enter]')).forEach(img => {
    img.setAttribute('data-src-out', img.src)
    img.addEventListener('mouseenter', () => {
      img.src = img.getAttribute('data-src-enter')
    }, false)
    img.addEventListener('mouseout', () => {
      img.src = img.getAttribute('data-src-out')
    }, false)
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  <img src="http://lorempixel.com/50/50/cats/1/" data-src-enter="http://lorempixel.com/50/50/cats/2/">
</p>
<p>
  <img src="http://lorempixel.com/50/50/cats/3/" data-src-enter="http://lorempixel.com/50/50/cats/4/">
</p></code>```

Title: Change image with MouseOver

Body:
I'm new to javascript and Html , Typed a code that changes the image when the mouse hovers over, it works but i was wondering if there is any better solution because it is very long and repetitive ;
Here is the code :

<doctype html>

Body:
You could store all the information required in each image tag, that way you wouldn't have to create extra functions for each one.

For example

document.addEventListener('DOMContentLoaded', () => {
  Array.from(document.querySelectorAll('img[data-src-enter]')).forEach(img => {
    img.setAttribute('data-src-out', img.src)
    img.addEventListener('mouseenter', () => {
      img.src = img.getAttribute('data-src-enter')
    }, false)
    img.addEventListener('mouseout', () => {
      img.src = img.getAttribute('data-src-out')
    }, false)
  })
})

<p>
  <img src="http://lorempixel.com/50/50/cats/1/" data-src-enter="http://lorempixel.com/50/50/cats/2/">
</p>
<p>
  <img src="http://lorempixel.com/50/50/cats/3/" data-src-enter="http://lorempixel.com/50/50/cats/4/">
</p>


问:
Signed document retrieval and envelope creation using Docusign API
We have been checking DocuSign APIs through your sandbox for the integration with our App. Currently we are facing issues where we are stuck.

Would you please advise how we can retrieve the signed document through API? We found that once we signed a document the sigining URL seems to be expired and we couldn't find any other URL or anything to retrieve the signed document from our App programmatically?

We are trying to integrate DocuSign with our hybrid mobile app and we saw in your documentation that you are not recommending iFrame. But if we need to implement the functionality for adding signature fields, or text boxes on the fly by using your APIs, we need to have the events in our page for those and we should use iFrame in such cases.

So please let me know whether there is any other way through which you are providing us controls to be dragged to the envelope (like control palette) when we take it in our app?

答:
You can retrieve the documents in an envelope using the getEnvelopeDocuments api.

```<code>GET /v2/accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}
</code>```

For integrating DocuSign into your mobile app look at Docusign embedded sending. You can find more information for optimizing embedded workflows here

Body:
You can retrieve the documents in an envelope using the getEnvelopeDocuments api.

GET /v2/accounts/{accountId}/envelopes/{envelopeId}/documents/{documentId}

For integrating DocuSign into your mobile app look at Docusign embedded sending. You can find more information for optimizing embedded workflows here


问:
how to put white space and change date format in View on MVC ?
I am developing MVC application and using razor syntax.

In this application I am giving comment facility.

Currently the comments look like...

```<code>P Moris9/15/2012 5:40:44 PM
Test comment 1

P Moris9/15/2012 5:40:44 PM
Test comment 2

P moris9/15/2012 5:40:45 PM
Test comment 3
</code>```

Now, I wan to put space between Name of the comment owner and the datetime.
As well How do I convert dateTime in to

dd-MMM-yy hh:mm tt ?

The Comment should be look like ...

P Moris       17 Sept 2012 05:45 PM.

Test comment 1

(I cant give more than one space in above sample...its automatically remove the space.)

How should I ?

My code in View is

```<code> @foreach (var item in Model)
    {
        <div id="OwnerName">

         <span class="EmpName"> @Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { @style = "color:#1A6690;" })</span>

           @Html.DisplayFor(ModelItem => item.CommentDateTime)

        </div>

        <p class="CommentP">
           @Html.DisplayFor(ModelItem => item.CommentText)
        </p>

        <br />

    }
</code>```

答:
For  white space  use  below  code </p>

```<code>@{
  @:
}
</code>```

Body:
I am developing MVC application and using razor syntax.

In this application I am giving comment facility.

Currently the comments look like...

P Moris9/15/2012 5:40:44 PM
Test comment 1

P Moris9/15/2012 5:40:44 PM
Test comment 2

P moris9/15/2012 5:40:45 PM
Test comment 3

Now, I wan to put space between Name of the comment owner and the datetime.
As well How do I convert dateTime in to

dd-MMM-yy hh:mm tt ?

The Comment should be look like ...

P Moris       17 Sept 2012 05:45 PM.

Test comment 1

(I cant give more than one space in above sample...its automatically remove the space.)

How should I ?

My code in View is

 @foreach (var item in Model)
    {

          @Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { @style = "color:#1A6690;" })

           @Html.DisplayFor(ModelItem => item.CommentDateTime)

           @Html.DisplayFor(ModelItem => item.CommentText)

    }

Body:
For  white space  use  below  code

@{
  @:  &nbsp;&nbsp;
}


问:
Getting error in button position change in swift 3
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here</p>

```<code>if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }
</code>```

答:
```<code>var newRect: CGRect = nextBtn.frame

newRect.origin.x = newRect.origin.x - 100 // do whatever you want either + or -
newRect.origin.y = newRect.origin.y - 100 // do whatever you want either + or -

nextBtn.frame = newRect
</code>```

Body:
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here

if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }


答:
All the above answers are good. I just want to add you could also use data-* attributes.

```<code><img src="image1.jpg" height="200px" width="300px" onmouseover="rollover(this)" onmouseout="mouseaway(this)" data-hover-img="image1.jpg" data-normal-img="image2.jpg" />
</code>```

In JS:

```<code>function rollover(img)
{

     img.src = this.dataset.hoverImg;

 }
function mouseaway(img)
{

   img.src = this.dataset.normalImg;

}
</code>```

Title: Change image with MouseOver

Body:
All the above answers are good. I just want to add you could also use data-* attributes.

<img src="image1.jpg" height="200px" width="300px" onmouseover="rollover(this)" onmouseout="mouseaway(this)" data-hover-img="image1.jpg" data-normal-img="image2.jpg" />

In JS:

function rollover(img)
{

     img.src = this.dataset.hoverImg;

 }
function mouseaway(img)
{

   img.src = this.dataset.normalImg;

}


问:
How to set Immutable Id of an MSOlUser to null value using powershell?
I have tried the following command to set the immutable id of a user in Office 365

```<code> Set-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in -ImmutableId $null
</code>```

But when i try the following command it is actually returning an immutable id

```<code>Get-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in | select ImmutableId
</code>```

Please let me know if there is some other way to set the immutable id to null?

答:
```<code>Set-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in -ImmutableId "$null"
</code>```

While executing the above command I got the following error:

You must provide a required property: Parameter name:
FederatedUser.SourceAnchor

While digging deep into the issue I got to know that we cannot clear immutable Id from a federated O365 account, instead we need to do the following:

Move the federated domain onto a managed domain:

```<code>Set-MsolUserPrincipalName -UserPrincipalName edwardlt501edwar@KT2.kb.co.in  -NewUserPrincipalName edwardlt501edwar@<managed domain, usually something.onmicrosoft.com>
</code>```

Set immutableid to null:

```<code>Set-MsolUser -UserPrincipalName gw17edwardlt501edwar@<managed domain> -ImmutableId "$null"
</code>```

Then wait for some time and assign a new immutable id:

```<code>set-msolUser -userprincipalname gw17edwardlt501edwar@<managed domain> -immutableID f33fc1d2-73bd-4957-995f-37c83d349ef3
</code>```

Move back to federated domain:

```<code>Set-MsolUserPrincipalName -NewUserPrincipalName edwardlt501edwar@KT2.kb.co.in-UserPrincipalName edwardlt501edwar@<managed domain>
</code>```

See the new immutable ID:

```<code>Get-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in | select ImmutableId
</code>```

Body:
I have tried the following command to set the immutable id of a user in Office 365

 Set-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in -ImmutableId $null

But when i try the following command it is actually returning an immutable id

Get-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in | select ImmutableId

Please let me know if there is some other way to set the immutable id to null?

Body:
Set-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in -ImmutableId "$null"

While executing the above command I got the following error:

You must provide a required property: Parameter name:
FederatedUser.SourceAnchor

While digging deep into the issue I got to know that we cannot clear immutable Id from a federated O365 account, instead we need to do the following:

Move the federated domain onto a managed domain:

Set-MsolUserPrincipalName -UserPrincipalName edwardlt501edwar@KT2.kb.co.in  -NewUserPrincipalName edwardlt501edwar@<managed domain, usually something.onmicrosoft.com>

Set immutableid to null:

Set-MsolUser -UserPrincipalName gw17edwardlt501edwar@<managed domain> -ImmutableId "$null"

Then wait for some time and assign a new immutable id:

set-msolUser -userprincipalname gw17edwardlt501edwar@<managed domain> -immutableID f33fc1d2-73bd-4957-995f-37c83d349ef3

Move back to federated domain:

Set-MsolUserPrincipalName -NewUserPrincipalName edwardlt501edwar@KT2.kb.co.in-UserPrincipalName edwardlt501edwar@<managed domain>

See the new immutable ID:

Get-MsolUser -UserPrincipalName edwardlt501edwar@KT2.kb.co.in | select ImmutableId


问:
Is there a sleep() function for Android NDK?
Under Android NDK, is there a sleep() function which sleeps for X miliseconds, but do not block the event loop?

We are writing API tests to work on Mac, Windows, and Android. So far, we have implemented some sort of sleep() for Mac and Windows, but we are all new to Android NDK and need some help there. Thank you in advance.

答: So you are looking for a sleep() method that does sleep for a certain amount of time but does not block the event loop? This sounds odd to me. I think you might want to use a new thread instead and call the sleep() method there - without having to use any JNI.


问:
Outputting the product html price increased of 20%
In WooCommerce, I am trying to output the product html price increased of 20% using this code:

```<code>echo $product->get_price_html(); // +20%
</code>```

I have tried for a long time to get it working but unfortunately I cannot do so.

How can I achieve that?

Thanks

答:
First you have to know that the variable $product is an instance of WC_Product class, that will allow you to apply to it any methods from this WC_Product class.

You can use WC_Product method get_price() and WC_Product method adjust_price() this way:

```<code>// Get the numerical (float) price value
$product_price = (float) $product->get_price();

// calculate 20% of product price
$add_to_price = $product_price * 0.2;

// Adjust the new displayed price
$product->adjust_price( $add_to_price );

// Displaying the new adjusted price html
echo $product->get_price_htm();
</code>```

So now you finally get the html product price output increased of 20% simply reusing WC_Product get_price_html() method…

Body:
In WooCommerce, I am trying to output the product html price increased of 20% using this code:

echo $product->get_price_html(); // +20%

I have tried for a long time to get it working but unfortunately I cannot do so.

How can I achieve that?

Thanks

Body:
First you have to know that the variable $product is an instance of WC_Product class, that will allow you to apply to it any methods from this WC_Product class.

You can use WC_Product method get_price() and WC_Product method adjust_price() this way:

// Get the numerical (float) price value
$product_price = (float) $product->get_price();

// calculate 20% of product price
$add_to_price = $product_price * 0.2;

// Adjust the new displayed price
$product->adjust_price( $add_to_price );

// Displaying the new adjusted price html
echo $product->get_price_htm();

So now you finally get the html product price output increased of 20% simply reusing WC_Product get_price_html() method…


问:
How to get date more than 14 days base on date in column?
Example: Claim Date = 14/3/2017 And today was 29/3/2017 it was more than 14 days.
I've tried DATEDIFF in Mysql it keep showing error somehow.

```<code>Example Table:
Table Name:
**ec_claims**
ec_claims_id Primaryint(11)
ec_claims_date  date
</code>```

CODE:

```<code>SELECT DATEDIFF(NOW(),ec_claims_date) AS DAYGAP FROM ec_claims
WHERE DAYGAP >= 14
</code>```

Error:

```<code>#1054 - Unknown column 'DAYGAP' in 'where clause'
</code>```

Thank You For Reading This.

答:
WHERE clause does not allow the use of aliases.

You can either use your entire expression without the alias in the where clause, like:

```<code>SELECT DATEDIFF(NOW(),ec_claims_date) AS DAYGAP FROM ec_claims
WHERE DATEDIFF(NOW(),ec_claims_date) >= 14
</code>```

or alternatively, you can use HAVING in place of WHERE and go ahead with the alias.

```<code>SELECT DATEDIFF(NOW(),ec_claims_date) AS DAYGAP FROM ec_claims
HAVING DAYGAP >= 14
</code>```

Body:
Example: Claim Date = 14/3/2017 And today was 29/3/2017 it was more than 14 days.
I've tried DATEDIFF in Mysql it keep showing error somehow.

Example Table:
Table Name:
**ec_claims**
ec_claims_id Primaryint(11)
ec_claims_date  date

CODE:

SELECT DATEDIFF(NOW(),ec_claims_date) AS DAYGAP FROM ec_claims
WHERE DAYGAP >= 14

Error:

#1054 - Unknown column 'DAYGAP' in 'where clause'

Thank You For Reading This.

Body:
WHERE clause does not allow the use of aliases.

You can either use your entire expression without the alias in the where clause, like:

SELECT DATEDIFF(NOW(),ec_claims_date) AS DAYGAP FROM ec_claims
WHERE DATEDIFF(NOW(),ec_claims_date) >= 14

or alternatively, you can use HAVING in place of WHERE and go ahead with the alias.

SELECT DATEDIFF(NOW(),ec_claims_date) AS DAYGAP FROM ec_claims
HAVING DAYGAP >= 14


问:
AVLoadingIndicatorView Library not visible in app
added the library for showing loading effects but it is not visible or any effect is not seen. Although no error occurs but there is no effect seen when the network call begins. The show method doesnot have any effect. Currently im using using android version 4.1.2.

xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10">

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/signin_back_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_gravity="center"
                android:background="@drawable/ic_arrow_back_black_24dp"></ImageView>
        </FrameLayout>

        <TextView
            android:id="@+id/txt_signIn"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="right"
            android:background="@color/colorPrimary"
            android:gravity="center"
            android:padding="12dp"
            android:text="@string/sign_in"
            android:textColor="@color/white"
            android:textSize="18dp"></TextView>
    </RelativeLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Sign in to TruePay"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="50dp">

        <EditText
            android:id="@+id/signin_email_address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:hint="Username"
            android:inputType="textEmailAddress"></EditText>

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_password"
        android:layout_width="match_parent"
        android:layout_marginLeft="20dp"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/signin_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:hint="@string/signin_password"
            android:inputType="textPassword"></EditText>

    </android.support.design.widget.TextInputLayout>

    <TextView
        android:id="@+id/forgot_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="40dp"
        android:clickable="true"
        android:gravity="center"
        android:padding="10dp"
        android:text="@string/forgot_password"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:textStyle="bold"></TextView>

    <TextView
        android:id="@+id/use_device_code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="10dp"
        android:text="@string/device_code"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:textStyle="bold"></TextView>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/avi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            app:indicatorName="BallPulseIndicator" />
    </RelativeLayout>

</LinearLayout>
</code>```

java code

```<code>public class SignIn extends BaseSupportFragment {
    private View view;
    private ImageView backPage;
    private TextView signInBtn;
    private TextView forgotPassword;
    private TextView deviiceCodes;
    TextInputLayout emailLayout,passwordLayout;
    EditText email,password;
    private static SessionManagement sessionManagement;
    AVLoadingIndicatorView avi;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.sign_in_fragment, container, false);
        initiateUI();
        setListener();
        return view;
    }

    public  void getTokenFromServer()
    {
        WeakHashMap<String, String> param = new WeakHashMap<>();
        param.put("username",email.getText().toString());
        param.put("password",password.getText().toString());
        Log.e("param...", String.valueOf(param));

        RetrofitInterface apiService = RetrofitClient.getClient().create(RetrofitInterface.class);
        Observable<TokenModel> call = apiService.postFishDetails(param)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread());
        call.subscribe(new Observer<TokenModel>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                //handle error
                Log.e("access",e.toString());
                try {
                    if (e instanceof HttpException) {
                        if (((HttpException) e).code() == 401) {
                            // GlobalBus.getBus().post(new TokenExpirationNotification("Token Expired"));
                        }
                    }
                    if (e instanceof IOException) {

                    }

                } catch (Exception e1) {

                }

            }

            @Override
            public void onNext(TokenModel response)
            {

                Constant.ACCESS_TOKEN = "Bearer" + response.getAccessToken();

                avi.hide();
                Intent intent = new Intent(getActivity(), DrawerAct.class);
                getActivity().startActivity(intent);
                getActivity().finish();

            }

        });

    }
    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private void setListener() {
        backPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
        signInBtn.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if(TextUtils.isEmpty(email.getText().toString()))
                {
                    emailLayout.setError("Enter Username");
                    requestFocus(email);
                }
                else if(TextUtils.isEmpty(password.getText().toString()))
                {
                    passwordLayout.setError("Enter Password");
                    requestFocus(password);
                }
                else
                {

                    avi.show();
                    getTokenFromServer();
                }

            }
        });

        forgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(R.id.frame_layout, new ForgotPassword());
            }
        });

        deviiceCodes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(R.id.frame_layout, new DeviceCode());
            }
        });
    }

    private void initiateUI()
    {

        backPage = (ImageView) view.findViewById(R.id.signin_back_button);
        signInBtn = (TextView) view.findViewById(R.id.txt_signIn);
        forgotPassword = (TextView) view.findViewById(R.id.forgot_password);
        deviiceCodes = (TextView) view.findViewById(R.id.use_device_code);

        emailLayout=(TextInputLayout)view.findViewById(R.id.input_layout_email);
        passwordLayout=(TextInputLayout)view.findViewById(R.id.input_layout_password);

        email=(EditText)view.findViewById(R.id.signin_email_address);
        password=(EditText)view.findViewById(R.id.signin_password);

        avi=(AVLoadingIndicatorView)view.findViewById(R.id.avi);

    }

}
</code>```

答:
Resolved the issue. Forgot to mention the indiacator color which is white by default so the loader was actually working but wasnt visible;

XML code

```<code><com.wang.avi.AVLoadingIndicatorView
        android:id="@+id/avi"
        style="@style/AVLoadingIndicatorView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone"
        app:indicatorColor="@color/colorPrimaryDark"
        app:indicatorName="LineSpinFadeLoaderIndicator" />
</code>```

Body:
added the library for showing loading effects but it is not visible or any effect is not seen. Although no error occurs but there is no effect seen when the network call begins. The show method doesnot have any effect. Currently im using using android version 4.1.2.

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10">

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/signin_back_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_gravity="center"
                android:background="@drawable/ic_arrow_back_black_24dp"></ImageView>
        </FrameLayout>

        <TextView
            android:id="@+id/txt_signIn"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="right"
            android:background="@color/colorPrimary"
            android:gravity="center"
            android:padding="12dp"
            android:text="@string/sign_in"
            android:textColor="@color/white"
            android:textSize="18dp"></TextView>
    </RelativeLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Sign in to TruePay"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:textStyle="bold"></TextView>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="50dp">

        <EditText
            android:id="@+id/signin_email_address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:hint="Username"
            android:inputType="textEmailAddress"></EditText>

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_password"
        android:layout_width="match_parent"
        android:layout_marginLeft="20dp"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/signin_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:hint="@string/signin_password"
            android:inputType="textPassword"></EditText>

    </android.support.design.widget.TextInputLayout>

    <TextView
        android:id="@+id/forgot_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="40dp"
        android:clickable="true"
        android:gravity="center"
        android:padding="10dp"
        android:text="@string/forgot_password"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:textStyle="bold"></TextView>

    <TextView
        android:id="@+id/use_device_code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:padding="10dp"
        android:text="@string/device_code"
        android:textColor="@color/black"
        android:textSize="18dp"
        android:textStyle="bold"></TextView>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <com.wang.avi.AVLoadingIndicatorView
            android:id="@+id/avi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="visible"
            app:indicatorName="BallPulseIndicator" />
    </RelativeLayout>

</LinearLayout>

java code

public class SignIn extends BaseSupportFragment {
    private View view;
    private ImageView backPage;
    private TextView signInBtn;
    private TextView forgotPassword;
    private TextView deviiceCodes;
    TextInputLayout emailLayout,passwordLayout;
    EditText email,password;
    private static SessionManagement sessionManagement;
    AVLoadingIndicatorView avi;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.sign_in_fragment, container, false);
        initiateUI();
        setListener();
        return view;
    }

    public  void getTokenFromServer()
    {
        WeakHashMap<String, String> param = new WeakHashMap<>();
        param.put("username",email.getText().toString());
        param.put("password",password.getText().toString());
        Log.e("param...", String.valueOf(param));

        RetrofitInterface apiService = RetrofitClient.getClient().create(RetrofitInterface.class);
        Observable<TokenModel> call = apiService.postFishDetails(param)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread());
        call.subscribe(new Observer<TokenModel>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                //handle error
                Log.e("access",e.toString());
                try {
                    if (e instanceof HttpException) {
                        if (((HttpException) e).code() == 401) {
                            // GlobalBus.getBus().post(new TokenExpirationNotification("Token Expired"));
                        }
                    }
                    if (e instanceof IOException) {

                    }

                } catch (Exception e1) {

                }

            }

            @Override
            public void onNext(TokenModel response)
            {

                Constant.ACCESS_TOKEN = "Bearer" + response.getAccessToken();

                avi.hide();
                Intent intent = new Intent(getActivity(), DrawerAct.class);
                getActivity().startActivity(intent);
                getActivity().finish();

            }

        });

    }
    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private void setListener() {
        backPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
        signInBtn.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if(TextUtils.isEmpty(email.getText().toString()))
                {
                    emailLayout.setError("Enter Username");
                    requestFocus(email);
                }
                else if(TextUtils.isEmpty(password.getText().toString()))
                {
                    passwordLayout.setError("Enter Password");
                    requestFocus(password);
                }
                else
                {

                    avi.show();
                    getTokenFromServer();
                }

            }
        });

        forgotPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(R.id.frame_layout, new ForgotPassword());
            }
        });

        deviiceCodes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                replaceFragment(R.id.frame_layout, new DeviceCode());
            }
        });
    }

    private void initiateUI()
    {

        backPage = (ImageView) view.findViewById(R.id.signin_back_button);
        signInBtn = (TextView) view.findViewById(R.id.txt_signIn);
        forgotPassword = (TextView) view.findViewById(R.id.forgot_password);
        deviiceCodes = (TextView) view.findViewById(R.id.use_device_code);

        emailLayout=(TextInputLayout)view.findViewById(R.id.input_layout_email);
        passwordLayout=(TextInputLayout)view.findViewById(R.id.input_layout_password);

        email=(EditText)view.findViewById(R.id.signin_email_address);
        password=(EditText)view.findViewById(R.id.signin_password);

        avi=(AVLoadingIndicatorView)view.findViewById(R.id.avi);

    }

}

Body:
Resolved the issue. Forgot to mention the indiacator color which is white by default so the loader was actually working but wasnt visible;

XML code

<com.wang.avi.AVLoadingIndicatorView
        android:id="@+id/avi"
        style="@style/AVLoadingIndicatorView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone"
        app:indicatorColor="@color/colorPrimaryDark"
        app:indicatorName="LineSpinFadeLoaderIndicator" />


问:
How to reset service between tests in AngularJS
I have a service that is injected into beforeEach:

```<code>beforeEach(inject(function($rootScope, $state, $injector, $controller, MyService) {
    var state = $state;
    scope = $rootScope.$new();
    myService = MyService;
    ctrl = $controller('MainCtrl', {$state: state, MyService: myService});
}));
</code>```

And I have some tests described with "it":

```<code>it('test1', function() {
   var data = ["test"];
   ctrl.extract_data(data);
   expect(myService.get_data()).toEquals("test");
});
</code>```

Now my problem is that I have a shared variable in service (variable data) between the tests and if I run the test with other data (e.g. var data = ["a", "b"]), the variable that is shared in myService will contain a, b and test (that was retrieved from the previous test). Is there a way to "reset" the service content everytime a test is ran?

答:
I don't know a way to reset it, but each it block don't share anything with other it blocks. You could just inject a new controller in each it block.

```<code>it('test1', function() {
   var ctrl;
   var data = ["test"];
   inject(function($controller) {
     ctrl = $controller('MainCtrl', {$state: state, MyService: myService}
   })
   ctrl.extract_data(data);
   expect(myService.get_data()).toEquals("test");
});
</code>```

Body:
I have a service that is injected into beforeEach:

beforeEach(inject(function($rootScope, $state, $injector, $controller, MyService) {
    var state = $state;
    scope = $rootScope.$new();
    myService = MyService;
    ctrl = $controller('MainCtrl', {$state: state, MyService: myService});
}));

And I have some tests described with "it":

it('test1', function() {
   var data = ["test"];
   ctrl.extract_data(data);
   expect(myService.get_data()).toEquals("test");
});

Now my problem is that I have a shared variable in service (variable data) between the tests and if I run the test with other data (e.g. var data = ["a", "b"]), the variable that is shared in myService will contain a, b and test (that was retrieved from the previous test). Is there a way to "reset" the service content everytime a test is ran?

Body:
I don't know a way to reset it, but each it block don't share anything with other it blocks. You could just inject a new controller in each it block.

it('test1', function() {
   var ctrl;
   var data = ["test"];
   inject(function($controller) {
     ctrl = $controller('MainCtrl', {$state: state, MyService: myService}
   })
   ctrl.extract_data(data);
   expect(myService.get_data()).toEquals("test");
});


问:
Segmentation fault when inserting at the end of a linked list C++
Okay, so I'm trying to create a linked list of items by adding them one by one onto the end, and I also wanna print out the results.

I'm only showing part of my code (the part that I need work on), so ignore all the libraries that I'm not really making use of in this snippet:

```<code>#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

struct Item {
    char letter;
    Item *next;
};

class List {
  public:
    List();
    void InsertEnd(char key);
    void Display();
    bool IsEmpty();
    void SizeOf();
  private:
    Item *head;
    Item *tail;
    int size;
};

List::List() {
    head = NULL;
    tail = NULL;
    size = 0;
}

void List::InsertEnd(char key) {
    //new item we're adding to the end
    Item* addOn = new Item();
    addOn->letter = key;
    addOn->next = NULL;

    //temporary item to traverse through list
    Item* temp = head;

    //if list is empty, head and tail both point to it
    if ( IsEmpty() ) {
        head->next = addOn;
        tail->next = addOn;
    } else {
        //once temp = tail
        if (temp->next == NULL) {
            tail->next = temp;
            temp = addOn;
        }
    }

    //update size of list
    SizeOf();

}

void List::Display() {
    cout << "Items:" << endl;
    for (Item* curr = head->next; curr != NULL; curr = curr->next) {
      cout << curr->letter << endl;
    }

cout << size << " items." << endl;

}

bool List::IsEmpty() {
    if (size == 0)
        return true;
    else
        return false;
}

void List::SizeOf() {
    size++;
}

int main() {
    List* test = new List;

    test->InsertEnd('A');
    test->InsertEnd('B');
    test->InsertEnd('C');

    test->Display();

    return 0;
}
</code>```

It compiles just fine, but when I run it, literally the only thing I get is "Segmentation fault." ???

答: I recommend that you single step in a debugger and see exactly which value is null when you crash. The debugger will show you every value at each step in your code. I've been programming for over 30 years and I single step through my code every day.</p>

Body:
Okay, so I'm trying to create a linked list of items by adding them one by one onto the end, and I also wanna print out the results.

I'm only showing part of my code (the part that I need work on), so ignore all the libraries that I'm not really making use of in this snippet:

#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

struct Item {
    char letter;
    Item *next;
};

class List {
  public:
    List();
    void InsertEnd(char key);
    void Display();
    bool IsEmpty();
    void SizeOf();
  private:
    Item *head;
    Item *tail;
    int size;
};

List::List() {
    head = NULL;
    tail = NULL;
    size = 0;
}

void List::InsertEnd(char key) {
    //new item we're adding to the end
    Item* addOn = new Item();
    addOn->letter = key;
    addOn->next = NULL;

    //temporary item to traverse through list
    Item* temp = head;

    //if list is empty, head and tail both point to it
    if ( IsEmpty() ) {
        head->next = addOn;
        tail->next = addOn;
    } else {
        //once temp = tail
        if (temp->next == NULL) {
            tail->next = temp;
            temp = addOn;
        }
    }

    //update size of list
    SizeOf();

}

void List::Display() {
    cout << "Items:" << endl;
    for (Item* curr = head->next; curr != NULL; curr = curr->next) {
      cout << curr->letter << endl;
    }

cout << size << " items." << endl;

}

bool List::IsEmpty() {
    if (size == 0)
        return true;
    else
        return false;
}

void List::SizeOf() {
    size++;
}

int main() {
    List* test = new List;

    test->InsertEnd('A');
    test->InsertEnd('B');
    test->InsertEnd('C');

    test->Display();

    return 0;
}

It compiles just fine, but when I run it, literally the only thing I get is "Segmentation fault." ???


问:
MeteorJS setting a different mongodb url to run locally on windows
I am trying to run my mlab mongoDB locally on my computer from MeteorJS, so that when my Meteor code runs and gets put on localhost:3000, I look into the mLab mongoDB collections rather than local collections. I try to set the new mongo url like this on the command prompt:

```<code>set MONGO_URL=mongodb://user:password@stuff.mlab.com:11903/thing
</code>```

After doing this and running meteor, however, I don't appear to access the mlab collections. Am I doing something wrong?

答:
Run meteor with following command:</p>

```<code>MONGO_URL=mongodb://DB_USER:PASSWORD@MLAB_URL:PORT/DB_NAME meteor
</code>```

Body:
I am trying to run my mlab mongoDB locally on my computer from MeteorJS, so that when my Meteor code runs and gets put on localhost:3000, I look into the mLab mongoDB collections rather than local collections. I try to set the new mongo url like this on the command prompt:

set MONGO_URL=mongodb://user:password@stuff.mlab.com:11903/thing

After doing this and running meteor, however, I don't appear to access the mlab collections. Am I doing something wrong?

Body:
Run meteor with following command:

MONGO_URL=mongodb://DB_USER:PASSWORD@MLAB_URL:PORT/DB_NAME meteor


问:
Javascript: silently fail on undefined assignment
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

```<code>myObject.property = dictionary['NO_KEY'][0];
</code>```

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

答:
While I believe this is a bad idea that will come back to bite you later, here is a solution for modern browsers using proxies. Yes, you are still checking for the property existence, but it is hidden from your code accessing the dictionary keys.

var dictionary = {a: 42};

dictionary = new Proxy(dictionary, {
    get: (target, property) => {
        if (target.hasOwnProperty(property)) {
            return target[property];
        }
        return {};
    }
});

// Existing properties are passed through unchanged
console.log(dictionary.a);
// Missing properties result in an empty object
console.log(dictionary.b);
// Original test
var lost = dictionary['NO_KEY'][0];
console.log(lost);```

Body:
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

myObject.property = dictionary['NO_KEY'][0];

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?


问:
Exponential of large negative numbers
How does one compute a number such as np.exp(-28000) on Python? The answer is around 5E-12161. I've been told that due to the double-precision floating point format, I would only be able to calculate a number > 1e-2048</p>

答:
Try the decimal module.</p>

```<code>Decimal(math.exp(1))**-28000
</code>```

Title: Exponential of large negative numbers

Body:
Try the decimal module.

Decimal(math.exp(1))**-28000


问:
How assign char * value to char using C
I have variable char * amount; and char t_amount;
I want to assign amount to t_amount.

```<code>char * amount = "sdf";
char t_amount = amount;
printf("%s t_amount \n", t_amount);
// I am expecting : sdf t_amount
</code>```

when i print, segmentation error occurs so how do i fix this?
Hope you guys can help me.

答:
the variable amount is a pointer so when char t_amount = amount;you are actually assigning the pointer's address to your t_amount variable, hence the segfault

If t_amount was a char * you could have done that assignment without any errors.

Title: How assign char * value to char using C

Body:
I have variable char * amount; and char t_amount;
I want to assign amount to t_amount.

char * amount = "sdf";
char t_amount = amount;
printf("%s t_amount \n", t_amount);
// I am expecting : sdf t_amount

when i print, segmentation error occurs so how do i fix this?
Hope you guys can help me.


问:
Select in sql statement
Can anyone assist me with this below?

I have 10 records in a table with same acc no and different branches. If I fired the query it should not return any values while where condition is matched.

For example:

```<code> SELECT *
 FROM temp
 WHERE branch != "xxx"
</code>```

It should not return other 9 records also.

Can someone help me?

Thanks

答:
Use this

```<code>Select * from temp
Where branch != 'xxx'
</code>```

Title: Select in sql statement

Body:
Can anyone assist me with this below?

I have 10 records in a table with same acc no and different branches. If I fired the query it should not return any values while where condition is matched.

For example:

 SELECT *
 FROM temp
 WHERE branch != "xxx"

It should not return other 9 records also.

Can someone help me?

Thanks

Body:
Use this

Select * from temp
Where branch != 'xxx'


问:
How to flatten the parse tree and store in a string for further string operations python nltk
I am trying to get flat tree from the tree structure like the one given below.

I want to get this whole tree in a string like without Bad tree detected error:

```<code>( (S (NP-SBJ (NP (DT The) (JJ high) (JJ seven-day) )(PP (IN of) (NP (DT the) (CD 400) (NNS money) )))(VP (VBD was) (NP-PRD (CD 8.12) (NN %) )(, ,) (ADVP (RB down) (PP (IN from) (NP (CD 8.14) (NN %) ))))(. .) ))
</code>```

答:
You can convert the tree into string using str function then split and join as follow:</p>

```<code>parse_string = ' '.join(str(tree).split())

print parse_string
</code>```

Body:
I am trying to get flat tree from the tree structure like the one given below.

I want to get this whole tree in a string like without Bad tree detected error:

( (S (NP-SBJ (NP (DT The) (JJ high) (JJ seven-day) )(PP (IN of) (NP (DT the) (CD 400) (NNS money) )))(VP (VBD was) (NP-PRD (CD 8.12) (NN %) )(, ,) (ADVP (RB down) (PP (IN from) (NP (CD 8.14) (NN %) ))))(. .) ))

Body:
You can convert the tree into string using str function then split and join as follow:

parse_string = ' '.join(str(tree).split())

print parse_string


问:
How to shorten MongoDB ObjectId and use it in Mongoose schema
I am looking for a way to shorten the ObjectID generated by the MongoDB database, and I am aware of some of the existing library like 'shortid''short-mongo-id'

However, my problem is that I wish to create a new 'shortID' field in the mongoose schema for every document that exists in the collection, and this new field should be unique and ideally the truncated version of the ObjectId attached to the document.
Like such:

```<code>var subjectSchema = new Schema({

    shortID: {required: true, unique: true},
    //must be unique to each document and is same everytime server restarts

    Sex: {type: String, enum: enumSex},
    Diagnosis: String,
    Projects:[projectPerSubjectSchema]
});
</code>```

The 'shortid' https://www.npmjs.com/package/shortid library works good and does generate unique id, but, it generates different id every time server restarts, which is not what I want.

Another library I tried 'short-mongo-id' https://www.npmjs.com/package/short-mongo-id was able to convert ObjectId into a truncated version of unique ID string, however, I'm not sure how to use it in creating a schema. I've tried:

```<code>ID: {type: String, 'default': shortid((this.ObjectId).valueOf()), unique: true}
</code>```

to try and get the document's ObjectId using this.ObjectId, stringify it with valueOf(), but the terminal shows:

```<code>TypeError: Cannot read property 'valueOf' of undefined
</code>```

All of the code are done in Node.JS and I am very new to both NodeJS and MongoDB, so please correct me if I am making some major errors with the code provided above. Thanks in advance!

答:
The shortid module should work for what you need, you just need to save the shortId as normal String field, and make sure a new code is generated before saving, like this (inside mongoose schema definition):

```<code>const mongoose = require('mongoose')
const shortid = require('shortid')
const Schema = mongoose.Schema
const schema = new Schema({
  _shortId: {
    type: String,
    unique: true
  },
  ... // other fields...
})
// This is for checking if the document already have a _shortId,
// so you don't replace it with a new code
schema.pre('save', function (next) {
  let doc = this

  if (!this._shortId) {
    addShortId(doc, next)
  }
})

function addShortId (doc, next) {
  let newShortId = shortid.generate()
  doc.constructor.findOne({_shortId: newShortId}).then((docRes) => {
    if (docRes) {
      addShortId(doc, next)
    } else {
      doc._shortId = newCode
      next()
    }
  }, (err) => {
    next(err)
  })
}
</code>```

If you want to insert a _showId for all the existing documents, you just need a forEach and save the model again, this is how I'm doing (using https://github.com/JMPerez/promise-throttle, cause it's a huge collection, calling save() all at once would slow down the server) :

```<code>XXXXX.find({ '_shortId': { '$exists': false } }).then((data) => {
  var promiseThrottle = new PromiseThrottle({
    requestsPerSecond: 50,
    promiseImplementation: Promise
  })
  var i = 1
  data.forEach(element => {
  var myFunction = function (j) {
    return element.save()
  }
  promiseThrottle.add(myFunction.bind(this, i++)).then(ss => {
    console.log('done ' + ss._shortId)
  })
})
</code>```

Some of this code is adapted from: https://github.com/dylang/shortid/issues/65

Body:
I am looking for a way to shorten the ObjectID generated by the MongoDB database, and I am aware of some of the existing library like 'shortid''short-mongo-id'

However, my problem is that I wish to create a new 'shortID' field in the mongoose schema for every document that exists in the collection, and this new field should be unique and ideally the truncated version of the ObjectId attached to the document.
Like such:

var subjectSchema = new Schema({

    shortID: {required: true, unique: true},
    //must be unique to each document and is same everytime server restarts

    Sex: {type: String, enum: enumSex},
    Diagnosis: String,
    Projects:[projectPerSubjectSchema]
});

The 'shortid' https://www.npmjs.com/package/shortid library works good and does generate unique id, but, it generates different id every time server restarts, which is not what I want.

Another library I tried 'short-mongo-id' https://www.npmjs.com/package/short-mongo-id was able to convert ObjectId into a truncated version of unique ID string, however, I'm not sure how to use it in creating a schema. I've tried:

ID: {type: String, 'default': shortid((this.ObjectId).valueOf()), unique: true}

to try and get the document's ObjectId using this.ObjectId, stringify it with valueOf(), but the terminal shows:

TypeError: Cannot read property 'valueOf' of undefined

All of the code are done in Node.JS and I am very new to both NodeJS and MongoDB, so please correct me if I am making some major errors with the code provided above. Thanks in advance!

Body:
The shortid module should work for what you need, you just need to save the shortId as normal String field, and make sure a new code is generated before saving, like this (inside mongoose schema definition):

const mongoose = require('mongoose')
const shortid = require('shortid')
const Schema = mongoose.Schema
const schema = new Schema({
  _shortId: {
    type: String,
    unique: true
  },
  ... // other fields...
})
// This is for checking if the document already have a _shortId,
// so you don't replace it with a new code
schema.pre('save', function (next) {
  let doc = this

  if (!this._shortId) {
    addShortId(doc, next)
  }
})

function addShortId (doc, next) {
  let newShortId = shortid.generate()
  doc.constructor.findOne({_shortId: newShortId}).then((docRes) => {
    if (docRes) {
      addShortId(doc, next)
    } else {
      doc._shortId = newCode
      next()
    }
  }, (err) => {
    next(err)
  })
}

If you want to insert a _showId for all the existing documents, you just need a forEach and save the model again, this is how I'm doing (using https://github.com/JMPerez/promise-throttle, cause it's a huge collection, calling save() all at once would slow down the server) :

XXXXX.find({ '_shortId': { '$exists': false } }).then((data) => {
  var promiseThrottle = new PromiseThrottle({
    requestsPerSecond: 50,
    promiseImplementation: Promise
  })
  var i = 1
  data.forEach(element => {
  var myFunction = function (j) {
    return element.save()
  }
  promiseThrottle.add(myFunction.bind(this, i++)).then(ss => {
    console.log('done ' + ss._shortId)
  })
})

Some of this code is adapted from: https://github.com/dylang/shortid/issues/65


问:
RecyclerView Multiple Layout View(s) in an Adapter class
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

```<code>public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
        this.itemsList = itemsList;
        this.mContext = context;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

        public SingleItemRowHolder(View view) {
            super(view);

            this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            this.itemImage = (ImageView) view.findViewById(R.id.itemImage);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    }

}
</code>```

答: Simply use frame layout with your fragment and add this fragment in your framelayout that will add like you want for that. So its also easy to handle. hope this will help you </p>

Body:
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
        this.itemsList = itemsList;
        this.mContext = context;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

        public SingleItemRowHolder(View view) {
            super(view);

            this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            this.itemImage = (ImageView) view.findViewById(R.id.itemImage);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    }

}


问:
How to convert "/Date(1490065200000)/" to "21/03/2017"?
Please check in jsfiddle.

Code:

```<code>$( document ).ready(function() {
  var str = moment("/Date(1490065200000)/"); //Convert to "21/03/2017"
  console.log(str.toString());
});
</code>```

Here docs: https://momentjs.com/docs/#/parsing/asp-net-json-date/

Any Solution ?

答:
Add .format("MM/DD/YYYY") . Docs: http://momentjs.com/docs/#/displaying/format/

UPD: .format("DD/MM/YYYY"), like @Tushar noticed in comment

Body:
Please check in jsfiddle.

Code:

$( document ).ready(function() {
  var str = moment("/Date(1490065200000)/"); //Convert to "21/03/2017"
  console.log(str.toString());
});

Here docs: https://momentjs.com/docs/#/parsing/asp-net-json-date/

Any Solution ?


问:
Java enhanced enhanced for loop
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

```<code>int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}
</code>```

答:
Well, like you said, if you must have an index just use a standard for loop, or update a counter manually.

But rethink your question. Why should you need an index in a for (Object o : list) loop?

The whole point of using an enhanced loop is to abstract away the nasty parts of using an index or an iterator.

Most languages today do not give this kind of functionality in loops. Just as an example, the Pythonic way to do this is:

```<code>for index, val in enumerate(someList):
    # ....
</code>```

Title: Java enhanced enhanced for loop

Body:
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}

Body:
Well, like you said, if you must have an index just use a standard for loop, or update a counter manually.

But rethink your question. Why should you need an index in a for (Object o : list) loop?

The whole point of using an enhanced loop is to abstract away the nasty parts of using an index or an iterator.

Most languages today do not give this kind of functionality in loops. Just as an example, the Pythonic way to do this is:

for index, val in enumerate(someList):
    # ....


问:
Populate other field with value
I have a test many2one field. When it is populated I want the partner_id field to use the partner associated with that field. Following is not working:

<field name="partner_id" required="1"/>
<field name="x_test" context="{'partner_id': parent.partner_id}" />
```

答:
i assume you wanna put same value of partner_id  in x_test field, then use related field

```<code>partner_id = fields.Many2one('res.partner', string="partner")
x_test =  fields.Many2one('res.partner',related='partner_id', string="X Test")
</code>```

in XML

```<code><field name="partner_id" required="1"/>
 <field name="x_test" />
</code>```

Title: Populate other field with value

Body:
i assume you wanna put same value of partner_id  in x_test field, then use related field

partner_id = fields.Many2one('res.partner', string="partner")
x_test =  fields.Many2one('res.partner',related='partner_id', string="X Test")

in XML

<field name="partner_id" required="1"/>
 <field name="x_test" />


问:
Questions about parallel testing, need information about Cucumber, Selendroid, and Spoon
I need to implement a parallel testing feature to my tests, I found these three; Spoon, Cucumber(parallel-cucumber) and Selendroid(Selenium grid). But I searched for some information about them and I couldn't find it anywhere...

Spoon: Do it run in Webviews?

Cucumber: do it work with both UIAutomator and Espresso?

Selendroid: do it also run with UIAutomator and Espresso?

答:
I'm not familiar with UIAutomator and Espresso but I am familiar with Cucumber.

The steps you implement in Cucumber are regular Java methods. If you can use UIAutomator or Espresso from regular Java methods, then yes. You are able to use UIAutomator and Espresso with Cucumber-JVM.


问:
webpack common chunks plugin vs webpack dll plugin
Before I used webpack common chunks plugin to create vendor bundle containing third party libraries like angular, react, lodash etc, but then I knew about webpack dll plugin. They seem do the same things but dll plugin also allows you to reduce build time. So I'm confused do I need to use both these plugins together. Should I use common chunks plugin for creating vendor bundle in production build and dll plugin in development build. Or I should use dll plugin in both production and development builds? Could you please explain this?</p>

答:
I was looking for the difference here as well but I really don't think this is the case. At least, not anymore.

If you take a look at the webpack documenation for code splitting libraries, it mentions a way to extract out a similar manifest file. From my understanding, this is what the DllPlugin is doing except it is slightly more implicit with the CommonsChunkPlugin.

The benefit is that you don't need to maintain multiple Webpack configurations for this sort of functionality.


问:
How to install additional packages to jython jar in jmeter?
I am using jython inside jmeter by placing the jython.jar under "lib" folder of your JMeter installation. It runs successfully.

But the problem is I can't install additional packages or modules of python inside it. To be more specific, I want to run selenium in python inside jmeter, so needs selenium module needs to be installed in jython.

How should I do it?

答:
You can install Jython packages normally, i.e. using pip, however make sure you are executing pip which comes with Jython (located under "bin" folder of your Jython installation)

Download Jython installer and perform the installation somewhere, i.e. /temp/jython

Navigate to /temp/jython/bin folder and execute ./pip install selenium command

Add the next line to user.properties file which is located in JMeter's "bin" folder:

```<code>user.classpath=/temp/jython;/temp/jython/javalib
</code>```

Note that JMeter restart will be required to pick the classpath up, check out Apache JMeter Properties Customization Guide for more information.

Add JSR223 Sampler and selenium jython from the "Language" dropdown

Add the next lines at the beginning of your script:

```<code>import sys
sys.path.append('/temp/jython/Lib')
sys.path.append('/temp/jython/Lib/site-packages')
import selenium
</code>```

You should be good to go.

Body:
You can install Jython packages normally, i.e. using pip, however make sure you are executing pip which comes with Jython (located under "bin" folder of your Jython installation)

Download Jython installer and perform the installation somewhere, i.e. /temp/jython

Navigate to /temp/jython/bin folder and execute ./pip install selenium command

Add the next line to user.properties file which is located in JMeter's "bin" folder:

user.classpath=/temp/jython;/temp/jython/javalib

Note that JMeter restart will be required to pick the classpath up, check out Apache JMeter Properties Customization Guide for more information.

Add JSR223 Sampler and selenium jython from the "Language" dropdown

Add the next lines at the beginning of your script:

import sys
sys.path.append('/temp/jython/Lib')
sys.path.append('/temp/jython/Lib/site-packages')
import selenium

You should be good to go.