问:
Automation mobile application using appium
I am trying to automate an android application using Appium and Cucumber with Java.I have written the code for a functionality and it is working fine. But some times while running the script, it throws an error

```<code>org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original err
or: Could not proxy command to remote server. Original error: Error: read ECONNRESET (WARNING: The server did not provid
e any stacktrace information)
</code>```

Source code:

```<code>import com.google.common.base.Function;
import com.intel.truevr.appautomation.core.Capabilities;
import org.openqa.selenium.By;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.MobileElement;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.support.ui.Wait;
import java.util.List;
import io.appium.java_client.TouchAction;

public class C754L2D {
    Capabilities c = new Capabilities();
    MobileDriver driver =  c.getDefaultCapabilities();
    Wait wait = new Wait() {
        @Override
        public Object until(Function isTrue) {
            return null;
        }
    };

    @Given("^User taps the toggle button in the live 2D video playing screen$")
    public void user_taps_toggle_button() throws Exception {

        MobileElement allow = (MobileElement) driver.findElement(By.id("com.android.packageinstaller:id/permission_allow_button"));
        allow.click();
        List<MobileElement> list = driver.findElements(By.id("android:id/text1"));
        for(MobileElement ele :list) {
            String text = ele.getText();
            if(text.equals("Live")){
                ele.click();
                break;
            }
        }
        MobileElement panoramicButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_select_2d"));
        panoramicButton.click();
        MobileElement Screen= (MobileElement) driver.findElement(By.className("android.view.View"));
        TouchAction ta = new TouchAction(driver);
        ta.tap(Screen, 531, 357).perform();
        MobileElement toggleButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/fab_player_switch_mode"));
        toggleButton.click();
    }
    @When("^Taps back button in the transition screen$")
    public void taps_back_button() throws InterruptedException {

        Thread.sleep(1000);
        MobileElement backButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/iv_cardboard_back"));
        backButton.click();

    }
    @Then("^The transition screen should dismiss and user should be navigated back to 2d live video playing screen$")
    public void dismiss_transition_screen() {

        try{
            MobileElement cameraAngleSelectionButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_player_switch_camera_parent"));
            if(cameraAngleSelectionButton != null) {
                System.out.println("The transition screen is dismissed and user is navigated back to 2d live video playing screen");
            }
        }catch(Exception e){
            System.out.println("The transition screen is not dismissed and user is not navigated back to 2d live video playing screen");
        }
        //driver.quit();
    }

}
</code>```

This error gets cleared and the script works fine when I close the emulator and open it again. Can anybody help me in this?

答:
Hey please then kill all simulator programmatically after executing testcase. Below code might help you.

```<code>/**
 * Stop Simulator
 */
public void stopSimulator() {
    try {
        Runtime.getRuntime().exec("killall \"iOS Simulator\"");
    } catch (IOException e) {
        //e.printStackTrace();
    }
    try {
        Runtime.getRuntime().exec("killall Simulator");
    } catch (IOException e) {
        //e.printStackTrace();
    }
}
</code>```

If you are openning a specific simulator you can specify this in above code.

For android simulator please use

```<code>Runtime.getRuntime().exec("adb emu kill");
</code>```

Body:
I am trying to automate an android application using Appium and Cucumber with Java.I have written the code for a functionality and it is working fine. But some times while running the script, it throws an error

org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original err
or: Could not proxy command to remote server. Original error: Error: read ECONNRESET (WARNING: The server did not provid
e any stacktrace information)

Source code:

import com.google.common.base.Function;
import com.intel.truevr.appautomation.core.Capabilities;
import org.openqa.selenium.By;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.MobileElement;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.support.ui.Wait;
import java.util.List;
import io.appium.java_client.TouchAction;

public class C754L2D {
    Capabilities c = new Capabilities();
    MobileDriver driver =  c.getDefaultCapabilities();
    Wait wait = new Wait() {
        @Override
        public Object until(Function isTrue) {
            return null;
        }
    };

    @Given("^User taps the toggle button in the live 2D video playing screen$")
    public void user_taps_toggle_button() throws Exception {

        MobileElement allow = (MobileElement) driver.findElement(By.id("com.android.packageinstaller:id/permission_allow_button"));
        allow.click();
        List<MobileElement> list = driver.findElements(By.id("android:id/text1"));
        for(MobileElement ele :list) {
            String text = ele.getText();
            if(text.equals("Live")){
                ele.click();
                break;
            }
        }
        MobileElement panoramicButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_select_2d"));
        panoramicButton.click();
        MobileElement Screen= (MobileElement) driver.findElement(By.className("android.view.View"));
        TouchAction ta = new TouchAction(driver);
        ta.tap(Screen, 531, 357).perform();
        MobileElement toggleButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/fab_player_switch_mode"));
        toggleButton.click();
    }
    @When("^Taps back button in the transition screen$")
    public void taps_back_button() throws InterruptedException {

        Thread.sleep(1000);
        MobileElement backButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/iv_cardboard_back"));
        backButton.click();

    }
    @Then("^The transition screen should dismiss and user should be navigated back to 2d live video playing screen$")
    public void dismiss_transition_screen() {

        try{
            MobileElement cameraAngleSelectionButton = (MobileElement) driver.findElement(By.id("com.jackalopelite.simplecontainer:id/rl_player_switch_camera_parent"));
            if(cameraAngleSelectionButton != null) {
                System.out.println("The transition screen is dismissed and user is navigated back to 2d live video playing screen");
            }
        }catch(Exception e){
            System.out.println("The transition screen is not dismissed and user is not navigated back to 2d live video playing screen");
        }
        //driver.quit();
    }

}

This error gets cleared and the script works fine when I close the emulator and open it again. Can anybody help me in this?

Body:
Hey please then kill all simulator programmatically after executing testcase. Below code might help you.

/**
 * Stop Simulator
 */
public void stopSimulator() {
    try {
        Runtime.getRuntime().exec("killall \"iOS Simulator\"");
    } catch (IOException e) {
        //e.printStackTrace();
    }
    try {
        Runtime.getRuntime().exec("killall Simulator");
    } catch (IOException e) {
        //e.printStackTrace();
    }
}

If you are openning a specific simulator you can specify this in above code.

For android simulator please use

Runtime.getRuntime().exec("adb emu kill");


来源: stackexchange

问:
How to run R codes inside shell script?
I have a R file ( myfile.R). I want to run it using a shell script. How Can I do that?
I tried this:

```<code>#! /bin/bash
Rscript myfile.R
</code>```

but it gives me this error: Rscript: command not found

I also tried this:

```<code>#! /bin/bash
R --not-save-- < myfile.R
</code>```

It also gives this error: R : command not found

What is the best way to do that?

答:
Start R with the command R and then just add youre code

```<code>user@ubuntu:~/RCode/RCode$ R
> source("data_acquisition.R")
> load_libraries()
> df <- acquire_nps()
> head(df)
...
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to run R codes inside shell script?

Body:
I have a R file ( myfile.R). I want to run it using a shell script. How Can I do that?
I tried this:

#! /bin/bash
Rscript myfile.R

but it gives me this error: Rscript: command not found

I also tried this:

#! /bin/bash
R --not-save-- < myfile.R

It also gives this error: R : command not found

What is the best way to do that?

Body:
Start R with the command R and then just add youre code

user@ubuntu:~/RCode/RCode$ R
> source("data_acquisition.R")
> load_libraries()
> df <- acquire_nps()
> head(df)
...


问:
In-Place Radix Sort
This is a long text. Please bear with me. Boiled down, the question is: Is there a workable in-place radix sort algorithm?

Preliminary

I've got a huge number of small fixed-length strings that only use the letters “A”, “C”, “G” and “T” (yes, you've guessed it: DNA) that I want to sort.

At the moment, I use std::sort which uses introsort in all common implementations of the STL. This works quite well. However, I'm convinced that radix sort fits my problem set perfectly and should work much better in practice.

Details

I've tested this assumption with a very naive implementation and for relatively small inputs (on the order of 10,000) this was true (well, at least more than twice as fast). However, runtime degrades abysmally when the problem size becomes larger (N > 5,000,000).

The reason is obvious: radix sort requires copying the whole data (more than once in my naive implementation, actually). This means that I've put ~ 4 GiB into my main memory which obviously kills performance. Even if it didn't, I can't afford to use this much memory since the problem sizes actually become even larger.

Use Cases

Ideally, this algorithm should work with any string length between 2 and 100, for DNA as well as DNA5 (which allows an additional wildcard character “N”), or even DNA with IUPAC ambiguity codes (resulting in 16 distinct values). However, I realize that all these cases cannot be covered, so I'm happy with any speed improvement I get. The code can decide dynamically which algorithm to dispatch to.

Research

Unfortunately, the Wikipedia article on radix sort is useless. The section about an in-place variant is complete rubbish. The NIST-DADS section on radix sort is next to nonexistent. There's a promising-sounding paper called Efficient Adaptive In-Place Radix Sorting which describes the algorithm “MSL”. Unfortunately, this paper, too, is disappointing.

In particular, there are the following things.

First, the algorithm contains several mistakes and leaves a lot unexplained. In particular, it doesn’t detail the recursion call (I simply assume that it increments or reduces some pointer to calculate the current shift and mask values). Also, it uses the functions dest_group and dest_address without giving definitions. I fail to see how to implement these efficiently (that is, in O(1); at least dest_address isn’t trivial).

Last but not least, the algorithm achieves in-place-ness by swapping array indices with elements inside the input array. This obviously only works on numerical arrays. I need to use it on strings. Of course, I could just screw strong typing and go ahead assuming that the memory will tolerate my storing an index where it doesn’t belong. But this only works as long as I can squeeze my strings into 32 bits of memory (assuming 32 bit integers). That's only 16 characters (let's ignore for the moment that 16 > log(5,000,000)).

Another paper by one of the authors gives no accurate description at all, but it gives MSL’s runtime as sub-linear which is flat out wrong.

To recap: Is there any hope of finding a working reference implementation or at least a good pseudocode/description of a working in-place radix sort that works on DNA strings?

答: I would burstsort a packed-bit representation of the strings. Burstsort is claimed to have much better locality than radix sorts, keeping the extra space usage down with burst tries in place of classical tries. The original paper has measurements.</p>

OwnerDisplayName: Konrad Rudolph

Title: In-Place Radix Sort

LastEditorDisplayName: Konrad Rudolph

OwnerDisplayName: Darius Bacon

ContentLicense: CC BY-SA 2.5


问:
trigger('click') vs trigger('click')[0]
I am unable to differentiate between trigger('click') vs trigger('click')[0], is there any difference between them?

答:
trigger('click') calls the trigger method with the 'click' parameter.

trigger('click')[0] calls the trigger method with the 'click' parameter, and accesses the first element of whatever it's returning.

Title: trigger('click') vs trigger('click')[0]


问:
Simple explanation of "Unified Modelling Language", why is it important?
i am new to asp.net and i was told that i need to know UML thoroughly to build successful software, is this correct? i mean cant i just "code and fix" and "model" in my brain. how important is UML and what is the best way to learn it?</p>

答:
UML is a simple way to graphically document a system and its interactions. Its value to you is not necessarily using UML itself, but the value of documenting a system before coding or modifying it.

I see the advantages as

You are forced to think about the whole design before you start building. A drawing is a lot easier to change than a whole lot of code. Mistakes at this stage are easier to rectify.

It helps to understand the system and interactions far better than code alone can. With all the self-documenting code that you can write, a good diagram will nearly always be clearer to and fast to pick up.

The disadvantages are

Takes time to produce, when you would probably rather be coding and experimenting

Can get out of date if effort is not put in to keeping up to date.


问:
Hadoop Data Blocks and Data Content
Hadoop breaks up the content of the input data into blocks without regard to the content.

As a post described:

HDFS has no idea (and doesn’t care) what’s stored inside the file, so raw files are not split in accordance with rules that we humans would understand. Humans, for example, would want record boundaries — the lines showing where a record begins and ends — to be respected.

The part I am unclear is that if the data is split based only on the data size without regards to the content, then would there not be implication on the accuracy of queries performed later? For instance, an often sited example of list of cities and daily temperatures. could a city be in one block and its temperature somewhere else, how then a map operation correctly queries the info. There seems to be something fundamental about blocks and MR queries that I am missing.

Any help would be greatly appreciated.

答:
See Ali,

the data block were decided by hadoop hdfs gateway in stored procedure and this will based on the hadoop version 1.x or 2.x and depends on size of the file too, which you are placing from the local to hadoop gateway and later after -put command, the hadoop gateway splits the file blocks and stores to your data node directory /data/dfs/data/current/ (if you are running on single node then it is inside your hadoop directory) in form of blk_<job_process_id> and meta data about the blk_ with same job_id name and with .meta extension.

Size of data blocks in Hadoop 1 is 64 mb and in Hadoop 2 it increased to 128 mb block size and thereafter depending on file size it split the block as per I said earlier, so there is no tool to control this thing in hadoop hdfs, if anything, please let me know!

In Hadoop 1, We put simply a file in cluster like below said, if file size is 100 mb then what -

```<code>bin/hadoop fs -put <full-path of the input file till ext> </user/datanode/(target-dir)>
</code>```

Hadoop 1 gateway will divide the file in two(64 mb & 36 mb) blocks and Hadoop 2 make it simply one block and sequentially replicates those blocks as per your configuration.

if you are placing a jar using hadoop for map reduce jobs then there you can set org.apache.hadoop.mapreduce.Job method inside you java Mapper-Reducer class to 1 and later after testing export a jar for mr job like below.

```<code>//Setting the Results to Single Target File in Java File inside main method
job.setNumReduceTasks(1);
</code>```

and later run the hadoop fs script like :

```<code>bin/hadoop jar <full class path of your jar file> <full class path of Main class inside jar> <input directory or file path> <give the output target directory>
</code>```

If you are using sqoop to import the data from rdbms engines then there you can use the "-m 1" to set the single file result but it varies from your question.

Hope, my answer will give a glance to you on the issue, thanks.

Title: Hadoop Data Blocks and Data Content

Body:
See Ali,

the data block were decided by hadoop hdfs gateway in stored procedure and this will based on the hadoop version 1.x or 2.x and depends on size of the file too, which you are placing from the local to hadoop gateway and later after -put command, the hadoop gateway splits the file blocks and stores to your data node directory /data/dfs/data/current/ (if you are running on single node then it is inside your hadoop directory) in form of blk_<job_process_id> and meta data about the blk_ with same job_id name and with .meta extension.

Size of data blocks in Hadoop 1 is 64 mb and in Hadoop 2 it increased to 128 mb block size and thereafter depending on file size it split the block as per I said earlier, so there is no tool to control this thing in hadoop hdfs, if anything, please let me know!

In Hadoop 1, We put simply a file in cluster like below said, if file size is 100 mb then what -

bin/hadoop fs -put <full-path of the input file till ext> </user/datanode/(target-dir)>

Hadoop 1 gateway will divide the file in two(64 mb & 36 mb) blocks and Hadoop 2 make it simply one block and sequentially replicates those blocks as per your configuration.

if you are placing a jar using hadoop for map reduce jobs then there you can set org.apache.hadoop.mapreduce.Job method inside you java Mapper-Reducer class to 1 and later after testing export a jar for mr job like below.

//Setting the Results to Single Target File in Java File inside main method
job.setNumReduceTasks(1);

and later run the hadoop fs script like :

bin/hadoop jar <full class path of your jar file> <full class path of Main class inside jar> <input directory or file path> <give the output target directory>

If you are using sqoop to import the data from rdbms engines then there you can use the "-m 1" to set the single file result but it varies from your question.

Hope, my answer will give a glance to you on the issue, thanks.

ContentLicense: CC BY-SA 4.0


问:
Pop_front doubly linked list function issue
I got an issue with a function for popping out the element from the front of the bidirectional ring.

```<code>template <typename Key, typename Info>
void Ring<Key, Info>::pop_front() {
if (!isEmpty()) {

    Node* p = any->next;
    if (any != NULL) {
    p->prev->next = p->next;
    p->next->prev = p->prev;
    delete p;
    }}}
</code>```

Function begin() is defined.
As you see, it should work perfectly but it doesn't start from the first element. It pops the second one.
What to do? How to point to the first Node?

答: Change Node* p = any->next; to  Node* p = any;

Body:
I got an issue with a function for popping out the element from the front of the bidirectional ring.

template <typename Key, typename Info>
void Ring<Key, Info>::pop_front() {
if (!isEmpty()) {

    Node* p = any->next;
    if (any != NULL) {
    p->prev->next = p->next;
    p->next->prev = p->prev;
    delete p;
    }}}

Function begin() is defined.
As you see, it should work perfectly but it doesn't start from the first element. It pops the second one.
What to do? How to point to the first Node?


问:
How can I find n smallest numbers without changing the order of the first list?
I intend to get the n smallest numbers in a list but keep the numbers in the same order they appear in the list. For example:

This is my list:

```<code>A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
</code>```

I like to get the first three lowest numbers as it has been ordered in the first list:

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

I do not want to sort the result as:

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

I have tried:

```<code>heapq.nsmallest(3,A)
</code>```

but i wonder if it is possible to retain this list as:[1, 2, 0]

By the way, I'm not a Python coder so thanks for the help in advance.

答:
You could use heapq.nsmallest() to get the n smallest elements from the list. Then use collections.Counter to create a multiset from that list which you can use to check which elements from the original list to include in the result, e.g.

```<code>>>> from heapq import nsmallest
>>> from collections import Counter
>>> A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
>>> n = 3
>>> c = Counter(nsmallest(n, A))
>>> result = []
>>> for elem in A:
...     if c.get(elem, 0):
...         result.append(elem)
...         c[elem] -= 1
...
>>> result
[1, 2, 0]
</code>```

Body:
I intend to get the n smallest numbers in a list but keep the numbers in the same order they appear in the list. For example:

This is my list:

A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]

I like to get the first three lowest numbers as it has been ordered in the first list:

[1, 2, 0]

I do not want to sort the result as:

[0, 1, 2]

I have tried:

heapq.nsmallest(3,A)

but i wonder if it is possible to retain this list as:[1, 2, 0]

By the way, I'm not a Python coder so thanks for the help in advance.

Body:
You could use heapq.nsmallest() to get the n smallest elements from the list. Then use collections.Counter to create a multiset from that list which you can use to check which elements from the original list to include in the result, e.g.

>>> from heapq import nsmallest
>>> from collections import Counter
>>> A = [1, 3, 4, 6, 7, 6, 8, 7, 2, 6, 8, 7, 0]
>>> n = 3
>>> c = Counter(nsmallest(n, A))
>>> result = []
>>> for elem in A:
...     if c.get(elem, 0):
...         result.append(elem)
...         c[elem] -= 1
...
>>> result
[1, 2, 0]


问:
How to find an object which contains a specific string and a number which is the highest number?
I'm a beginner in Python and I'm trying to use boto (CloudFormation) to list the latest stacks created which contains a string.

```<code>import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    print(st)
</code>```

This is part of the output I get from running the command:

```<code>{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Stg-22/bc2b6c10-d41a-11e7-b1ab-50d5ca789eae', u'StackName': 'Company-Stg-22', u'CreationTime': datetime.datetime(2017, 11, 28, 9, 1, 34, 985000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-64/0e85cc00-9602-11e7-8c08-50d5ca0184d2', u'StackName': 'Company-Prod-US-API-64', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 28, 43, 598000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-63/1ba257c0-9600-11e7-821f-503f20f2ad4a', u'StackName': 'Company-Prod-US-API-63', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 14, 46, 602000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-61/9252a9d0-2ace-11e7-8eea-503ac9ec2461', u'StackName': 'Company-Prod-US-API-61', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 20, 36, 473000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-60/1ba83440-2acd-11e7-a0c3-503a90a9c435', u'StackName': 'Company-Prod-US-API-60', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 10, 7, 890000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
</code>```

It seems like the output is already sorted with the newest objects first.

I would like to parse the name of the stack which contains the word "Dev" and where the number is the highest among the rest of the stacks of the same environment (Dev), in this case "Company-Dev-31".

How can it be achieved?

答:
You can test if some characters are present by using in as follows:

```<code>import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    if 'dev' in st['StackName'].lower():
        print(st)
</code>```

This would give you:

```<code>{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
</code>```

Converting first to lowercase has the effect of making the test case insensitive, so Dev or dev would match.

Body:
I'm a beginner in Python and I'm trying to use boto (CloudFormation) to list the latest stacks created which contains a string.

import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    print(st)

This is part of the output I get from running the command:

{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Stg-22/bc2b6c10-d41a-11e7-b1ab-50d5ca789eae', u'StackName': 'Company-Stg-22', u'CreationTime': datetime.datetime(2017, 11, 28, 9, 1, 34, 985000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-64/0e85cc00-9602-11e7-8c08-50d5ca0184d2', u'StackName': 'Company-Prod-US-API-64', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 28, 43, 598000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-63/1ba257c0-9600-11e7-821f-503f20f2ad4a', u'StackName': 'Company-Prod-US-API-63', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 14, 46, 602000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-61/9252a9d0-2ace-11e7-8eea-503ac9ec2461', u'StackName': 'Company-Prod-US-API-61', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 20, 36, 473000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-60/1ba83440-2acd-11e7-a0c3-503a90a9c435', u'StackName': 'Company-Prod-US-API-60', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 10, 7, 890000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}

It seems like the output is already sorted with the newest objects first.

I would like to parse the name of the stack which contains the word "Dev" and where the number is the highest among the rest of the stacks of the same environment (Dev), in this case "Company-Dev-31".

How can it be achieved?

Body:
You can test if some characters are present by using in as follows:

import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    if 'dev' in st['StackName'].lower():
        print(st)

This would give you:

{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}

Converting first to lowercase has the effect of making the test case insensitive, so Dev or dev would match.


问:
Dynamic Range in Excel VBA
I have a UserForm with some Checkboxes and TextFields and when I press on the "Insert" button the inputs are pasted in row 1 column A - 7.

I have the following problem:

After I press the button, I want to fill out the UserForm again and paste the data in row 2 and then 3, 4, 5, 6 and so on. Can someone tell me how I can jump dynamically to the next row and insert there the data?

My codesnippet for a checkbox is the following:

```<code>If UserForm1.eig_hand.Value = True Then
    Range("E3").Value = "Yes"
End If
</code>```

This snippet will be executed after I press the "Insert button" and it would be very helpful, when I can close and reopen the Excel file and continue in the row where I closed the file. I know that I have a static expression in the Code snippet but I'm a completly beginner in VBA

Edit:

I found a solution for my problem.
I have a counter variable in a cell for example cell(5,1) and my code looks like this:

```<code>Dim counter_var As Integer
counter_var = Cells(5, 1)
If UserForm1.eig_hand.Value = True Then
Cells(counter_var, 4).Value = "Ja"
End If
If UserForm1.eig_kmu.Value = True Then
Cells(counter_var, 5).Value = "Ja"
End If
</code>```

And at the end of my code i set the counter_var += 1.
Ty for all the replies :)

答:
just:

```<code>Range("E" & Rows.Count).End(xlUp).Offset(1).Value= "Yes"
</code>```

But mine as well as your code has one significant weakness - they may give unexpected results when you switch between workbooks and worksheets. But it is answer for your question.

Title: Dynamic Range in Excel VBA

Body:
I have a UserForm with some Checkboxes and TextFields and when I press on the "Insert" button the inputs are pasted in row 1 column A - 7.

I have the following problem:

After I press the button, I want to fill out the UserForm again and paste the data in row 2 and then 3, 4, 5, 6 and so on. Can someone tell me how I can jump dynamically to the next row and insert there the data?

My codesnippet for a checkbox is the following:

If UserForm1.eig_hand.Value = True Then
    Range("E3").Value = "Yes"
End If

This snippet will be executed after I press the "Insert button" and it would be very helpful, when I can close and reopen the Excel file and continue in the row where I closed the file. I know that I have a static expression in the Code snippet but I'm a completly beginner in VBA

Edit:

I found a solution for my problem.
I have a counter variable in a cell for example cell(5,1) and my code looks like this:

Dim counter_var As Integer
counter_var = Cells(5, 1)
If UserForm1.eig_hand.Value = True Then
Cells(counter_var, 4).Value = "Ja"
End If
If UserForm1.eig_kmu.Value = True Then
Cells(counter_var, 5).Value = "Ja"
End If

And at the end of my code i set the counter_var += 1.
Ty for all the replies :)

Body:
just:

Range("E" & Rows.Count).End(xlUp).Offset(1).Value= "Yes"

But mine as well as your code has one significant weakness - they may give unexpected results when you switch between workbooks and worksheets. But it is answer for your question.


问:
Avoid to get user informations inside every method/controller Spring Boot
I'm using Spring Boot, and I want to show inside my navbar the name and surname of the logged user.

To do that I have to call the principal inside every method of each controller and then I have to add the information to the model.
I think there is a better way to do that. I think about the session attribute. Is it correct?

So my question is: Is the session attribute the best choice?
If yes How can I do it?

答:
You can use something along these lines directly in your jsp:
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<security:authorize access="isAuthenticated()">
    authenticated as <security:authentication property="principal.username" />
</security:authorize>
Taken from baeldung


问:
Turning NSData back to plain text NSString
I have a simple NSString and I'm converting it to NSData :

```<code>NSData *data = [[NSData dataWithBytes:[[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding]
                              length:[[NSString stringWithFormat:@",%@",self.targetId] lengthOfBytesUsingEncoding:NSASCIIStringEncoding]] retain];
</code>```

Now I want to get the plain text from the NSData object.

If I'm doing that :

```<code>NSString* dataStr = [NSString stringWithFormat:@"%@",data];
</code>```

- I'm getting just an hex expression (i.e <9c3f473e 02000000 0b0000>) and not the plain string I want !

I've tried also using initWithData -

```<code>    NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
</code>```

But it always shows gibrish, no matter which encoding I give it.

Can you please help here ?? :)

答:
You need to simplify your first code snippet to:

```<code>NSData *data = [[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding]
</code>```

And then your second decoding snippet will work:

```<code>NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
</code>```

Body:
I have a simple NSString and I'm converting it to NSData :

NSData *data = [[NSData dataWithBytes:[[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding]
                              length:[[NSString stringWithFormat:@",%@",self.targetId] lengthOfBytesUsingEncoding:NSASCIIStringEncoding]] retain];

Now I want to get the plain text from the NSData object.

If I'm doing that :

NSString* dataStr = [NSString stringWithFormat:@"%@",data];

- I'm getting just an hex expression (i.e <9c3f473e 02000000 0b0000>) and not the plain string I want !

I've tried also using initWithData -

    NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

But it always shows gibrish, no matter which encoding I give it.

Can you please help here ?? :)

Body:
You need to simplify your first code snippet to:

NSData *data = [[NSString stringWithFormat:@",%@",self.targetId] dataUsingEncoding:NSASCIIStringEncoding]

And then your second decoding snippet will work:

NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];


问:
what is @IonicPage decorator in ts.file ionic 3
What is the meaning of @IonicPage() decorator which is in ts.file ionic 3 and how to use this @IonicPage() decorator

答:
It's very important to use the @IonicPage() decorator to lazy load your pages. By using Lazy Loading you make your project navigation lighter, because the pages will only be loaded when needed.
For example, normally you would import a page in your app.module.ts so you could use it throughout the project.

```<code>import { HomePage } from '../pages/home/home';
</code>```

With lazy loading you'll only need to refer the page as a string while navigating, like this:

```<code>this.navCtrl.push('HomePage');
</code>```

Or directly in the html file like this:

```<code><button ion-button navPush="HomePage">
</code>```

In the end of it all you won't need to import pages anymore.

Remember that the page must have the module.ts so the lazy load could work.

You can understand better with this article.

Body:
It's very important to use the @IonicPage() decorator to lazy load your pages. By using Lazy Loading you make your project navigation lighter, because the pages will only be loaded when needed.
For example, normally you would import a page in your app.module.ts so you could use it throughout the project.

import { HomePage } from '../pages/home/home';

With lazy loading you'll only need to refer the page as a string while navigating, like this:

this.navCtrl.push('HomePage');

Or directly in the html file like this:

<button ion-button navPush="HomePage">

In the end of it all you won't need to import pages anymore.

Remember that the page must have the module.ts so the lazy load could work.

You can understand better with this article.


问:
Symfony injected Doctrine Manager instance to controller method arguments
In Controller, you can define a update action with following:

```<code>    /**
     * @Route("/product/edit/{id}")
     */
    public function updateAction(Product $product)
    {
     // product is auto select from database by id and inject to controller action.
    }
</code>```

The auto injection is very convenient, But how to inject the Doctrine Manager instance to controller action, it would be more convenient without create Doctrine Manager instance manually. like following:

```<code>    /**
     * @Route("/product/edit/{id}")
     */
    public function updateAction(Product $product, ObjectManager $em)
    {
       $product->setName("new name");
       $em->flush();
    }
</code>```

instead of long coding:

```<code>/**
 * @Route("/product/edit/{id}")
 */
public function updateAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository(Product::class)->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    $product->setName('New product name!');
    $em->flush();

    return $this->redirectToRoute('app_product_show', [
        'id' => $product->getId()
    ]);
}
</code>```

答:
I haven't tried Symfony4 yet, but based on official symfony documentation, there is action-based dependency injection, so you should be able to use services by declaring service interface as argument on your action.

https://symfony.com/doc/4.1/controller.html#controller-accessing-services

If you need a service in a controller, just type-hint an argument with its class (or interface) name. Symfony will automatically pass you the service you need:

So in your case it should look like this:

```<code>/**
  * @Route("/product/edit/{id}")
  */
public function updateAction(Product $product, EntityManagerInterface $em)
{
    $product->setName("new name");
    $em->flush();
}
</code>```

Body:
In Controller, you can define a update action with following:

    /**
     * @Route("/product/edit/{id}")
     */
    public function updateAction(Product $product)
    {
     // product is auto select from database by id and inject to controller action.
    }

The auto injection is very convenient, But how to inject the Doctrine Manager instance to controller action, it would be more convenient without create Doctrine Manager instance manually. like following:

    /**
     * @Route("/product/edit/{id}")
     */
    public function updateAction(Product $product, ObjectManager $em)
    {
       $product->setName("new name");
       $em->flush();
    }

instead of long coding:

/**
 * @Route("/product/edit/{id}")
 */
public function updateAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository(Product::class)->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );
    }

    $product->setName('New product name!');
    $em->flush();

    return $this->redirectToRoute('app_product_show', [
        'id' => $product->getId()
    ]);
}

Body:
I haven't tried Symfony4 yet, but based on official symfony documentation, there is action-based dependency injection, so you should be able to use services by declaring service interface as argument on your action.

https://symfony.com/doc/4.1/controller.html#controller-accessing-services

If you need a service in a controller, just type-hint an argument with its class (or interface) name. Symfony will automatically pass you the service you need:

So in your case it should look like this:

/**
  * @Route("/product/edit/{id}")
  */
public function updateAction(Product $product, EntityManagerInterface $em)
{
    $product->setName("new name");
    $em->flush();
}


问:
Shared memory for grpc client and server
My project is to read an image in a server, do some processing and then pass the whole image to the client. Client takes up the image and do some more processing and returns some output values to the server. The image being used between both the server and client is of size [640x480x3].

Following are the various techniques that came in my mind to implement this problem:

Pass the whole pixel values through the message from server to client

It takes 75ms for just sending a message from one server to one client, even if they are in the same system! (Never a good idea)

Split the whole image to chunks, and then message from server to client using stream.

There are various answers in SO for this. I am currently working on getting this working.

Assign the pixel values to a variable recognised by gRPC in both server and client. In other words have the image in a shared memory of gRPC, which could be accessed by both the server and client (assuming both server and client to be in the same system).

Is this mode of messaging between server and client possible? If yes, please provide some references to the doc or examples for the same.

答: I would say you shouldn't use gRPC. Your issue sound to me more like distributed image processing. I would recommend to use a FPGA for this kind of things. Another solution with a CPU could be R/DMA. With DMA you just bypass the CPU and uses its Memory directly. Both CPU can communicate with each other over gRPC. Let's say you have 2 server. Server A has the image, Server B wants it. Server B ask, via gRPC for the pointer address, Server A gives him the address and Server B gets it via DMA. If you use RDMA make sure you have a high speed low latency network solution. With 10 Gbit/s or more and nanoseconds latency. Both solutions are suitable for bigger images. If you just want to send smaller images just use some file transfer protocol.</p>


问:
Matplotlib error in axis drawing
I'm using Flask to generate graphs on a certain endpoint and send them to the browser. I update the data that I am graphing, but nothing else. I call the /graph endpoint once every 2 seconds, but the plot changes dramatically in that time. Examples are below:

This is the code that I am using:

```<code>@app.route('/graph')
def graph_ep():
    fig = plt.figure()

    # Matplotlib setup
    style.use('fivethirtyeight')  # Make the graphs look better

    ax1 = fig.add_subplot(1, 1, 1)

    ax1.clear()
    ax1.plot(x, y, marker='o', label="Heart Data")
    ax1.plot(x, LRL_data, marker='o', label="Lower Rate Limit")
    ax1.plot(x, URL_data, marker='o', label="Upper Rate Limit")
    ax1.set(xlabel="Time",
        ylabel="Beats per Minute",
        title="Moving Average of Heart Rate")

    ax1.legend(loc="upper center")

    ax1.grid(True)

    # Change y axis
    ax1.set_ylim(0,2.5)
    x1, x2, y1, y2 = plt.axis()
    plt.axis((x1,x2,0.0, 2.5))
    y_axis = [float(i)/10.0 for i in range(0,25,2)]
    plt.yticks(y_axis)

    time_string = str(int(time.time()))
    file_name = 'static/graphs/real/graph' + time_string + '.png'

    plt.savefig(file_name)

    return '<img src="' + file_name + '">'
</code>```

How can I keep all the features of the graph (axes, axis labels, grid, etc) the same as the first image while only updating the data?

答: Turns out the data in the array y was inconsistent. I had strings and floats in it at the same time, which was confusing matplotlib. For example, [0.0, 0.1, '0.2', '0.3', '0.4']. Once I converted the strings to floats, the issue was mostly resolved. However, the axis labels are still hidden.

Title: Matplotlib error in axis drawing

Body:
I'm using Flask to generate graphs on a certain endpoint and send them to the browser. I update the data that I am graphing, but nothing else. I call the /graph endpoint once every 2 seconds, but the plot changes dramatically in that time. Examples are below:

This is the code that I am using:

@app.route('/graph')
def graph_ep():
    fig = plt.figure()

    # Matplotlib setup
    style.use('fivethirtyeight')  # Make the graphs look better

    ax1 = fig.add_subplot(1, 1, 1)

    ax1.clear()
    ax1.plot(x, y, marker='o', label="Heart Data")
    ax1.plot(x, LRL_data, marker='o', label="Lower Rate Limit")
    ax1.plot(x, URL_data, marker='o', label="Upper Rate Limit")
    ax1.set(xlabel="Time",
        ylabel="Beats per Minute",
        title="Moving Average of Heart Rate")

    ax1.legend(loc="upper center")

    ax1.grid(True)

    # Change y axis
    ax1.set_ylim(0,2.5)
    x1, x2, y1, y2 = plt.axis()
    plt.axis((x1,x2,0.0, 2.5))
    y_axis = [float(i)/10.0 for i in range(0,25,2)]
    plt.yticks(y_axis)

    time_string = str(int(time.time()))
    file_name = 'static/graphs/real/graph' + time_string + '.png'

    plt.savefig(file_name)

    return ''

How can I keep all the features of the graph (axes, axis labels, grid, etc) the same as the first image while only updating the data?


问:
Replacing character with File.separator using java.regex Pattern Matcher
I have a field called 'path' in back end database, which stores the path to certain resource. Instead of storing lots of backslashed (escaped) path for windows path, my idea is to let user enter the path with certain character as file separator (independent of OS).

For example:

original path:

```<code>\\\\server\\share\\
</code>```

with escaped path in db:

```<code>\\\\\\\\server\\\\share\\\\
</code>```

instead I want:

```<code>%%server%share%
</code>```

and later I wanted to replace those with java's File.separator for the real thing. For this job, the quickest solution I found is to use the java.regex Pattern Matcher.

My function for this job is:

```<code>private String convertToRealPathFromDB(String pth) {
    String patternStr = "%";
    String replaceStr = File.separator;
    String convertedpath;

    //Compile regular expression
    Pattern pattern = Pattern.compile(patternStr); //pattern to look for

    //replace all occurance of percentage character to file separator
    Matcher matcher = pattern.matcher(pth);
    convertedpath = matcher.replaceAll(replaceStr);

    System.out.println(convertedpath);

    return convertedpath;
}
</code>```

but the same File.separator which was supposed to save life is creating trouble with

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

I have tested with other characters (for example: replace '%' with 'q') and this function works fine but File.separator and "\\\\" as replace string is not working.

I like to know it there is workaround for this. Or better, easier and elegant solution.

答:
```<code> String str = " \\server\\share\\";
 String result = str.replaceAll("\\\\", "%%");
 System.out.println(result);
</code>```

Output

```<code> %%server%%share%%
</code>```

and back

```<code>String path=null;
if (File.separator.equals("\\")) {
    path = result.replaceAll("%%", "\\\\");
} else {
    path = result.replaceAll("%%", "//");
}
</code>```

Body:
I have a field called 'path' in back end database, which stores the path to certain resource. Instead of storing lots of backslashed (escaped) path for windows path, my idea is to let user enter the path with certain character as file separator (independent of OS).

For example:

original path:

\\\\server\\share\\

with escaped path in db:

\\\\\\\\server\\\\share\\\\

instead I want:

%%server%share%

and later I wanted to replace those with java's File.separator for the real thing. For this job, the quickest solution I found is to use the java.regex Pattern Matcher.

My function for this job is:

private String convertToRealPathFromDB(String pth) {
    String patternStr = "%";
    String replaceStr = File.separator;
    String convertedpath;

    //Compile regular expression
    Pattern pattern = Pattern.compile(patternStr); //pattern to look for

    //replace all occurance of percentage character to file separator
    Matcher matcher = pattern.matcher(pth);
    convertedpath = matcher.replaceAll(replaceStr);

    System.out.println(convertedpath);

    return convertedpath;
}

but the same File.separator which was supposed to save life is creating trouble with

java.lang.StringIndexOutOfBoundsException: String index out of range: 1

I have tested with other characters (for example: replace '%' with 'q') and this function works fine but File.separator and "\\\\" as replace string is not working.

I like to know it there is workaround for this. Or better, easier and elegant solution.

Body:
 String str = " \\server\\share\\";
 String result = str.replaceAll("\\\\", "%%");
 System.out.println(result);

Output

 %%server%%share%%

and back

String path=null;
if (File.separator.equals("\\")) {
    path = result.replaceAll("%%", "\\\\");
} else {
    path = result.replaceAll("%%", "//");
}


问:
How to read and write a vector of struct to a file?
I am currently trying to read and write a vector of structs to a binary file, such that I don't spends on preprocessing it with filling it up all the time.

I seem to have some problems doing so... I though that i could std::ofstream but that doesn't seem to be the case.

```<code>#include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>

struct element
{
    std::vector<std::pair<int, int>> coord;
    element(std::vector<std::pair<int, int>> set_coord )
    {
         coord = set_coord;
    }
};

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> matrix;

    std::ofstream datafile;
    datafile.open("path/to/file");
    datafile<<matrix;
    datafile.close();
}
</code>```

https://wandbox.org/permlink/urCHoETdh7vE3xlE

I am getting an error message that the operator<< is not valid here... but why?

答:
If you want to use the stream operator directly you have to overload it for your struct. Something like this:

```<code>#include <iostream>
#include <vector>

struct MyStruct {
    using coordinates = std::vector<std::pair<int, int>>;
    MyStruct(coordinates c) : c(c) {};

    friend std::ostream& operator<<(std::ostream& os, const MyStruct& m) {
        for (const auto &pair : m.c) {
            os << "First: " << pair.first << "; Second: " << pair.second;
        }
        return os;
    }

private:
    coordinates c;
};

class MyVector {
public:
    MyVector(std::initializer_list<MyStruct> list) : elements(list) {}

    friend std::ostream& operator<<(std::ostream& os, const MyVector& m) {
        for (const auto &ms : m.elements) {
            os << ms << std::endl;
        }
        return os;
    }

private:
    std::vector<MyStruct> elements;
};

int main()
{
    MyStruct m1({{1, 2}});
    MyStruct m2({{3, 4}});
    MyVector vec({m1, m2});
    std::cout << vec << std::endl;
    return 0;
}
</code>```

I've edited the code so it does work with a vector as a member. And in a second edit I am using my own (very basic) vector implementation

Here is the code on wandbox

Body:
I am currently trying to read and write a vector of structs to a binary file, such that I don't spends on preprocessing it with filling it up all the time.

I seem to have some problems doing so... I though that i could std::ofstream but that doesn't seem to be the case.

#include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>

struct element
{
    std::vector<std::pair<int, int>> coord;
    element(std::vector<std::pair<int, int>> set_coord )
    {
         coord = set_coord;
    }
};

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> matrix;

    std::ofstream datafile;
    datafile.open("path/to/file");
    datafile<<matrix;
    datafile.close();
}

https://wandbox.org/permlink/urCHoETdh7vE3xlE

I am getting an error message that the operator<< is not valid here... but why?

Body:
If you want to use the stream operator directly you have to overload it for your struct. Something like this:

#include <iostream>
#include <vector>

struct MyStruct {
    using coordinates = std::vector<std::pair<int, int>>;
    MyStruct(coordinates c) : c(c) {};

    friend std::ostream& operator<<(std::ostream& os, const MyStruct& m) {
        for (const auto &pair : m.c) {
            os << "First: " << pair.first << "; Second: " << pair.second;
        }
        return os;
    }

private:
    coordinates c;
};

class MyVector {
public:
    MyVector(std::initializer_list<MyStruct> list) : elements(list) {}

    friend std::ostream& operator<<(std::ostream& os, const MyVector& m) {
        for (const auto &ms : m.elements) {
            os << ms << std::endl;
        }
        return os;
    }

private:
    std::vector<MyStruct> elements;
};

int main()
{
    MyStruct m1({{1, 2}});
    MyStruct m2({{3, 4}});
    MyVector vec({m1, m2});
    std::cout << vec << std::endl;
    return 0;
}

I've edited the code so it does work with a vector as a member. And in a second edit I am using my own (very basic) vector implementation

Here is the code on wandbox


问:
How to query the data present in Stream[java.io.File] in Scala?
Using Scala I am trying to list all the files in a directory and then read the file attributes.
In my case, I am trying to read the file attribute: creation date.
The files are present in local and after doing some research, I was able to list all the files in a directory in Linux using the below code:

```<code>import java.io.File
import scala.collection.JavaConversions._

def getFileTree(f: File): Stream[File] =
        f #:: (if (f.isDirectory) f.listFiles().toStream.flatMap(getFileTree)
               else Stream.empty)

val filesList = getFileTree(new File("/tmp/hive_audits/"))
</code>```

fileList is created in the following format:

```<code>files: Stream[java.io.File] = Stream(/tmp/hive_audits, ?)
</code>```

I understood that it is in the form of a collection. But I unable to understand how to query the 'fileList', like iterate thru the files present in the directory and then get the creation date of it.
Could anyone let me know how can I do it ?

答:
You can iterate through with .foreach also with for (file <- files) {...}:

```<code> for (file <- files) println(new java.util.Date(file.lastModified))
</code>```

The java.io.File API does not support creation date.

Body:
Using Scala I am trying to list all the files in a directory and then read the file attributes.
In my case, I am trying to read the file attribute: creation date.
The files are present in local and after doing some research, I was able to list all the files in a directory in Linux using the below code:

import java.io.File
import scala.collection.JavaConversions._

def getFileTree(f: File): Stream[File] =
        f #:: (if (f.isDirectory) f.listFiles().toStream.flatMap(getFileTree)
               else Stream.empty)

val filesList = getFileTree(new File("/tmp/hive_audits/"))

fileList is created in the following format:

files: Stream[java.io.File] = Stream(/tmp/hive_audits, ?)

I understood that it is in the form of a collection. But I unable to understand how to query the 'fileList', like iterate thru the files present in the directory and then get the creation date of it.
Could anyone let me know how can I do it ?

Body:
You can iterate through with .foreach also with for (file <- files) {...}:

 for (file <- files) println(new java.util.Date(file.lastModified))

The java.io.File API does not support creation date.


问:
Unable to pass json row in dynamically created table using angular JS
I'm creating a table dynamically using Angular JS. In my table, I have to pass JSON row. But when it renders it's showing error !

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object] | QcDetailsManualAuto] starting at [Object] | QcDetailsManualAuto].

CODE :

```<code>var jData = JSON.parse(response.data);
             var vQCTableData = jData.ResultData;
            var vQCTable = '';
            vQCTable += "<table class=\"table table-striped table-bordered table-hover\" id=\"qctable\">";
            vQCTable += "<thead>";
            vQCTable += "<tr>";
            vQCTable += "<th>SOM</th>";
            vQCTable += "<th>EOM</th>";
            vQCTable += "<th>Type of Error</th>";
            vQCTable += "<th>QC Type</th>";
            vQCTable += "<th>Remarks</th>";
            vQCTable += "<th>Action</th>";
            vQCTable += "</tr>";
            vQCTable += "</thead>";
            for(var td in vQCTableData)
            {
                vQCTable += "<tbody>";
                vQCTable += "<tr class=\"wer1\" ng-if=\"" + vQCTableData[td] + " | QcDetailsManualAuto\">";
                vQCTable += "<td>" +vQCTableData[td].SOM+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].EOM+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].Parameter+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].QCType+ "</td>";
                vQCTable += "<td>" +vQCTableData[td].Remarks+ "</td>";
                vQCTable += "<td class=\"MediaDataListPointer\">";
                vQCTable += "<span ng-click=\"QCParameterEdit(" + vQCTableData[td] + ")\" title=\"Edit\" class=\"glyphicon glyphicon-pencil QualityCheckIcons\"></span>";
                vQCTable += "<span ng-click=\"DeleteMQC(" + vQCTableData[td] + ")\" title=\"Delete\" class=\"glyphicon glyphicon-trash QualityCheckIcons\"></span>";
                vQCTable += "</td>";
                vQCTable += "</tr>";
                vQCTable += " </tbody>";
            }
            vQCTable += "</table>";

            var mediadiv = angular.element(document.querySelector('#mediadiv'));
            mediadiv.html($compile(vQCTable)($scope));
</code>```

In [response] I m getting data after calling URL.

QCParameterEdit function require json row for its functionality

```<code>    $scope.QCParameterEdit = function (data) {
    $("#GenerateMarksModal").modal();
    $scope.QCPDRButton = "Update";
    $scope.somModel = data.SOM;
    $scope.eomModel = data.EOM;
    $scope.qCParameterModel = data.QcParamUID;
    $scope.typeOfErrorModel = data.Type;
    $scope.typeModel = data.Type;
    $scope.remarksModel = data.Remarks;
    $scope.UID = data.UID;
    $scope.QcParameterIUDSuccess = false;
    $scope.QcParameterIUDFailure = false;
    $scope.QcParameterIUDSMessage = '';
    $scope.QcParameterIUDFMessage = '';
};
</code>```

QcDetailsManualAuto is angular custom filter [Can not change it because it being used at multiple places]

```<code>app.filter('QcDetailsManualAuto', function () {
return function (value) {
    var result = false;
    if (value.QCType == 'Auto' || value.QCType == 'Manual') { result = true; }
    return result;
};
});
</code>```

Thanks in Advance!

答:
You have to use filter in controller instead of html something like

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $compile,$filter) {
var data=[
    {
        "UID": "d465703c-504c-4a4f-b8e2-2877b0eadc1",
        "QCType": "Manual"
    }
]

var vQCTable = '';
            vQCTable += "
";
            vQCTable += "
";
            vQCTable += "
";
            vQCTable += "SOM	";
            vQCTable += "EOM	";
            vQCTable += "
";
            vQCTable += "
";
            for(var td in data)
            {
                vQCTable += "
";
                //notice the line below
                vQCTable += "
";
                vQCTable += "" +data[td].QCType+ "	";
                vQCTable += "
";
                vQCTable += "
";
            }
            vQCTable += "
";
           console.log("your html string"+vQCTable);
          })

myApp.filter('QcDetailsManualAuto', function () {
return function (value) {
    var result = false;
    if (value.QCType == 'Auto' || value.QCType == 'Manual') { result = true; }
    return result;
};
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div></code>```

Body:
I'm creating a table dynamically using Angular JS. In my table, I have to pass JSON row. But when it renders it's showing error !

Error: [$parse:syntax] Syntax Error: Token 'Object' is unexpected, expecting []] at column 9 of the expression [[object Object] | QcDetailsManualAuto] starting at [Object] | QcDetailsManualAuto].

CODE :

var jData = JSON.parse(response.data);
             var vQCTableData = jData.ResultData;
            var vQCTable = '';
            vQCTable += "
";
            vQCTable += "
";
            vQCTable += "
";
            vQCTable += "SOM	";
            vQCTable += "EOM	";
            vQCTable += "Type of Error	";
            vQCTable += "QC Type	";
            vQCTable += "Remarks	";
            vQCTable += "Action	";
            vQCTable += "
";
            vQCTable += "
";
            for(var td in vQCTableData)
            {
                vQCTable += "
";
                vQCTable += "
";
                vQCTable += "" +vQCTableData[td].SOM+ "	";
                vQCTable += "" +vQCTableData[td].EOM+ "	";
                vQCTable += "" +vQCTableData[td].Parameter+ "	";
                vQCTable += "" +vQCTableData[td].QCType+ "	";
                vQCTable += "" +vQCTableData[td].Remarks+ "	";
                vQCTable += "";
                vQCTable += "";
                vQCTable += "";
                vQCTable += "	";
                vQCTable += "
";
                vQCTable += "
";
            }
            vQCTable += "
";

            var mediadiv = angular.element(document.querySelector('#mediadiv'));
            mediadiv.html($compile(vQCTable)($scope));

In [response] I m getting data after calling URL.

QCParameterEdit function require json row for its functionality

    $scope.QCParameterEdit = function (data) {
    $("#GenerateMarksModal").modal();
    $scope.QCPDRButton = "Update";
    $scope.somModel = data.SOM;
    $scope.eomModel = data.EOM;
    $scope.qCParameterModel = data.QcParamUID;
    $scope.typeOfErrorModel = data.Type;
    $scope.typeModel = data.Type;
    $scope.remarksModel = data.Remarks;
    $scope.UID = data.UID;
    $scope.QcParameterIUDSuccess = false;
    $scope.QcParameterIUDFailure = false;
    $scope.QcParameterIUDSMessage = '';
    $scope.QcParameterIUDFMessage = '';
};

QcDetailsManualAuto is angular custom filter [Can not change it because it being used at multiple places]

app.filter('QcDetailsManualAuto', function () {
return function (value) {
    var result = false;
    if (value.QCType == 'Auto' || value.QCType == 'Manual') { result = true; }
    return result;
};
});

Thanks in Advance!

Body:
You have to use filter in controller instead of html something like

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $compile,$filter) {
var data=[
    {
        "UID": "d465703c-504c-4a4f-b8e2-2877b0eadc1",
        "QCType": "Manual"
    }
]

var vQCTable = '';
            vQCTable += "<table class=\"table table-striped table-bordered table-hover\" id=\"qctable\">";
            vQCTable += "<thead>";
            vQCTable += "<tr>";
            vQCTable += "<th>SOM</th>";
            vQCTable += "<th>EOM</th>";
            vQCTable += "</tr>";
            vQCTable += "</thead>";
            for(var td in data)
            {
                vQCTable += "<tbody>";
                //notice the line below
                vQCTable += "<tr class=\"wer1\" ng-if=\"" + $filter('QcDetailsManualAuto')(data[td]) + ">";
                vQCTable += "<td>" +data[td].QCType+ "</td>";
                vQCTable += "</tr>";
                vQCTable += " </tbody>";
            }
            vQCTable += "</table>";
           console.log("your html string"+vQCTable);
          })

myApp.filter('QcDetailsManualAuto', function () {
return function (value) {
    var result = false;
    if (value.QCType == 'Auto' || value.QCType == 'Manual') { result = true; }
    return result;
};
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>


问:
Python spyder: changing a function in another file takes no effect
Using spyder 3.2.4 with python.

When I call i function (in another file) lets call it my_func() from my main script, it uses the "old version" of that function. Clarification:

If i change my_func and save that file, the new version of the function is used if called from my main script, BUT only if I run the entire main script.

If i just run the lines with my_func (using run cell or run selected lines) the OLD version of my_func (before the changes was mad) is used.

I though my_func had to be "reimported" (from myOtherFile import my_func), so I try to run those lines as well, but the old version of the function (not changed) is still used.

Did I misunderstand something or is this a really, really serious bug? If i close down spyder and restart it it works (it uses the new version of the function) but that's an unacceptable solution.

答:
This behavior has to do with how the (I)Python interpreter handles imports.

You can find a detailed explanation (with possible solutions) here: https://support.enthought.com/hc/en-us/articles/204469240-Jupyter-IPython-After-editing-a-module-changes-are-not-effective-without-kernel-restart

Short answer:

- either restart the kernel

- or use importlib.reload (https://docs.python.org/3/library/importlib.html#importlib.reload)

- or use IPython's autoreload extension (http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html)


问:
Thinking Sphinx display options
Ok so i have a graphic model and I am using thinking sphinx as the search tool. It works well but i want to display different models on the search results page.. for example

i have this in my Graphic model

```<code>define_index do
 indexes :name, :description, :scale,
 indexes sub_category.name, :as => :subcategory_name
 indexes sub_category.category.name, :as => :category_name
 indexes colors.name, :as => :color_name
end
</code>```

This is fine and good but the problem is i want to display all the categories and subcategories for a found search and not just the graphics that are related. In my controller should i have three find like

```<code>@graphics = Graphic.search params[:search]
@categories = Categories.search params[:search]
@sub_categories = SubCategories.search params[:search]
</code>```

this seems like overkill...is there a better way so in the view i can show each of them seperately

答:
You'll need to have indexes defined in your Category and SubCategory models as well, and then you can search across all three at once:

```<code>@results = ThinkingSphinx.search params[:search], :page => params[:page]
</code>```

In your view, you'll want some logic around each search result to render the correct HTML - perhaps you can have different partials for each class? I'd also recommend wrapping it into a helper. Here's a start:

```<code><ul>
  <% @results.each do |result| %>
    <li><%= render :partial => partial_for_search_result(result),
              :locals => {:result => result} %></li>
  <% end %>
</ul>
</code>```

And the helper:

```<code>def partial_for_search_result(result)
  case result
  when Graphic
    'graphics/search_result'
  when Category
    'categories/search_result'
  when SubCategory
    'sub_categories/search_result'
  else
    raise "Unknown search result/partial mapping for #{result.class}"
  end
end
</code>```

Hopefully this gives you some ideas on how to approach the problem.

Title: Thinking Sphinx display options

Body:
Ok so i have a graphic model and I am using thinking sphinx as the search tool. It works well but i want to display different models on the search results page.. for example

i have this in my Graphic model

define_index do
 indexes :name, :description, :scale,
 indexes sub_category.name, :as => :subcategory_name
 indexes sub_category.category.name, :as => :category_name
 indexes colors.name, :as => :color_name
end

This is fine and good but the problem is i want to display all the categories and subcategories for a found search and not just the graphics that are related. In my controller should i have three find like

@graphics = Graphic.search params[:search]
@categories = Categories.search params[:search]
@sub_categories = SubCategories.search params[:search]

this seems like overkill...is there a better way so in the view i can show each of them seperately

Body:
You'll need to have indexes defined in your Category and SubCategory models as well, and then you can search across all three at once:

@results = ThinkingSphinx.search params[:search], :page => params[:page]

In your view, you'll want some logic around each search result to render the correct HTML - perhaps you can have different partials for each class? I'd also recommend wrapping it into a helper. Here's a start:

<ul>
  <% @results.each do |result| %>
    <li><%= render :partial => partial_for_search_result(result),
              :locals => {:result => result} %></li>
  <% end %>
</ul>

And the helper:

def partial_for_search_result(result)
  case result
  when Graphic
    'graphics/search_result'
  when Category
    'categories/search_result'
  when SubCategory
    'sub_categories/search_result'
  else
    raise "Unknown search result/partial mapping for #{result.class}"
  end
end

Hopefully this gives you some ideas on how to approach the problem.


问:
trigger('click') vs trigger('click')[0]
I am unable to differentiate between trigger('click') vs trigger('click')[0], is there any difference between them?

答:
A lot of methods in jQuery return the original jQuery collection to allow for easier chaining.

For instance

```<code>jQuery("body").trigger("click").css("background", "red");
// returns the jQuery collection.
</code>```

If you use an index to access a jQuery collection, you'll get the corresponding DOM element, in my example, document.body.

Title: trigger('click') vs trigger('click')[0]

Body:
A lot of methods in jQuery return the original jQuery collection to allow for easier chaining.

For instance

jQuery("body").trigger("click").css("background", "red");
// returns the jQuery collection.

If you use an index to access a jQuery collection, you'll get the corresponding DOM element, in my example, document.body.


问:
Text-decoration not working in Google chrome drop down (Select) option
I have the drop down list, and i want to strike through the specific option.
I'm using the below sample code, the red color is working fine but line-through is working in IE, but not working in chrome

```<code><select>
<option>option 1</option>
<option style="text-decoration:line-through; color:red;">option 2</option>
<option>option 3</option>
</select>
</code>```

I want to apply this without any jquery or any other library, just by directly through JavaScript & css

答:
A crude but working way to do this would be to just use a Unicode text generator like this one http://adamvarga.com/strike/. And it would end up working like this:

    <select>
        <option>option 1</option>
        <option>s̶t̶r̶o̶k̶e̶n̶</option>
        <option>option 3</option>
    </select>```

I am guessing it's a bug in chrome from what people before me wrote

Body:
I have the drop down list, and i want to strike through the specific option.
I'm using the below sample code, the red color is working fine but line-through is working in IE, but not working in chrome

<select>
<option>option 1</option>
<option style="text-decoration:line-through; color:red;">option 2</option>
<option>option 3</option>
</select>

I want to apply this without any jquery or any other library, just by directly through JavaScript & css

Body:
A crude but working way to do this would be to just use a Unicode text generator like this one http://adamvarga.com/strike/. And it would end up working like this:

    <select>
        <option>option 1</option>
        <option>s̶t̶r̶o̶k̶e̶n̶</option>
        <option>option 3</option>
    </select>

I am guessing it's a bug in chrome from what people before me wrote


问:
Access props inside a closure
calling this.props.navigation.dispatch(resetAction); inside componentWillMount() works fine for me, but if I try this code

```<code>componentWillMount(){
    Keychain
    .getGenericPassword()
    .then(function(credentials) {
         this.props.navigation.dispatch(resetAction);
    })
}
</code>```

I get an error telling me that this.props.navigation is undefined. I suppose that the problem is that I am calling it inside .then. Do you know how can I solve this?

答:
you just change the scope of this

try this

```<code>componentWillMount(){
Keychain
  .getGenericPassword()
  .then((credentials)=>{
this.props.navigation.dispatch(resetAction);
});
</code>```

or else use extra val for this like

```<code>var _self = this;
</code>```

Title: Access props inside a closure

Body:
calling this.props.navigation.dispatch(resetAction); inside componentWillMount() works fine for me, but if I try this code

componentWillMount(){
    Keychain
    .getGenericPassword()
    .then(function(credentials) {
         this.props.navigation.dispatch(resetAction);
    })
}

I get an error telling me that this.props.navigation is undefined. I suppose that the problem is that I am calling it inside .then. Do you know how can I solve this?

Body:
you just change the scope of this

try this

componentWillMount(){
Keychain
  .getGenericPassword()
  .then((credentials)=>{
this.props.navigation.dispatch(resetAction);
});

or else use extra val for this like

var _self = this;


问:
Adding content property to serialization
Whenever I use a custom serializer in spring data rest, it adds a "content" property that wrapps the object returned, like:

```<code>{
   "content":{
      object properties...
   },
   _links: {
   }
}
</code>```

EDIT: Add configuration class

```<code>@Configuration
public class JacksonCustomizations {

    @Bean
    public Module rateModule() {
        return new RateModule();
    }

    @SuppressWarnings("serial")
    static class RateModule extends SimpleModule {

        public RateModule() {
            setMixInAnnotation(Package.class, RateModule.PackageMixin.class);
            setMixInAnnotation(Section.class, RateModule.SectionMixin.class);
            setMixInAnnotation(MainPart.class, RateModule.MainPartMixin.class);
            setMixInAnnotation(SubPart.class, RateModule.SubPartMixin.class);

            addSerializer(MaintenanceTask.class, new MaintenanceTaskSerializer());

            addDeserializer(Package.class, new PackageDeserializer());
            addDeserializer(Section.class, new SectionDeserializer());
            addDeserializer(MainPart.class, new MainPartDeserializer());
            addDeserializer(MaintenanceTask.class, new MaintenanceTaskDeserializer());
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class PackageMixin {

            @JsonProperty("name") public abstract String getName();
            @JsonProperty("sections") public abstract List<Section> getSections();
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class SectionMixin {

            @JsonProperty("id") public abstract Long getId();
            @JsonProperty("name") public abstract String getName();
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class MainPartMixin {

            @JsonProperty("name") public abstract String getName();
            @JsonProperty("subparts") public abstract List<SubPart> getSubParts();
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class SubPartMixin {

            @JsonProperty("id") public abstract Long getId();
            @JsonProperty("name") public abstract String getName();
        }

        static class MaintenanceTaskSerializer extends JsonSerializer<MaintenanceTask> {

            @Override
            public void serialize(final MaintenanceTask value, final JsonGenerator gen, final SerializerProvider serializers)
                    throws IOException, JsonProcessingException {
                gen.writeStartObject();
                gen.writeNumberField("id", value.getId());
                gen.writeStringField("maintenanceRequirementId", value.getMaintenanceRequirementId());
                gen.writeStringField("type", value.getType().toString());
                gen.writeStringField("title", value.getTitle());
                gen.writeStringField("description", value.getDescription());
                gen.writeStringField("note", value.getNote());
                gen.writeStringField("effectivity", value.getEffectivity());
                gen.writeNumberField("procedureReference", value.getReferenceTask().getId());
                gen.writeNumberField("aircraftModel", value.getAircraftModel().getId());
                gen.writeNumberField("packageId", value.getPack().getId());
                gen.writeNumberField("sectionId", value.getSection().getId());
                gen.writeStringField("taskType", value.getTaskType().toString());
                gen.writeEndObject();
            }

        }
    }
}
</code>```

But when I use spring data rest serialization without custom serializers, the property is not inserted.

How can I prevent this property from showing?

答:
This is an known issue.

It has been reported here: https://jira.spring.io/browse/DATAREST-504

The issue points to this stack overflow question: Different JSON output when using custom json serializer in Spring Data Rest

Body:
Whenever I use a custom serializer in spring data rest, it adds a "content" property that wrapps the object returned, like:

{
   "content":{
      object properties...
   },
   _links: {
   }
}

EDIT: Add configuration class

@Configuration
public class JacksonCustomizations {

    @Bean
    public Module rateModule() {
        return new RateModule();
    }

    @SuppressWarnings("serial")
    static class RateModule extends SimpleModule {

        public RateModule() {
            setMixInAnnotation(Package.class, RateModule.PackageMixin.class);
            setMixInAnnotation(Section.class, RateModule.SectionMixin.class);
            setMixInAnnotation(MainPart.class, RateModule.MainPartMixin.class);
            setMixInAnnotation(SubPart.class, RateModule.SubPartMixin.class);

            addSerializer(MaintenanceTask.class, new MaintenanceTaskSerializer());

            addDeserializer(Package.class, new PackageDeserializer());
            addDeserializer(Section.class, new SectionDeserializer());
            addDeserializer(MainPart.class, new MainPartDeserializer());
            addDeserializer(MaintenanceTask.class, new MaintenanceTaskDeserializer());
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class PackageMixin {

            @JsonProperty("name") public abstract String getName();
            @JsonProperty("sections") public abstract List
 getSections();
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class SectionMixin {

            @JsonProperty("id") public abstract Long getId();
            @JsonProperty("name") public abstract String getName();
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class MainPartMixin {

            @JsonProperty("name") public abstract String getName();
            @JsonProperty("subparts") public abstract List<SubPart> getSubParts();
        }

        @JsonAutoDetect(fieldVisibility=Visibility.NONE, getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE)
        static abstract class SubPartMixin {

            @JsonProperty("id") public abstract Long getId();
            @JsonProperty("name") public abstract String getName();
        }

        static class MaintenanceTaskSerializer extends JsonSerializer<MaintenanceTask> {

            @Override
            public void serialize(final MaintenanceTask value, final JsonGenerator gen, final SerializerProvider serializers)
                    throws IOException, JsonProcessingException {
                gen.writeStartObject();
                gen.writeNumberField("id", value.getId());
                gen.writeStringField("maintenanceRequirementId", value.getMaintenanceRequirementId());
                gen.writeStringField("type", value.getType().toString());
                gen.writeStringField("title", value.getTitle());
                gen.writeStringField("description", value.getDescription());
                gen.writeStringField("note", value.getNote());
                gen.writeStringField("effectivity", value.getEffectivity());
                gen.writeNumberField("procedureReference", value.getReferenceTask().getId());
                gen.writeNumberField("aircraftModel", value.getAircraftModel().getId());
                gen.writeNumberField("packageId", value.getPack().getId());
                gen.writeNumberField("sectionId", value.getSection().getId());
                gen.writeStringField("taskType", value.getTaskType().toString());
                gen.writeEndObject();
            }

        }
    }
}

But when I use spring data rest serialization without custom serializers, the property is not inserted.

How can I prevent this property from showing?


问:
Running executable from Android shell
I copied my executable file to Android '/data/local/tmp' directory using

```<code>adb push /home/build/bin/myexec /data/local/tmp
</code>```

I then changed the permission of the executable

```<code>chmod 755 myexec
</code>```

When I tried  ./myexec

I got this /system/bin/sh: myexec: not found

I understand that it is not working because it is not on the system's bin folder. Is it possible to run executable through the Android's shell or through an Android app?

答:
Use full executable path

```<code>/data/local/tmp/myexec
</code>```

Or change directory first:

```<code>cd /data/local/tmp/
./myexec
</code>```

Title: Running executable from Android shell

Body:
I copied my executable file to Android '/data/local/tmp' directory using

adb push /home/build/bin/myexec /data/local/tmp

I then changed the permission of the executable

chmod 755 myexec

When I tried  ./myexec

I got this /system/bin/sh: myexec: not found

I understand that it is not working because it is not on the system's bin folder. Is it possible to run executable through the Android's shell or through an Android app?

Body:
Use full executable path

/data/local/tmp/myexec

Or change directory first:

cd /data/local/tmp/
./myexec


问:
Avoid to get user informations inside every method/controller Spring Boot
I'm using Spring Boot, and I want to show inside my navbar the name and surname of the logged user.

To do that I have to call the principal inside every method of each controller and then I have to add the information to the model.
I think there is a better way to do that. I think about the session attribute. Is it correct?

So my question is: Is the session attribute the best choice?
If yes How can I do it?

答:
here is link to proposed solution using ControllerAdvice

How to display current logged-in user's information in all templates including view managed by WebMvcConfigurerAdapter in Spring Security application


问:
Maven project can not be created in Eclipse through Proxy
Im using eclipse Neon and working behind a proxy.  Below message boxes are displayed when im trying to create a maven project using an archetype.

"Could not resolve archetype XXXXXXXX from any of the configured repositories."

"Creating xxxxx has encountered a problem. Could not resolve archetype xxxx from any of the configured repositories"

I have configured the below settings correctly.
1. Proxy settings in Eclipse
2. Proxy settings in maven setting.xml file
3. Add the remote catalog as "http://repo1.maven.org/maven2/archetype-catalog.xml"

However, when i go to error description, it says "unexpected end of stream on connection" and it shows my proxy IP and port. Just to check, i have altered proxy IP in the setting.xml file and eclipse proxy setting but it shows the same IP and PORT in the error description without any change. I have no idea from where maven refers the proxy settings. Please advice.

Thanks in Advance

答:
The same error made me struggle alot, I could download testNG and other things from eclipse marketplace, but when i'm creating a maven project i got this error. Because my internet connection is going through proxy.
I tried all the above but i couldn't resolve this error, but this guy gave me the solution:

http://www.javahelps.com/2015/08/set-proxy-for-maven-in-eclipse.html

After the above procedure is done, then you have to delete the existing quickstart-archetype from below folder
C:\Users.m2\repository\org\apache\maven\archetypes

then restart the eclipse and create a new maven project with new project name.
Since this is only a proxy issue, so no need to specify the arche types and all. This should work if it's a proxy related issue.


问:
How to create a sample single-column Spark DataFrame in Python?
I want to create a sample single-column DataFrame, but the following code is not working:

df = spark.createDataFrame(["10","11","13"], ("age"))

## ValueError
## ...
## ValueError: Could not parse datatype: age
```
<p>The expected result:</p>
<pre class="lang-none prettyprint-override"><code>age
10
11
13
</code>```

答:
the following code is not working

With single element you need a schema as type

```<code>spark.createDataFrame(["10","11","13"], "string").toDF("age")
</code>```

or DataType:

```<code>from pyspark.sql.types import StringType

spark.createDataFrame(["10","11","13"], StringType()).toDF("age")
</code>```

With name elements should be tuples and schema as sequence:

```<code>spark.createDataFrame([("10", ), ("11", ), ("13",  )], ["age"])
</code>```

Body:
I want to create a sample single-column DataFrame, but the following code is not working:

df = spark.createDataFrame(["10","11","13"], ("age"))

## ValueError
## ...
## ValueError: Could not parse datatype: age

The expected result:

age
10
11
13

Body:
the following code is not working

With single element you need a schema as type

spark.createDataFrame(["10","11","13"], "string").toDF("age")

or DataType:

from pyspark.sql.types import StringType

spark.createDataFrame(["10","11","13"], StringType()).toDF("age")

With name elements should be tuples and schema as sequence:

spark.createDataFrame([("10", ), ("11", ), ("13",  )], ["age"])


问:
Server DateTime issue -> client get bad experience
If server is located in US and website user is from Asia, when user add a new comment, he sees that the comment is added 10 hours ago because there is 10 hours timing difference in Asia and US.

What I want to do is when displaying comment, automatically convert date time to the time of target country or region where user come from.

Track user region/country

DateTime in any webpage should be converted to that country time

So that I can display user that he posted comment a few second ago...

答:
Handle all dates internally as UTC,
meaning 0 hour offset

Use the language/country part of the user-agent string or the ip address to detect where the user is from, and look up the timezone.

Use TimeZoneInfo.ConvertTime(..) to convert the UAC time to the users local time

Point 2 will be the most work unless you find some lookup table or existing code to do this.