问:
Spring-shell usage
I'm trying to use spring-shell.
 Created such class:

```<code>@Component
public class T implements CommandMarker {

public T() {
    System.out.println("T Constructor");
}

@CliCommand(value = "trans", help = "translate")
public String translate(@CliOption(key = { "msg" },
    mandatory = false, help = "The hello world message")
    final String msg) {
    System.out.println("!!! " + msg);
    return "!!! " + msg;
  }
}
</code>```

and have such spring-shell-plugin.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.1.xsd">

   <context:component-scan base-package="com" />

</beans>
</code>```

Class that starting application:

```<code>public class Main {

public static void main(String[] args) {
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("classpath*:/META-INF/spring/spring-shell-plugin.xml");
    context.start();
}
}
</code>```

But as a result I'm just getting in console only 'T Constructor' althought I'm passing arguments 'trans --msg f'.

How to make it works?

答:
```<code>public static void main(String[] args) throws IOException {
    Bootstrap.main(args);
}
</code>```

Title: Spring-shell usage

Body:
I'm trying to use spring-shell.
 Created such class:

@Component
public class T implements CommandMarker {

public T() {
    System.out.println("T Constructor");
}

@CliCommand(value = "trans", help = "translate")
public String translate(@CliOption(key = { "msg" },
    mandatory = false, help = "The hello world message")
    final String msg) {
    System.out.println("!!! " + msg);
    return "!!! " + msg;
  }
}

and have such spring-shell-plugin.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.1.xsd">

   <context:component-scan base-package="com" />

</beans>

Class that starting application:

public class Main {

public static void main(String[] args) {
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("classpath*:/META-INF/spring/spring-shell-plugin.xml");
    context.start();
}
}

But as a result I'm just getting in console only 'T Constructor' althought I'm passing arguments 'trans --msg f'.

How to make it works?


来源: stackexchange

问:
How to get all commits without downloading to local system with JGit?
that I need to get all commits from a remote repository.

This is how I clone a repository to a local system, but it's not a good idea to download all files because there is so much.

```<code>git = Git.cloneRepository().setURI(repo).setDirectory(pathGit).call();
File pathRepo = new File(pathGit.getPath() + "/.git");
repository = FileRepositoryBuilder.create(pathRepo);
</code>```

How to resolve this issue?

答:
Cloning a repository is the only way to gain access to its history. If the time that it takes to clone a repository is an issue, you may want to cache it for future or shared access.

Git Hosting services like GitLab of GitHub may have specialized REST APIs to obtain commit metadata. However, these are specific to the respective service hoster.

ContentLicense: CC BY-SA 3.0

Body:
that I need to get all commits from a remote repository.

This is how I clone a repository to a local system, but it's not a good idea to download all files because there is so much.

git = Git.cloneRepository().setURI(repo).setDirectory(pathGit).call();
File pathRepo = new File(pathGit.getPath() + "/.git");
repository = FileRepositoryBuilder.create(pathRepo);

How to resolve this issue?


问:
How to store variables values in a class i.e "settings"?
OK. After spending literally a few hours trying to get things working I give up.

Basically I am creating a program in which user inputs some values, then after hitting button a new scene is created and depending on the values it was given, different things take place.
My problem - I created "Settings.class" with a few variables with getters and setters. My assumption was to store the values input in there and whenever needed I have easy access to them using getters.
For some reason it doesn't work.

Keep in mind I simplified it as much as I can because It'd look very messy and would be very long if I pasted my original code. I made sure that the core of the problem is the same.

Settings class:

```<code>public class Settings {
private boolean diamonds;

public boolean getDiamonds() {
    return diamonds;
}
public void setDiamonds(boolean diamonds) {
    this.diamonds = diamonds;
}
}
</code>```

Controller class:

```<code>public class Controller implements Initializable {
private Settings settings = new Settings();
private ProblematicOne prob = new ProblematicOne();

public void handleGoAction() throws IOException {

settings.setDiamonds(true);

prob.editText("This shall be set");

/* ..creating new stage and scene here no reason to paste it here, no probs with that.. */

@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
}
</code>```

And crème de la crème, problematic class:

```<code>public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}
</code>```

答:
in the following class with out setting value to settings object, you are trying to use get, which will return default value.

```<code>public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}
</code>```

if you want to use the settings object which you created in the controller then pass settings object to editText method in the ProblematicOne class.

Body:
OK. After spending literally a few hours trying to get things working I give up.

Basically I am creating a program in which user inputs some values, then after hitting button a new scene is created and depending on the values it was given, different things take place.
My problem - I created "Settings.class" with a few variables with getters and setters. My assumption was to store the values input in there and whenever needed I have easy access to them using getters.
For some reason it doesn't work.

Keep in mind I simplified it as much as I can because It'd look very messy and would be very long if I pasted my original code. I made sure that the core of the problem is the same.

Settings class:

public class Settings {
private boolean diamonds;

public boolean getDiamonds() {
    return diamonds;
}
public void setDiamonds(boolean diamonds) {
    this.diamonds = diamonds;
}
}

Controller class:

public class Controller implements Initializable {
private Settings settings = new Settings();
private ProblematicOne prob = new ProblematicOne();

public void handleGoAction() throws IOException {

settings.setDiamonds(true);

prob.editText("This shall be set");

/* ..creating new stage and scene here no reason to paste it here, no probs with that.. */

@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
}

And crème de la crème, problematic class:

public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}

Body:
in the following class with out setting value to settings object, you are trying to use get, which will return default value.

public class ProblematicOne{

private Setting settings = new Settings();
String toBeEdited = "";  //

public void editText(String text){

if(settings.getDiamonds){      // for some reason it doesn't work; The getter returns false.
    toBeEdited = text;
}else if(!settings.getDiamonds){
    toBeEdited = "getDiamonds is false";
}
}
}

if you want to use the settings object which you created in the controller then pass settings object to editText method in the ProblematicOne class.


问:
Why does my JSON data get lost when passed as a data attribute from erb to Javascript?
I try to pass some stuff (among which a JSON object) from the Ruby part of my Rails application to a Javascript file, and try to do so using the HTML data attributes.

In the .html.erb file:

```<code><div id='myDiv' data-points="<%=raw @points.to_json%>" data-unit-id="<%=@unit_id%>" >
</div>
</code>```

In the .js file:

```<code>var myDiv = document.getElementById("myDiv");
console.log(map_canvas.getAttribute("data-unit-id"));
console.log(map_canvas.getAttribute("data-points"));
</code>```

Data-unit-id does show up correctly in the console log. However, data-points, which is a JSON object, shows up like only this in the console log:

```<code>{
</code>```

When I log <%=raw @points.to_json%> from the html.erb side, it shows up fine as well - so the piece of ruby code does its job fine -, so somewhere while getting passed as a data attribute it gets lost (and data-unit-id does not!).

Does anyone have a clue what I'm doing wrong?

答:
Quotes. Your generated markup is syntactically invalid html. Attribute value ends prematurely, data-points="{"foo": 1}". See? You think it's an opening quote for key foo, but actually it's closing quote for data-points value.

To avoid this, either escape double quotes in the value:

```<code>data-points="{\"foo\": 1}"
</code>```

or use another type of quotes to surround the value

```<code>data-points='{"foo": 1}'
</code>```

Body:
I try to pass some stuff (among which a JSON object) from the Ruby part of my Rails application to a Javascript file, and try to do so using the HTML data attributes.

In the .html.erb file:

<div id='myDiv' data-points="<%=raw @points.to_json%>" data-unit-id="<%=@unit_id%>" >

In the .js file:

var myDiv = document.getElementById("myDiv");
console.log(map_canvas.getAttribute("data-unit-id"));
console.log(map_canvas.getAttribute("data-points"));

Data-unit-id does show up correctly in the console log. However, data-points, which is a JSON object, shows up like only this in the console log:

{

When I log <%=raw @points.to_json%> from the html.erb side, it shows up fine as well - so the piece of ruby code does its job fine -, so somewhere while getting passed as a data attribute it gets lost (and data-unit-id does not!).

Does anyone have a clue what I'm doing wrong?

Body:
Quotes. Your generated markup is syntactically invalid html. Attribute value ends prematurely, data-points="{"foo": 1}". See? You think it's an opening quote for key foo, but actually it's closing quote for data-points value.

To avoid this, either escape double quotes in the value:

data-points="{\"foo\": 1}"

or use another type of quotes to surround the value

data-points='{"foo": 1}'


问:
Spring Boot - inject map from properties file
property file looks like this:

```<code>url1=path_to_binary1
url2=path_to_binary2
</code>```

According this I tried following approach:

```<code>@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}
</code>```

and in another component I autowired ApplicationProperties:

```<code>@Autowired
private ApplicationProperties properties;
      //inside some method:
      properties.getPathMapper().get(appName);
</code>```

produces NullPointerException.

How to correct it?

update

I have correct according user7757360 advice:

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
</code>```

and properties file:

```<code>app.url1=path_to_binary1
app.url2=path_to_binary2
</code>```

Still doesn't work

Update 2

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;
</code>```

and inside application.properties:

```<code>app.url1=path_to_binary1
app.url2=path_to_binary2
</code>```

Still doesn't work

答:
it would be helpful if you can give a more specific example for property file. You should have the same prefix in the url1 and url2 and then you can use

@ConfigurationProperties(prefix="my")

as in

my.pathMapper.url1=path_to_binary1
my.pathMapper.url2=path_to_binary2

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="my")
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set for pathMapper are important
}
</code>```

see more at https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml

Body:
property file looks like this:

url1=path_to_binary1
url2=path_to_binary2

According this I tried following approach:

@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}

and in another component I autowired ApplicationProperties:

@Autowired
private ApplicationProperties properties;
      //inside some method:
      properties.getPathMapper().get(appName);

produces NullPointerException.

How to correct it?

update

I have correct according user7757360 advice:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {

and properties file:

app.url1=path_to_binary1
app.url2=path_to_binary2

Still doesn't work

Update 2

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;

and inside application.properties:

app.url1=path_to_binary1
app.url2=path_to_binary2

Still doesn't work

Body:
it would be helpful if you can give a more specific example for property file. You should have the same prefix in the url1 and url2 and then you can use

@ConfigurationProperties(prefix="my")

as in

my.pathMapper.url1=path_to_binary1
my.pathMapper.url2=path_to_binary2

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="my")
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set for pathMapper are important
}

see more at https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml


问:
How exactly work this iterate mediator in this WSO2 ESB project?
I am absolutly new in WSO2 and I have the following doubt about an ESB project on which I am working on.

I have to iterate on each <Sample>...</Sample> element of the following XML document (coming from a DSS service):

```<code><?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <Samples xmlns="http://ws.wso2.org/dataservice">
            <Sample>
                <sample_id>XXX00001</sample_id>
                <processed>n</processed><sample_doi>sampleid001</sample_doi><date>2000-01-01</date><hold_wiews>hold_wiews-0001</hold_wiews><hold_pid>hold_pid-001</hold_pid><hold_name>hold_name-001</hold_name><hold_address>hold_address-001</hold_address><hold_country>001</hold_country><hold_lat>hold_lat-1</hold_lat><hold_lon>hold_lon-1</hold_lon><method>acqu</method><genus>genus-001</genus><species>species-001</species><sp_auth>sp_auth-001</sp_auth><subtaxa>subtaxa-001</subtaxa><st_auth>st_auth-001</st_auth><bio_status>001</bio_status><mls_status>01</mls_status><prov_sid>prov_sid-001</prov_sid><provenance>pr1</provenance><coll_sid>coll_sid-001</coll_sid><coll_miss_id>coll_miss_id-001</coll_miss_id><coll_site>coll_site-001</coll_site><coll_lat>coll_lat-1</coll_lat><coll_lon>coll_lon-1</coll_lon><coll_uncert>coll_uncert-001</coll_uncert><coll_datum>coll_datum-001</coll_datum><coll_georef>coll_georef-001</coll_georef><coll_elevation>1</coll_elevation><coll_date>2001-01-01</coll_date><coll_source>s1</coll_source><ancestry>ancestry-001</ancestry>
            </Sample>

            <Sample>
                <sample_id>XXX00002</sample_id>
                <processed>n</processed><sample_doi>sampleid002</sample_doi><date>2000-01-02</date><hold_wiews>hold_wiews-0002</hold_wiews><hold_pid>hold_pid-002</hold_pid><hold_name>hold_name-002</hold_name><hold_address>hold_address-002</hold_address><hold_country>002</hold_country><hold_lat>hold_lat-2</hold_lat><hold_lon>hold_lon-2</hold_lon><method>acqu</method><genus>genus-002</genus><species>species-002</species><sp_auth>sp_auth-002</sp_auth><subtaxa>subtaxa-002</subtaxa><st_auth>st_auth-002</st_auth><bio_status>002</bio_status><mls_status>02</mls_status><prov_sid>prov_sid-002</prov_sid><provenance>pr2</provenance><coll_sid>coll_sid-002</coll_sid><coll_miss_id>coll_miss_id-002</coll_miss_id><coll_site>coll_site-002</coll_site><coll_lat>coll_lat-2</coll_lat><coll_lon>coll_lon-2</coll_lon><coll_uncert>coll_uncert-002</coll_uncert><coll_datum>coll_datum-002</coll_datum><coll_georef>coll_georef-002</coll_georef><coll_elevation>2</coll_elevation><coll_date>2001-01-02</coll_date><coll_source>s2</coll_source><ancestry>ancestry-002</ancestry>
            </Sample>

            <Sample>
                <sample_id>XXX00003</sample_id>
                <processed>n</processed><sample_doi>sampleid003</sample_doi><date>2000-01-03</date><hold_wiews>hold_wiews-0003</hold_wiews><hold_pid>hold_pid-003</hold_pid><hold_name>hold_name-003</hold_name><hold_address>hold_address-003</hold_address><hold_country>003</hold_country><hold_lat>hold_lat-3</hold_lat><hold_lon>hold_lon-3</hold_lon><method>acqu</method><genus>genus-003</genus><species>species-003</species><sp_auth>sp_auth-003</sp_auth><subtaxa>subtaxa-003</subtaxa><st_auth>st_auth-003</st_auth><bio_status>003</bio_status><mls_status>03</mls_status><prov_sid>prov_sid-003</prov_sid><provenance>pr3</provenance><coll_sid>coll_sid-003</coll_sid><coll_miss_id>coll_miss_id-003</coll_miss_id><coll_site>coll_site-003</coll_site><coll_lat>coll_lat-3</coll_lat><coll_lon>coll_lon-3</coll_lon><coll_uncert>coll_uncert-003</coll_uncert><coll_datum>coll_datum-003</coll_datum><coll_georef>coll_georef-003</coll_georef><coll_elevation>3</coll_elevation><coll_date>2001-01-03</coll_date><coll_source>s3</coll_source><ancestry>ancestry-003</ancestry>
            </Sample>
        </Samples>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

To do it I am using the iterate mediator (it is working pretty fine), something like this:

```<code><iterate expression="$body//ds:Sample" id="ITR_AGG" xmlns:ds="http://ws.wso2.org/dataservice">
    <target>
        <sequence>
            <enrich>
                <source clone="true" type="envelope"/>
                <target property="sampleData" type="property"/>
            </enrich>

            <!-- Log Sample Data -->
            <log level="custom">
                <property expression="$ctx:sampleData" name="sample data"/>
            </log>

            ...........................................................
            ...........................................................
            DO SOME OTHER STUFF
            ...........................................................
            ...........................................................
        </sequence>
    </target>
</iterate>
</code>```

It works fine but I have some doubts, I try to explain these doubts.

The iterate mediator implements the Splitter enterprise integration pattern **, it is used to splits the message into a number of different messages derived from the parent message**.

Ok, so I am splitting the original message that basically is contained into the <soapenv:Body>---</soapenv:Body> container into the 3 <Sample>...</Sample> separated message.

It works but why the iterate expression defined into the iterator mediator:

```<code><iterate expression="$body//ds:Sample" id="ITR_AGG" xmlns:ds="http://ws.wso2.org/dataservice">
</code>```

is $body//ds:Sample?

Ok so I think that I have to use the ds: prefix because it is coming from a data service (tell me if I am doing wronga assertion). But what exactly represent the $body "variable"? (is it something like a variable?)

Is it representing the <soapenv:Body> element in which have to be searched the <Sample> element that have to be iterated? Or what? In case my assumption is correct how the <soapenv:Body> is associated to the $body "variable"?

The second doubt is related to the use of the enrich mediator contained at the begining of the iterate mediator:

```<code><enrich>
    <source clone="true" type="envelope"/>
    <target property="sampleData" type="property"/>
</enrich>
</code>```

What exactly does? It seems to me that it is copying the current element on which is iterating into a new property named sampleData, infact after this mediator the sampleData property is logged by a logger and it is printed something like this:

```<code>sample data =
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <Sample xmlns="http://ws.wso2.org/dataservice">
            <sample_id>XXX00001</sample_id>
            <processed>n</processed><sample_doi>sampleid001</sample_doi><date>2000-01-01</date><hold_wiews>hold_wiews-0001</hold_wiews><hold_pid>hold_pid-001</hold_pid><hold_name>hold_name-001</hold_name><hold_address>hold_address-001</hold_address><hold_country>001</hold_country><hold_lat>hold_lat-1</hold_lat><hold_lon>hold_lon-1</hold_lon><method>acqu</method><genus>genus-001</genus><species>species-001</species><sp_auth>sp_auth-001</sp_auth><subtaxa>subtaxa-001</subtaxa><st_auth>st_auth-001</st_auth><bio_status>001</bio_status><mls_status>01</mls_status><prov_sid>prov_sid-001</prov_sid><provenance>pr1</provenance><coll_sid>coll_sid-001</coll_sid><coll_miss_id>coll_miss_id-001</coll_miss_id><coll_site>coll_site-001</coll_site><coll_lat>coll_lat-1</coll_lat><coll_lon>coll_lon-1</coll_lon><coll_uncert>coll_uncert-001</coll_uncert><coll_datum>coll_datum-001</coll_datum><coll_georef>coll_georef-001</coll_georef><coll_elevation>1</coll_elevation><coll_date>2001-01-01</coll_date><coll_source>s1</coll_source><ancestry>ancestry-001</ancestry>
        </Sample>
    </soapenv:Body>
</soapenv:Envelope> {org.apache.synapse.mediators.builtin.LogMediator}
</code>```

that represents the current element on which I am iterating. Is it my reasoning correct?

答:
You can use any string for the prefix, just be sure to use the same string after xmlns:

```<code>xmlns:ds="http://ws.wso2.org/dataservice"
</code>```

Ex:

```<code><iterate expression="$body//mypref:Sample" id="ITR_AGG" xmlns:mypref="http://ws.wso2.org/dataservice">
</code>```

$body is a predefined xpath expression for synapse that represent the body message:

https://docs.wso2.com/display/ESB500/Synapse+XPath+Variables#SynapseXPathVariables-$body

The enrich mediator:

```<code><enrich>
    <source clone="true" type="envelope"/>
    <target property="sampleData" type="property"/>
</enrich>
</code>```

Just copy the content of the incoming message, the entire payload including the soapevelop inside a property called sampleData.

Body:
I am absolutly new in WSO2 and I have the following doubt about an ESB project on which I am working on.

I have to iterate on each <Sample>...</Sample> element of the following XML document (coming from a DSS service):

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <Samples xmlns="http://ws.wso2.org/dataservice">
            <Sample>
                <sample_id>XXX00001</sample_id>
                <processed>n</processed><sample_doi>sampleid001</sample_doi><date>2000-01-01</date><hold_wiews>hold_wiews-0001</hold_wiews><hold_pid>hold_pid-001</hold_pid><hold_name>hold_name-001</hold_name><hold_address>hold_address-001</hold_address><hold_country>001</hold_country><hold_lat>hold_lat-1</hold_lat><hold_lon>hold_lon-1</hold_lon><method>acqu</method><genus>genus-001</genus><species>species-001</species><sp_auth>sp_auth-001</sp_auth><subtaxa>subtaxa-001</subtaxa><st_auth>st_auth-001</st_auth><bio_status>001</bio_status><mls_status>01</mls_status><prov_sid>prov_sid-001</prov_sid><provenance>pr1</provenance><coll_sid>coll_sid-001</coll_sid><coll_miss_id>coll_miss_id-001</coll_miss_id><coll_site>coll_site-001</coll_site><coll_lat>coll_lat-1</coll_lat><coll_lon>coll_lon-1</coll_lon><coll_uncert>coll_uncert-001</coll_uncert><coll_datum>coll_datum-001</coll_datum><coll_georef>coll_georef-001</coll_georef><coll_elevation>1</coll_elevation><coll_date>2001-01-01</coll_date><coll_source>s1</coll_source><ancestry>ancestry-001</ancestry>
            </Sample>

            <Sample>
                <sample_id>XXX00002</sample_id>
                <processed>n</processed><sample_doi>sampleid002</sample_doi><date>2000-01-02</date><hold_wiews>hold_wiews-0002</hold_wiews><hold_pid>hold_pid-002</hold_pid><hold_name>hold_name-002</hold_name><hold_address>hold_address-002</hold_address><hold_country>002</hold_country><hold_lat>hold_lat-2</hold_lat><hold_lon>hold_lon-2</hold_lon><method>acqu</method><genus>genus-002</genus><species>species-002</species><sp_auth>sp_auth-002</sp_auth><subtaxa>subtaxa-002</subtaxa><st_auth>st_auth-002</st_auth><bio_status>002</bio_status><mls_status>02</mls_status><prov_sid>prov_sid-002</prov_sid><provenance>pr2</provenance><coll_sid>coll_sid-002</coll_sid><coll_miss_id>coll_miss_id-002</coll_miss_id><coll_site>coll_site-002</coll_site><coll_lat>coll_lat-2</coll_lat><coll_lon>coll_lon-2</coll_lon><coll_uncert>coll_uncert-002</coll_uncert><coll_datum>coll_datum-002</coll_datum><coll_georef>coll_georef-002</coll_georef><coll_elevation>2</coll_elevation><coll_date>2001-01-02</coll_date><coll_source>s2</coll_source><ancestry>ancestry-002</ancestry>
            </Sample>

            <Sample>
                <sample_id>XXX00003</sample_id>
                <processed>n</processed><sample_doi>sampleid003</sample_doi><date>2000-01-03</date><hold_wiews>hold_wiews-0003</hold_wiews><hold_pid>hold_pid-003</hold_pid><hold_name>hold_name-003</hold_name><hold_address>hold_address-003</hold_address><hold_country>003</hold_country><hold_lat>hold_lat-3</hold_lat><hold_lon>hold_lon-3</hold_lon><method>acqu</method><genus>genus-003</genus><species>species-003</species><sp_auth>sp_auth-003</sp_auth><subtaxa>subtaxa-003</subtaxa><st_auth>st_auth-003</st_auth><bio_status>003</bio_status><mls_status>03</mls_status><prov_sid>prov_sid-003</prov_sid><provenance>pr3</provenance><coll_sid>coll_sid-003</coll_sid><coll_miss_id>coll_miss_id-003</coll_miss_id><coll_site>coll_site-003</coll_site><coll_lat>coll_lat-3</coll_lat><coll_lon>coll_lon-3</coll_lon><coll_uncert>coll_uncert-003</coll_uncert><coll_datum>coll_datum-003</coll_datum><coll_georef>coll_georef-003</coll_georef><coll_elevation>3</coll_elevation><coll_date>2001-01-03</coll_date><coll_source>s3</coll_source><ancestry>ancestry-003</ancestry>
            </Sample>
        </Samples>
    </soapenv:Body>
</soapenv:Envelope>

To do it I am using the iterate mediator (it is working pretty fine), something like this:

<iterate expression="$body//ds:Sample" id="ITR_AGG" xmlns:ds="http://ws.wso2.org/dataservice">
    <target>
        <sequence>
            <enrich>
                <source clone="true" type="envelope"/>
                <target property="sampleData" type="property"/>
            </enrich>

            <log level="custom">
                <property expression="$ctx:sampleData" name="sample data"/>
            </log>

            ...........................................................
            ...........................................................
            DO SOME OTHER STUFF
            ...........................................................
            ...........................................................
        </sequence>
    </target>
</iterate>

It works fine but I have some doubts, I try to explain these doubts.

The iterate mediator implements the Splitter enterprise integration pattern **, it is used to splits the message into a number of different messages derived from the parent message**.

Ok, so I am splitting the original message that basically is contained into the <soapenv:Body>---</soapenv:Body> container into the 3 <Sample>...</Sample> separated message.

It works but why the iterate expression defined into the iterator mediator:

<iterate expression="$body//ds:Sample" id="ITR_AGG" xmlns:ds="http://ws.wso2.org/dataservice">

is $body//ds:Sample?

Ok so I think that I have to use the ds: prefix because it is coming from a data service (tell me if I am doing wronga assertion). But what exactly represent the $body "variable"? (is it something like a variable?)

Is it representing the <soapenv:Body> element in which have to be searched the <Sample> element that have to be iterated? Or what? In case my assumption is correct how the <soapenv:Body> is associated to the $body "variable"?

The second doubt is related to the use of the enrich mediator contained at the begining of the iterate mediator:

<enrich>
    <source clone="true" type="envelope"/>
    <target property="sampleData" type="property"/>
</enrich>

What exactly does? It seems to me that it is copying the current element on which is iterating into a new property named sampleData, infact after this mediator the sampleData property is logged by a logger and it is printed something like this:

sample data =
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <Sample xmlns="http://ws.wso2.org/dataservice">
            <sample_id>XXX00001</sample_id>
            <processed>n</processed><sample_doi>sampleid001</sample_doi><date>2000-01-01</date><hold_wiews>hold_wiews-0001</hold_wiews><hold_pid>hold_pid-001</hold_pid><hold_name>hold_name-001</hold_name><hold_address>hold_address-001</hold_address><hold_country>001</hold_country><hold_lat>hold_lat-1</hold_lat><hold_lon>hold_lon-1</hold_lon><method>acqu</method><genus>genus-001</genus><species>species-001</species><sp_auth>sp_auth-001</sp_auth><subtaxa>subtaxa-001</subtaxa><st_auth>st_auth-001</st_auth><bio_status>001</bio_status><mls_status>01</mls_status><prov_sid>prov_sid-001</prov_sid><provenance>pr1</provenance><coll_sid>coll_sid-001</coll_sid><coll_miss_id>coll_miss_id-001</coll_miss_id><coll_site>coll_site-001</coll_site><coll_lat>coll_lat-1</coll_lat><coll_lon>coll_lon-1</coll_lon><coll_uncert>coll_uncert-001</coll_uncert><coll_datum>coll_datum-001</coll_datum><coll_georef>coll_georef-001</coll_georef><coll_elevation>1</coll_elevation><coll_date>2001-01-01</coll_date><coll_source>s1</coll_source><ancestry>ancestry-001</ancestry>
        </Sample>
    </soapenv:Body>
</soapenv:Envelope> {org.apache.synapse.mediators.builtin.LogMediator}

that represents the current element on which I am iterating. Is it my reasoning correct?

Body:
You can use any string for the prefix, just be sure to use the same string after xmlns:

xmlns:ds="http://ws.wso2.org/dataservice"

Ex:

<iterate expression="$body//mypref:Sample" id="ITR_AGG" xmlns:mypref="http://ws.wso2.org/dataservice">

$body is a predefined xpath expression for synapse that represent the body message:

https://docs.wso2.com/display/ESB500/Synapse+XPath+Variables#SynapseXPathVariables-$body

The enrich mediator:

<enrich>
    <source clone="true" type="envelope"/>
    <target property="sampleData" type="property"/>
</enrich>

Just copy the content of the incoming message, the entire payload including the soapevelop inside a property called sampleData.


问:
Cannot resolve symbole 'input' JAVA
so I want to do a little alround program with quiz etc (won't paste the entire code because its 300 lines of basic stuff), and I want a boolean that repeats a gambling game for me, so when I get to the line:

```<code>String PlayAgain = input.nextLine();
</code>```

I get the error: Cannot resolve symbole 'input'.

The code for the little game is here:

```<code>enter  boolean InGame = true;
        while (InGame == true);

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs() ist eine Methode die den Betrag einer Zahl zurueck gibt.
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = input.nextLine();
        if  (PlayAgain == "Ja");
</code>```

Can you help me?

答:
Perhaps you miss

Scanner input = new Scanner(System.in) ?

or change input to scan

```<code>String PlayAgain = scan.nextLine();
</code>```

Title: Cannot resolve symbole 'input' JAVA

Body:
so I want to do a little alround program with quiz etc (won't paste the entire code because its 300 lines of basic stuff), and I want a boolean that repeats a gambling game for me, so when I get to the line:

String PlayAgain = input.nextLine();

I get the error: Cannot resolve symbole 'input'.

The code for the little game is here:

enter  boolean InGame = true;
        while (InGame == true);

        System.out.println("Glückspiel: Wer näher an der zufälligen Zahl ist gewinnt! 1-100");
        System.out.println("Spieler Eins");
        double playerOne = scan.nextDouble();
        System.out.println("Spieler Zwei");
        double playerTwo = scan.nextDouble();

        double randomValue = Math.random() * 100.0;

        // Math.abs() ist eine Methode die den Betrag einer Zahl zurueck gibt.
        double spacingOne = Math.abs(playerOne - randomValue);
        double spacingTwo = Math.abs(playerTwo - randomValue);
        System.out.println("Die Random Zahl war " + randomValue);

        if (spacingOne < spacingTwo) {
            System.out.println("Spieler Eins hat gewonnen!");
        }

        if (spacingOne > spacingTwo) {
            System.out.println("Spieler Zwei hat gewonnen!");
        }

        if (spacingOne == spacingTwo) {
            System.out.println("Unentschieden!");
        }
        System.out.println("Wenn du nochmal spielen willst schreibe 'ja' wenn nicht 'nein'");
        String PlayAgain = input.nextLine();
        if  (PlayAgain == "Ja");

Can you help me?

Body:
Perhaps you miss

Scanner input = new Scanner(System.in) ?

or change input to scan

String PlayAgain = scan.nextLine();


问:
Error event listener doesn't execute function when page loads
I have a page that contains some report pictures. Under each image, there are 4 buttons that change the image's src when clicked.
I've written a short script (imageValidation.js) that checks if the image has loaded successfully and if not, runs a function that changes images src to generic 'file not found' picture.

The problem is that I want the script to replace replace the 'broken' image srcs when the page load initially, which it doesn't. However, when I change the pictures by clicking on the buttons, the script works fine.

To give an example, I deleted the 01UR(All).jpeg. When the page loads I see generic broken picture icon. But when I click on the All Cycles button, the image changes to the ReportUnavailable.jpeg as desired.

I've tried executing the code in onload attribute in body section. Also tried moving the script tag to head and to the beginning of the body section.

How should it be done correctly?

Here's the HTML:

```<code><body>
<div>
    <img id="UR_chart" class="Reportpicture" src="reports/01UR(All).jpeg" />
</div>
<div class="submenu">
    <button id="UR_all" onclick="changeChart('UR_chart', 'reports/01UR(All).jpeg')">
        All Cycles
    </button>
    <button id="UR_c1" onclick="changeChart('UR_chart', 'reports/01UR(C1).jpeg')">
        Cycle 1
    </button>
    <button id="UR_c2" onclick="changeChart('UR_chart', 'reports/01UR(C2).jpeg')">
        Cycle 2
    </button>
    <button id="UR_c3" onclick="changeChart('UR_chart', 'reports/01UR(C3).jpeg')">
        Cycle 3
    </button>
</div>

<!-- more divs -->

<script src="../Scripts/imageValidation.js"></script>
</body>
</code>```

The image validation script:

```<code>/*imageValidation.js*/
var reportPix = document.getElementsByClassName("Reportpicture");

for(var i = 0; i < reportPix.length; i++)
{
    reportPix[i].addEventListener("error", noImageFound);
}

function noImageFound()
{
    this.src = 'ReportUnavailable.jpeg';

}
</code>```

答:
I'm doing two things here.
One after window.onload all images are checked and if they have a natrualWidth and naturalHeight of 0 then they are replaced. This should take care of any images that got loaded before the event got registered.

The Event listener is still registered and will be called for the cases where the image is changed.

function changeChart() {
 reportPix[0].src = "blank1.gif";

}
window.onload = checkImages;

var reportPix = document.getElementsByClassName("Reportpicture");
for(var i = 0; i < reportPix.length; i++) {
  reportPix[i].addEventListener("error", noImageFound);
}

function checkImages() {
 for(var i = 0; i < reportPix.length; i++) {
  if (reportPix[i].naturalHeight === 0 && reportPix[i].naturalWidth === 0) {
   noImageFound(reportPix[i]);
  }
 }
}

function noImageFound(obj) {
 if (obj.target) {
  obj.target.src = "https://img.clipartfest.com/cee7c57a2d96b3117b12d85fc6b6d6fc_photo-not-available-large-picture-not-available-clipart_325-384.png";
 } else {
  obj.src = "https://img.clipartfest.com/cee7c57a2d96b3117b12d85fc6b6d6fc_photo-not-available-large-picture-not-available-clipart_325-384.png";
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <img id="UR_chart" class="Reportpicture" src="reports/01UR(All).jpeg" />
</div>
<div class="submenu">
    <button id="UR_all" onclick="changeChart('UR_chart', 'reports/01UR(All).jpeg')">
        All Cycles
    </button>
    <button id="UR_c1" onclick="changeChart('UR_chart', 'reports/01UR(C1).jpeg')">
        Cycle 1
    </button>
    <button id="UR_c2" onclick="changeChart('UR_chart', 'reports/01UR(C2).jpeg')">
        Cycle 2
    </button>
    <button id="UR_c3" onclick="changeChart('UR_chart', 'reports/01UR(C3).jpeg')">
        Cycle 3
    </button>
</div></code>```

Body:
I have a page that contains some report pictures. Under each image, there are 4 buttons that change the image's src when clicked.
I've written a short script (imageValidation.js) that checks if the image has loaded successfully and if not, runs a function that changes images src to generic 'file not found' picture.

The problem is that I want the script to replace replace the 'broken' image srcs when the page load initially, which it doesn't. However, when I change the pictures by clicking on the buttons, the script works fine.

To give an example, I deleted the 01UR(All).jpeg. When the page loads I see generic broken picture icon. But when I click on the All Cycles button, the image changes to the ReportUnavailable.jpeg as desired.

I've tried executing the code in onload attribute in body section. Also tried moving the script tag to head and to the beginning of the body section.

How should it be done correctly?

Here's the HTML:

    <button id="UR_all" onclick="changeChart('UR_chart', 'reports/01UR(All).jpeg')">
        All Cycles
    </button>
    <button id="UR_c1" onclick="changeChart('UR_chart', 'reports/01UR(C1).jpeg')">
        Cycle 1
    </button>
    <button id="UR_c2" onclick="changeChart('UR_chart', 'reports/01UR(C2).jpeg')">
        Cycle 2
    </button>
    <button id="UR_c3" onclick="changeChart('UR_chart', 'reports/01UR(C3).jpeg')">
        Cycle 3
    </button>

The image validation script:

/*imageValidation.js*/
var reportPix = document.getElementsByClassName("Reportpicture");

for(var i = 0; i < reportPix.length; i++)
{
    reportPix[i].addEventListener("error", noImageFound);
}

function noImageFound()
{
    this.src = 'ReportUnavailable.jpeg';

}

Body:
I'm doing two things here.
One after window.onload all images are checked and if they have a natrualWidth and naturalHeight of 0 then they are replaced. This should take care of any images that got loaded before the event got registered.

The Event listener is still registered and will be called for the cases where the image is changed.

function changeChart() {
 reportPix[0].src = "blank1.gif";

}
window.onload = checkImages;

var reportPix = document.getElementsByClassName("Reportpicture");
for(var i = 0; i < reportPix.length; i++) {
  reportPix[i].addEventListener("error", noImageFound);
}

function checkImages() {
 for(var i = 0; i < reportPix.length; i++) {
  if (reportPix[i].naturalHeight === 0 && reportPix[i].naturalWidth === 0) {
   noImageFound(reportPix[i]);
  }
 }
}

function noImageFound(obj) {
 if (obj.target) {
  obj.target.src = "https://img.clipartfest.com/cee7c57a2d96b3117b12d85fc6b6d6fc_photo-not-available-large-picture-not-available-clipart_325-384.png";
 } else {
  obj.src = "https://img.clipartfest.com/cee7c57a2d96b3117b12d85fc6b6d6fc_photo-not-available-large-picture-not-available-clipart_325-384.png";
 }
}

<div>
    <img id="UR_chart" class="Reportpicture" src="reports/01UR(All).jpeg" />
</div>
<div class="submenu">
    <button id="UR_all" onclick="changeChart('UR_chart', 'reports/01UR(All).jpeg')">
        All Cycles
    </button>
    <button id="UR_c1" onclick="changeChart('UR_chart', 'reports/01UR(C1).jpeg')">
        Cycle 1
    </button>
    <button id="UR_c2" onclick="changeChart('UR_chart', 'reports/01UR(C2).jpeg')">
        Cycle 2
    </button>
    <button id="UR_c3" onclick="changeChart('UR_chart', 'reports/01UR(C3).jpeg')">
        Cycle 3
    </button>
</div>


问:
Cocoa pods stuck while cloning
I try to set up cocoa pods in my MacBook Pro El Capitan.

pod setup command will stuck on Cloning into 'master'...

Even I waited for 2 hours with 1GB download of git-remote-https.

It is never completed.

I also tried lots of time on Google for last 15 days.

I also tried following commands:

```<code>pod repo remove master
</code>```

It says master repository not found.

答:
That bypass / workaround solution works just to Virtual Machines

When you try to install cocoa pod, there is no network activity after it gets stuck.
According to hagge's comment on March 8, 2016 (https://github.com/cocoapods/cocoapods/issues/4989), this kind of problem can be caused by automatic limitation of transfer rate on servers, which is done to make sure that extremely high levels of load do not bring problems.
If you are using VMware or Virtualized Machines, you can proceed as below.

Change the configuration of Virtual Machine:

Select Network Adapter

Go to Advanced Settings

Incoming Transfer, set to Cable Mbps (4000 Kbps)

Outgoing Transfer, set to Cable Mbps (4000 Kbps)

Click OK

You may have to make the command install more than once. It'll take time but may work. Worked for me!

Title: Cocoa pods stuck while cloning

Body:
I try to set up cocoa pods in my MacBook Pro El Capitan.

pod setup command will stuck on Cloning into 'master'...

Even I waited for 2 hours with 1GB download of git-remote-https.

It is never completed.

I also tried lots of time on Google for last 15 days.

I also tried following commands:

pod repo remove master

It says master repository not found.


问:
Hiding the still objects when another createjs object passes through them in createjs
is there a way to hide the objects through which another object is passing in createjs. Also i have defined a path for the moving object but when it crosses other objects that come in the path; the objects are not hidden. It gives the view as if the moving object is cutting other objects. Is there a way in createjs through which i can handle this situation?</p>

答:
Sure, there is a way for that. You can calculate the area of the intersection between 2 objects, and if it's a number higher than 0, then you can hide the second object. It will look something like this:

```<code>var bounds1 = object1.nominalBounds; //or .getBounds();
var bounds2 = object2.nominalBounds;
var rectangle = bounds1.intersection(bounds2);
if (rectangle != null && rectangle.width * rectangle.height > 0){
   object2.visible = false;
}
</code>```

That's the gist of it, although depending on your objects and their containers, it might be a little more complicated than this, like needing to translate their coordinates to a global scope.

Body:
Sure, there is a way for that. You can calculate the area of the intersection between 2 objects, and if it's a number higher than 0, then you can hide the second object. It will look something like this:

var bounds1 = object1.nominalBounds; //or .getBounds();
var bounds2 = object2.nominalBounds;
var rectangle = bounds1.intersection(bounds2);
if (rectangle != null && rectangle.width * rectangle.height > 0){
   object2.visible = false;
}

That's the gist of it, although depending on your objects and their containers, it might be a little more complicated than this, like needing to translate their coordinates to a global scope.


问:
Cut Linux variable number of spaces
I need to get in linux the third column...

I used first last | cut -d " " -f 3 but it doesn't work and after that I taught the char is a TAB and used last | cut -f 2
and it's still not working...

how shoult i get that?

答:
You might try it with awk:

```<code><your-program-giving-tabular-output> | awk '{ print $3 }'
</code>```

For example with ps:

```<code>ps | awk '{ print $3 }'
</code>```

Title: Cut Linux variable number of spaces

Body:
You might try it with awk:

<your-program-giving-tabular-output> | awk '{ print $3 }'

For example with ps:

ps | awk '{ print $3 }'


问:
Converting NSString to char byte array
In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

```<code>char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};
</code>```

How to convert my NSString to char byte array like this one?

Thanks!

答:
Since your text is hex and you want actual bytes out (which each correspond to two hex characters), you'll have to manually convert each character into the corresponding number, and then add them together into the correct numerical value.

To do this, I'm taking advantage of the fact that, in ASCII characters, a...z are in a row, as are 0...9. I'm also taking advantage of the fact that hexadecimal is valid ASCII, and that Unicode characters from 0...127 are identical to their corresponding ASCII characters.

Below is a program that does this and prints out the original string's characters as well as the calculated bytes (as hex again):

```<code>#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    @autoreleasepool
    {
        NSString *hexStr = @"1234567890abcdef12";
        unsigned char theBytes[9] = {};
        for( NSUInteger x = 0; x < sizeof(theBytes); x++ )
        {
            unsigned char digitOne = [hexStr characterAtIndex: x * 2];
            if( digitOne >= 'a' )
                digitOne -= 'a' -10;
            else
                digitOne -= '0';
            unsigned char digitTwo = [hexStr characterAtIndex: (x * 2) +1];
            if( digitTwo >= 'a' )
                digitTwo -= 'a' -10;
            else
                digitTwo -= '0';
            printf("%01x%01x",digitOne,digitTwo);
            theBytes[x] = (digitOne << 4) | digitTwo;
        }
        printf("\n");

        for( int x = 0; x < sizeof(theBytes); x++ )
            printf("%02x",theBytes[x]);
        printf("\n");
    }
}
</code>```

Note: This code naïvely assumes that you are providing a correct string. I.e. your input has to consist of lowercase characters and numbers only, and exactly 18 characters. Anything else and you get a wrong result or an exception.

Title: Converting NSString to char byte array

Body:
In my program, I receive a NSString like this one : AA010158AA7D385002. And I need to pass it to a method which accept a char byte array, as below :

char[9] = {0xAA, 0x01, 0x01, 0x58, 0xAA, 0x7D, 0x38, 0x50, 0x02};

How to convert my NSString to char byte array like this one?

Thanks!

Body:
Since your text is hex and you want actual bytes out (which each correspond to two hex characters), you'll have to manually convert each character into the corresponding number, and then add them together into the correct numerical value.

To do this, I'm taking advantage of the fact that, in ASCII characters, a...z are in a row, as are 0...9. I'm also taking advantage of the fact that hexadecimal is valid ASCII, and that Unicode characters from 0...127 are identical to their corresponding ASCII characters.

Below is a program that does this and prints out the original string's characters as well as the calculated bytes (as hex again):

#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    @autoreleasepool
    {
        NSString *hexStr = @"1234567890abcdef12";
        unsigned char theBytes[9] = {};
        for( NSUInteger x = 0; x < sizeof(theBytes); x++ )
        {
            unsigned char digitOne = [hexStr characterAtIndex: x * 2];
            if( digitOne >= 'a' )
                digitOne -= 'a' -10;
            else
                digitOne -= '0';
            unsigned char digitTwo = [hexStr characterAtIndex: (x * 2) +1];
            if( digitTwo >= 'a' )
                digitTwo -= 'a' -10;
            else
                digitTwo -= '0';
            printf("%01x%01x",digitOne,digitTwo);
            theBytes[x] = (digitOne << 4) | digitTwo;
        }
        printf("\n");

        for( int x = 0; x < sizeof(theBytes); x++ )
            printf("%02x",theBytes[x]);
        printf("\n");
    }
}

Note: This code naïvely assumes that you are providing a correct string. I.e. your input has to consist of lowercase characters and numbers only, and exactly 18 characters. Anything else and you get a wrong result or an exception.


问:
getClass() of generic class
The problem is that I need to get something like T.class, because veryImportantMethod (from below example) have Class parameter.

```<code>public abstract class Something<T> {

    public abstract Class<T> getGenericClass();

}

public class Example extends Something<Example> {
    @Override
    public Class<Example> getGenericClass() {
        return Example.class;
    }
}

public static abstract class BaseDao<T extends Something<T>> extends Amazing {

        T type;

        public T doSomething() {
            this.veryImportantMethod(type.getGenericClass());
        }

}

public static class Son extends BaseDao<Example> {
}
</code>```

Actually I'm getting

...read of unwritten field... NP_UNWRITTEN_FIELD

How can I go through this?

答:
I'm not 100% sure whether this is what you are after but...

First, Example.getGenericClass as defined is totally useless, you would obtain the same answer but calling getClass on the Example typed variable,

```<code>Example example = new Example();
example.getClass() == Example.class; // always true.
</code>```

Thus If you can guaranteed that type will always have a non-null value then you can simply call type.getClass() on it.

If type might be null then you are kind of out of luck unless you keep record of the class by keeping a separate reference to it. I suspect that type is just there to get Example.class. In that case is best just
to point to the Class object directly. This reference must be initialized by the constructor and typically it only make sense to make it final since it should not change during the live of the containing object.

```<code>public static abstract class BaseDao<T extends Something<T>> extends Amazing {

        private final Class<T> clazz;

        public BaseDao(final Class<T> clazz) {
           this.clazz = clazz;
        }

        public void doSomething() {
            this.veryImportantMethod(clazz);
        }
}
...
class ExampleDao extends BaseDao<Example> {
      public ExampleDao() {
         super(Example.class);
      }
}
...
</code>```

Title: getClass() of generic class

Body:
The problem is that I need to get something like T.class, because veryImportantMethod (from below example) have Class parameter.

public abstract class Something<T> {

    public abstract Class<T> getGenericClass();

}

public class Example extends Something<Example> {
    @Override
    public Class<Example> getGenericClass() {
        return Example.class;
    }
}

public static abstract class BaseDao<T extends Something<T>> extends Amazing {

        T type;

        public T doSomething() {
            this.veryImportantMethod(type.getGenericClass());
        }

}

public static class Son extends BaseDao<Example> {
}

Actually I'm getting

...read of unwritten field... NP_UNWRITTEN_FIELD

How can I go through this?

Body:
I'm not 100% sure whether this is what you are after but...

First, Example.getGenericClass as defined is totally useless, you would obtain the same answer but calling getClass on the Example typed variable,

Example example = new Example();
example.getClass() == Example.class; // always true.

Thus If you can guaranteed that type will always have a non-null value then you can simply call type.getClass() on it.

If type might be null then you are kind of out of luck unless you keep record of the class by keeping a separate reference to it. I suspect that type is just there to get Example.class. In that case is best just
to point to the Class object directly. This reference must be initialized by the constructor and typically it only make sense to make it final since it should not change during the live of the containing object.

public static abstract class BaseDao<T extends Something<T>> extends Amazing {

        private final Class<T> clazz;

        public BaseDao(final Class<T> clazz) {
           this.clazz = clazz;
        }

        public void doSomething() {
            this.veryImportantMethod(clazz);
        }
}
...
class ExampleDao extends BaseDao<Example> {
      public ExampleDao() {
         super(Example.class);
      }
}
...


问:
Pass boolean from observable to observable
I want to check in my adminauthguard if the user has set a adminflag(in Firebase using angularfire2)

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> | boolean {
    return this.loginservice.af.auth.map((auth) =>  {
      if(auth == null) {
        return false;
      } else {
        this.membersservice.get(auth.uid).subscribe(users => {
          if(users.admin == true) {
            return true;
          } else {
            return false;
          }
        })
      }
    });
</code>```

how can I resolve the observable in the observable inside?

答:
I need wait User Suscription info before to run any secure component. I use a similar solution to lastWhisper's, implementing canActivateChild and setting in routes:</p>

```<code>    path: 'app', component: FullLayoutComponent, data: {title: 'Home'}, canActivateChild: [CanActivateChildTeam],

CanActivateChildTeam Service:

    import {Injectable, OnDestroy} from "@angular/core";
    import {CanActivateChild} from "@angular/router";
    import {Meteor} from 'meteor/meteor';
    import {Router} from '@angular/router';
    import {Observable} from "rxjs/Rx";
    import {MeteorObservable} from 'meteor-rxjs';
    import {Subscription} from 'rxjs/Subscription';

    @Injectable()
    export class CanActivateChildTeam implements CanActivateChild, OnDestroy {

    allow:Observable<boolean>;
    private _userSub:Subscription;

    constructor(private router:Router) {
    }

    canActivateChild(route:any, state:any):Observable<boolean> | Promise<boolean> | boolean {
        return this.getUser();
    }

    getUser() {
        if (this.allow) {
            this.allow = new Observable(observer => {
                observer.next(true);
                observer.complete();
            });
            return this.allow;
        }
        if (Meteor.userId()) {
            this.allow = new Observable(observer => {
                if (this._userSub)
                    this._userSub.unsubscribe();
                this._userSub = MeteorObservable.subscribe('user', Meteor.userId()).subscribe(
                    () => {
                        observer.next(true);
                        observer.complete();
                    }
                );
            });
            return this.allow;
        }
        else {
            this.router.navigate(['/']);
        }
    }

    ngOnDestroy():void {
        if (this._userSub)
            this._userSub.unsubscribe();
    }
}
</code>```

Body:
I want to check in my adminauthguard if the user has set a adminflag(in Firebase using angularfire2)

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> | boolean {
    return this.loginservice.af.auth.map((auth) =>  {
      if(auth == null) {
        return false;
      } else {
        this.membersservice.get(auth.uid).subscribe(users => {
          if(users.admin == true) {
            return true;
          } else {
            return false;
          }
        })
      }
    });

how can I resolve the observable in the observable inside?

Body:
I need wait User Suscription info before to run any secure component. I use a similar solution to lastWhisper's, implementing canActivateChild and setting in routes:

    path: 'app', component: FullLayoutComponent, data: {title: 'Home'}, canActivateChild: [CanActivateChildTeam],

CanActivateChildTeam Service:

    import {Injectable, OnDestroy} from "@angular/core";
    import {CanActivateChild} from "@angular/router";
    import {Meteor} from 'meteor/meteor';
    import {Router} from '@angular/router';
    import {Observable} from "rxjs/Rx";
    import {MeteorObservable} from 'meteor-rxjs';
    import {Subscription} from 'rxjs/Subscription';

    @Injectable()
    export class CanActivateChildTeam implements CanActivateChild, OnDestroy {

    allow:Observable<boolean>;
    private _userSub:Subscription;

    constructor(private router:Router) {
    }

    canActivateChild(route:any, state:any):Observable<boolean> | Promise<boolean> | boolean {
        return this.getUser();
    }

    getUser() {
        if (this.allow) {
            this.allow = new Observable(observer => {
                observer.next(true);
                observer.complete();
            });
            return this.allow;
        }
        if (Meteor.userId()) {
            this.allow = new Observable(observer => {
                if (this._userSub)
                    this._userSub.unsubscribe();
                this._userSub = MeteorObservable.subscribe('user', Meteor.userId()).subscribe(
                    () => {
                        observer.next(true);
                        observer.complete();
                    }
                );
            });
            return this.allow;
        }
        else {
            this.router.navigate(['/']);
        }
    }

    ngOnDestroy():void {
        if (this._userSub)
            this._userSub.unsubscribe();
    }
}


问:
Request timeout from ASP.NET Core app on IIS
I make a web request to a third-party api from my ASP.NET Core application.

When app is running alone itself, request succeeds.

When app is running in IIS on the same server, request timeouts.

Request is made from a Hangfire recurring job to Asana API endpoint (HTTPS) via RestSharp client. All the own app's pages are available through IIS, but app cannot make any requests.

Where should I look and what to debug to solve this problem?

答:
IIS behavior is driven by the web.config, I have configured to deal with request < 20 min specifying requestTimeout="00:20:00":

```<code><aspNetCore
  requestTimeout="00:20:00"
  processPath="%LAUNCHER_PATH%"
  arguments="%LAUNCHER_ARGS%"
  stdoutLogEnabled="false"
  stdoutLogFile=".\logs\stdout"
  forwardWindowsAuthToken="false">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="staging" /> <!-- value could be "development", "staging" or "production"-->
  </environmentVariables>
</aspNetCore>
</code>```

Body:
IIS behavior is driven by the web.config, I have configured to deal with request < 20 min specifying requestTimeout="00:20:00":

<aspNetCore
  requestTimeout="00:20:00"
  processPath="%LAUNCHER_PATH%"
  arguments="%LAUNCHER_ARGS%"
  stdoutLogEnabled="false"
  stdoutLogFile=".\logs\stdout"
  forwardWindowsAuthToken="false">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="staging" /> <!-- value could be "development", "staging" or "production"-->
  </environmentVariables>
</aspNetCore>


问:
How to name optionmenu boxes in a for loop
At the moment each option menu box replaces the previous one so if write ent1.get() i dont get the value within any box, how can i distinguish betweeen each optionmenu and therefor retrieve each value distinctly? Ideally calling them all by a different name decided by their position in the grid.</p>

```<code>  for x in range (xval):#creating the matrix
        for y in range (yval):
            variable = StringVar(root)
            ent1 = OptionMenu(root, variable, *inputvalues)#creating the dropdown menus
            ent1.config(width=3)
            ent1.grid(row=(y+1), column=x)
</code>```

答:
Use a dictionary to keep track of the widgets and variables. </p>

```<code>entries = {}
vars = {}
for x in range (xval):#creating the matrix
    for y in range (yval):
        variable = StringVar(root)
        entry = OptionMenu(root, variable, *inputvalues)
        entry.config(width=3)
        entry.grid(row=(y+1), column=x)
        entries[(x,y)] = entry
        vars[(x,y)] = variable
</code>```

Body:
At the moment each option menu box replaces the previous one so if write ent1.get() i dont get the value within any box, how can i distinguish betweeen each optionmenu and therefor retrieve each value distinctly? Ideally calling them all by a different name decided by their position in the grid.

  for x in range (xval):#creating the matrix
        for y in range (yval):
            variable = StringVar(root)
            ent1 = OptionMenu(root, variable, *inputvalues)#creating the dropdown menus
            ent1.config(width=3)
            ent1.grid(row=(y+1), column=x)

Body:
Use a dictionary to keep track of the widgets and variables.

entries = {}
vars = {}
for x in range (xval):#creating the matrix
    for y in range (yval):
        variable = StringVar(root)
        entry = OptionMenu(root, variable, *inputvalues)
        entry.config(width=3)
        entry.grid(row=(y+1), column=x)
        entries[(x,y)] = entry
        vars[(x,y)] = variable


问:
SQL how to remove new lines on string end?
Encountered issue when I needed to remove (or replace) new lines at the string end:

Somthing like this

```<code>-----
test

----
</code>```

to

```<code>----
test
----
</code>```

I encountered some examples such as

```<code>isnull(LEFT(fielddata, LEN(fielddata) - PATINDEX('%[^'+CHAR(9)+CHAR(10)+CHAR(12)+CHAR(13)+']%', REVERSE(fielddata))+1),'') as ResultValue
</code>```

But it doesn't seems to work well (in some cases there are still new lines left). It might be more appropriate to use something like regex ^\s+$, but I'm not sure how it supposed to look (just putting regex into example doesn't seems to work)

Can you help me with this please?

UPDATE

---- Is not a part of string! I simply don't know how else I suppose to show here string before (with new lines) and string after without them.

UPDATE 2

Found a reason why previous example didn't work in any situation. It does nothing in case if string contains ONLY new lines (yep, I have those kind of situations)

答:
You can try below, should work as you're expecting.</p>

```<code>DECLARE @TEST NVARCHAR(MAX) = 'TEST
'
SELECT @TEST --test before

SET @TEST = (SELECT REPLACE(REPLACE(@TEST, CHAR(13), ''), CHAR(10), ''))
SELECT @TEST --test after
</code>```

Body:
Encountered issue when I needed to remove (or replace) new lines at the string end:

Somthing like this

-----
test

----

to

----
test
----

I encountered some examples such as

isnull(LEFT(fielddata, LEN(fielddata) - PATINDEX('%[^'+CHAR(9)+CHAR(10)+CHAR(12)+CHAR(13)+']%', REVERSE(fielddata))+1),'') as ResultValue

But it doesn't seems to work well (in some cases there are still new lines left). It might be more appropriate to use something like regex ^\s+$, but I'm not sure how it supposed to look (just putting regex into example doesn't seems to work)

Can you help me with this please?

UPDATE

---- Is not a part of string! I simply don't know how else I suppose to show here string before (with new lines) and string after without them.

UPDATE 2

Found a reason why previous example didn't work in any situation. It does nothing in case if string contains ONLY new lines (yep, I have those kind of situations)

Body:
You can try below, should work as you're expecting.

DECLARE @TEST NVARCHAR(MAX) = 'TEST
'
SELECT @TEST --test before

SET @TEST = (SELECT REPLACE(REPLACE(@TEST, CHAR(13), ''), CHAR(10), ''))
SELECT @TEST --test after


问:
Laravel Passport Password Grant - Client authentication failed
After hearing a lot about laravel passport, i thought of implementing it into my new project where my requirement is to create an API that'll be used in a mobile app.

So my mobile app is a client, which will further have its users.

I followed the steps mentioned by Taylor and also read about it here. In a nutshell I followed these steps:

Installed laravel/passport.

Created a website user.

Generated passport keys php artisan passport:install

Generated client_id and client_secret using php artisan passport:client

Added redirection and callback routes in web.php

Authorized the user and got the final access token.

Then I tried calling api/user( with Header Authorization containing value Bearer eyJ0eXAiOiJKV1...(token)

I received the data. Pretty simple and neat.

But my app users won't have these details. So I thought of configuring Password Grant Tokens which fits perfectly in my requirement.

Now starts the real headache. I've been trying to set this up for the last 3 days and continuously getting

```<code>{"error":"invalid_client","message":"Client authentication failed"}
</code>```

I've tried almost every guide I followed online: Redirection Issues, Add Atleast One Scope Solution, P100Y Issue etc.

But I'm still getting invalid client error. Here's what I'm passing through POSTMAN to oauth/token:

```<code>{
    "grant_type": "password,"
    "client_id": "3,"
    "client_secret": "8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g,"
    "username": "test@gmail.com,"
    "password": "123456,"
    "scope": ""
}
</code>```

Any help would be appreciated.

答: Have yo try running php artisan config:cache after all the passport commands.

Body:
After hearing a lot about laravel passport, i thought of implementing it into my new project where my requirement is to create an API that'll be used in a mobile app.

So my mobile app is a client, which will further have its users.

I followed the steps mentioned by Taylor and also read about it here. In a nutshell I followed these steps:

Installed laravel/passport.

Created a website user.

Generated passport keys php artisan passport:install

Generated client_id and client_secret using php artisan passport:client

Added redirection and callback routes in web.php

Authorized the user and got the final access token.

Then I tried calling api/user( with Header Authorization containing value Bearer eyJ0eXAiOiJKV1...(token)

I received the data. Pretty simple and neat.

But my app users won't have these details. So I thought of configuring Password Grant Tokens which fits perfectly in my requirement.

Now starts the real headache. I've been trying to set this up for the last 3 days and continuously getting

{"error":"invalid_client","message":"Client authentication failed"}

I've tried almost every guide I followed online: Redirection Issues, Add Atleast One Scope Solution, P100Y Issue etc.

But I'm still getting invalid client error. Here's what I'm passing through POSTMAN to oauth/token:

{
    "grant_type": "password,"
    "client_id": "3,"
    "client_secret": "8BUPCSyYEdsgtZFnD6bFG6eg7MKuuKJHLsdW0k6g,"
    "username": "test@gmail.com,"
    "password": "123456,"
    "scope": ""
}

Any help would be appreciated.


问:
Linux system to manage configurations of servers?
I need a software to manage configurations of linux servers in one central location. It should be able to push changes to servers automaticly. Version control would be an advantage...</p>

答: Have a look at Puppet</p>

ContentLicense: CC BY-SA 2.5

Body: Have a look at Puppet

OwnerDisplayName: matli


问:
how to create a numpy list of names from names of numpy files
I have a set of numpy files, they are in one folder.
I need to create a numpy list where I can put in every line some details about each file'name:

Example:
The file name:

```<code>AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
</code>```

Each line in my list must include:

```<code>300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667
</code>```

I mean that I need to put only  numbers then space.

I use this method but it gives all the name of my file.

```<code>import os
path_For_Numpy_Files = 'C:\\Users\\user\\My_Test_Traces\\1000_Traces_bin'
path_List_File='C:\\Users\\user\\My_Test_Traces\\NewTest.list_bin'
os.chdir(path_For_Numpy_Files)
list_files=os.listdir(os.getcwd())
with open(path_List_File, 'w') as fp:
    fp.write('\n'.join(sorted((list_files),key=os.path.getmtime)))
</code>```

Hou could I correct it to give me the waited result please?

Body:
I have a set of numpy files, they are in one folder.
I need to create a numpy list where I can put in every line some details about each file'name:

Example:
The file name:

AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy

Each line in my list must include:

300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667

I mean that I need to put only  numbers then space.

I use this method but it gives all the name of my file.

import os
path_For_Numpy_Files = 'C:\\Users\\user\\My_Test_Traces\\1000_Traces_bin'
path_List_File='C:\\Users\\user\\My_Test_Traces\\NewTest.list_bin'
os.chdir(path_For_Numpy_Files)
list_files=os.listdir(os.getcwd())
with open(path_List_File, 'w') as fp:
    fp.write('\n'.join(sorted((list_files),key=os.path.getmtime)))

Hou could I correct it to give me the waited result please?

Body:
This seems to be the basic idea.

from pathlib import Path
import re

p = Path('c:/scratch/sample')
for fileName in p.iterdir():
    print (fileName.name)
    print (' '.join(re.findall('=([0123456789abcdef]{2,})', fileName.name)))

Output from this script was:

AES_Trace=300001_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
300001 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667
AES_Trace=300002_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
300002 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667
AES_Trace=300003_key=000102030405060708090a0b0c0d0e0f_Plaintext=f9f19b259648feb20d842480745de16f_Ciphertext=a3140be40735f9f1865aa6b1b32b5667.npy
300003 000102030405060708090a0b0c0d0e0f f9f19b259648feb20d842480745de16f a3140be40735f9f1865aa6b1b32b5667


问:
Visual studio team services build .net core 1.1
I'm trying to build a .net core 1.1 project on vsts. The project is developed in vs2017 and it uses the csproj instead of project.json. I have tried multiple options to build id on vsts with the hosted agents (windows and linux).

i have tried the following build steps

Visual studio build

Set to use vs 2017 but i get a warning "Visual Studio version '15.0' not found. Looking for the latest version." And then i get errors because it cant include .net core packages.

.NET Core (PREVIEW)

Cant find project.json. When i set it to use csproj file it gives an error "The file type was not recognized"

Command build step

I tried to run the commands with command build steps. "dotnet build"  gives the error that it cant find the project.json file.

Anyone building dotnet 1.1 with csproj on vsts that can help me how to do it?

答:
In my case, I have a .NET Core web app and four library projects, all targeting the full framework since I'm using EF 6.

I tried all of the suggestions here and none of them worked. Building with Visual Studio Build on Hosted Agent 2017 does build the project, but doesn't output any binaries. And all the options above did build as well but didn't generate the output files.

Reading around I found the only way to get the output files was by running dotnet publishbut this generates a build error because nuget isn't restoring well the packages and msbuild can't find them. After being tired of trying to make it work during a whole day, casually I enabled the "Restore Nuget Packages" on the VS Buid task, and though it says it's deprecated, that seems to have solved my isse.


问:
traverse a tree having more than two children from top to bottom to get values in java and then traverse bottom up to again adjust values
I have a tree which can have more than two children so it is not a binary tree. In fact it can have n no. of children and it can have n-levels as well.

If I start from the root(has an id) then, the children have the root's id as parent id and the children have their own id as well. Similarly if I go to the next level children the upper level nodes id will serve as parent id for this level.
How do I need to traverse?
Starting from root node, on basis of root node id I will find the children(have root node id as parent id) then I need to retrieve some data from these children and do some calculation. Moving to next level which I will find when I will pass these children ids and then again do some calculation. The process continues until I don't find any records on basis of Ids.
Further I also need to traverse in reverse direction to do some deductions.

I am working with spring boot and mongodb. Using spring data mongodb.

Entity structure
-id
-parent id
- type
- amount
- vendor id.

I need a solution to traverse this sort of tree and retrieve the data.
This is also a performance critical task.

答:
If I were you I would add children field to the structure
So traversing down the tree will be just Depth-fisrt search. Recursive implementation would be:

```<code>private static final int NOT_FOUND = -1;
public int findItem(someCondition) {
  if (check(someCondition)) {
    return id;
  }
  for(Structure child:current.getChildes()) {
    int childResult = child.findItem(someCondition);
    if (childResult != NOT_FOUND) {
      return childResult;
    }
  }
  // this node and its childes are not comply with someCondition
  return NOT_FOUND;
}
</code>```

Depth-fisrt search could be written in iterative way.

This method will finish in O(N) and visits each node only once. If you can't change the structure then you have to visit each node at each level and spend O(N*n) time.

If you want to search faster than O(N) you need for some sorting like K-d tree. In cost of adding in O(log N) time you get searching in O(log N) time.

Building path is more simple:

```<code>Structure current = this;
while (current.getParent() != null) {
  current = current.getParent();
  path.add(current.id);
}
</code>```

Body:
If I were you I would add children field to the structure
So traversing down the tree will be just Depth-fisrt search. Recursive implementation would be:

private static final int NOT_FOUND = -1;
public int findItem(someCondition) {
  if (check(someCondition)) {
    return id;
  }
  for(Structure child:current.getChildes()) {
    int childResult = child.findItem(someCondition);
    if (childResult != NOT_FOUND) {
      return childResult;
    }
  }
  // this node and its childes are not comply with someCondition
  return NOT_FOUND;
}

Depth-fisrt search could be written in iterative way.

This method will finish in O(N) and visits each node only once. If you can't change the structure then you have to visit each node at each level and spend O(N*n) time.

If you want to search faster than O(N) you need for some sorting like K-d tree. In cost of adding in O(log N) time you get searching in O(log N) time.

Building path is more simple:

Structure current = this;
while (current.getParent() != null) {
  current = current.getParent();
  path.add(current.id);
}


问:
SAS: Utilizing macro variables as numbers in data step
I am touching up some SAS code I wrote and found a chunk of code I wish to execute more effectively. I have a time-series data set called 'Forecasts' which just consists of date and the 'Forecast' variable for a given date.

I wrote a simple block of code to take this variable and basically chop it up into a series of variables, each one representing one date:

```<code>data forecasts;
set forecasts;
  obs=_n_;
  array r(241);
  do i=1 to dim(r);
    if obs=i then r(i)=Forecast;
  end; drop i; drop obs; drop forecast;
run;
</code>```

However, the 'r(241)' part of this code really annoys me. I already have a macro variable which corresponds to the number of times I need to perform this operation (called 'n'), and I would rather just plug it into the array proclamation directly, something like:

```<code>array r(&n)
</code>```

etc.

However macro variables are obviously considered text, so even when I managed to import the macro variable into the data step, variants r(&n) doesn't work because it doesn't read 'n' as a numeric. Outside of wrapping this entire data step into a broader macro, how can I pull 'n' into the data step then convert it to a numeric so this operation works?

答:
Just as a suggestion, you don't need to do it this way. PROC TRANSPOSE exists for this purpose.  Then you don't even have to know how many variables/rows there are.

```<code>data forecast;
  call streaminit(7);
  do id = 1 to 243;
    forecast = rand('Normal')*5;
    output;
  end;
run;

proc transpose data=forecast out=forecasts prefix=r;
  by id;
  id id;
  var forecast;
run;
</code>```

If you don't actually want 243 rows but want just one, dump the by and the id statements.

Even if you wanted to do it in a data step, you could do this quite a bit faster  (Right now you're checking 241 * 241 times, you only need 241 times...) by putting the set inside the loop.  Here I use the automatically dropped variable _n_ to iterate the loop.

```<code>data forecasts;
  do _n_ = 1 by 1 until (eof);
    set forecast end=eof;
    array r(243);
    r[_n_] = forecast;
    output; *if you actually want one row per original row still;
    call missing(r[_n_]); *clear it out;
  end;
  drop forecast;
run;
</code>```

Body:
I am touching up some SAS code I wrote and found a chunk of code I wish to execute more effectively. I have a time-series data set called 'Forecasts' which just consists of date and the 'Forecast' variable for a given date.

I wrote a simple block of code to take this variable and basically chop it up into a series of variables, each one representing one date:

data forecasts;
set forecasts;
  obs=_n_;
  array r(241);
  do i=1 to dim(r);
    if obs=i then r(i)=Forecast;
  end; drop i; drop obs; drop forecast;
run;

However, the 'r(241)' part of this code really annoys me. I already have a macro variable which corresponds to the number of times I need to perform this operation (called 'n'), and I would rather just plug it into the array proclamation directly, something like:

array r(&n)

etc.

However macro variables are obviously considered text, so even when I managed to import the macro variable into the data step, variants r(&n) doesn't work because it doesn't read 'n' as a numeric. Outside of wrapping this entire data step into a broader macro, how can I pull 'n' into the data step then convert it to a numeric so this operation works?

Body:
Just as a suggestion, you don't need to do it this way. PROC TRANSPOSE exists for this purpose.  Then you don't even have to know how many variables/rows there are.

data forecast;
  call streaminit(7);
  do id = 1 to 243;
    forecast = rand('Normal')*5;
    output;
  end;
run;

proc transpose data=forecast out=forecasts prefix=r;
  by id;
  id id;
  var forecast;
run;

If you don't actually want 243 rows but want just one, dump the by and the id statements.

Even if you wanted to do it in a data step, you could do this quite a bit faster  (Right now you're checking 241 * 241 times, you only need 241 times...) by putting the set inside the loop.  Here I use the automatically dropped variable _n_ to iterate the loop.

data forecasts;
  do _n_ = 1 by 1 until (eof);
    set forecast end=eof;
    array r(243);
    r[_n_] = forecast;
    output; *if you actually want one row per original row still;
    call missing(r[_n_]); *clear it out;
  end;
  drop forecast;
run;


问:
jQuery Grep in Multidimensional Array
I have an array that looks like this:

```<code>car1: 2
car2: 3
truck: 1
bike: 2
</code>```

Now want to filter the array with jQuery grep to only see car elements.

```<code>var r = jQuery.grep(arr, function(a) {
    return a.indexOf('car') === 0;
});
</code>```

But my array is empty afterwards. What do I need to do in order to grep/filter the array correctly?

答:
Depending on whether your data is actually an array of objects, or if it is a single object with multiple properties, here is a solution for each.

// solution for array of objects
var elems = [{car1: 2}, {car2: 3}, {truck: 1}, {bike: 2}];
var filtered = elems.reduce(function (result, current) {
  var isCar = Object.keys(current).some(function (key){
    return key.indexOf("car") > -1;
  });
  if (isCar) {
    result.push(current);
  }
  return result;
}, []);
// returns an array of "car" objects
console.log(filtered)

// solution for single object with multiple properties
var elems2 = {car1: 2, car2: 3, truck: 1, bike: 2};
var filtered2 = Object.keys(elems2).reduce(function (result, current) {
  var isCar = current.indexOf("car") > -1;
  if (isCar) {
    result[current] = elems2[current];
  }
  return result;
}, {});
// returns single object with only "car" properties and their values
console.log(filtered2)```

Title: jQuery Grep in Multidimensional Array

Body:
I have an array that looks like this:

car1: 2
car2: 3
truck: 1
bike: 2

Now want to filter the array with jQuery grep to only see car elements.

var r = jQuery.grep(arr, function(a) {
    return a.indexOf('car') === 0;
});

But my array is empty afterwards. What do I need to do in order to grep/filter the array correctly?


问:
Getting all matching values from a column
I have a data frame named toy like so:

```<code>    toy<- structure(list(id = 1:10, Name = c("A", "B", "C", "D", "E", "F",
"G", "H", "A", "A"), Alt = c("X|Y|a", "O|P|dev", "A|W|are", "M|Q|G",
"H|f|j|i_m|am", "L|E|B|i|j", "x|C|xx|yy", NA, NA, NA), Place = c(1L,
4L, 8L, 12L, 13L, 8L, 3L, 1L, 1L, 1L)), .Names = c("id", "Name",
"Alt", "Place"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-10L), spec = structure(list(cols = structure(list(id = structure(list(), class = c("collector_integer",
"collector")), Name = structure(list(), class = c("collector_character",
"collector")), Alt = structure(list(), class = c("collector_character",
"collector")), Place = structure(list(), class = c("collector_integer",
"collector"))), .Names = c("id", "Name", "Alt", "Place")), default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))
</code>```

My purpose is to find matching characters in the Name column that is also in the Alt column. I have tried the following using dplyr:

```<code>toy_sep<-toy %>% separate(Alt , into=LETTERS[1:5],sep="\\|",extra="merge",remove=FALSE) %>% gather(Alias_id,Alias,A:E) %>% mutate(Match=match(Alias,Name))
</code>```

From this the output for whereever there is a match looks like:

```<code>matches<-toy_sep[complete.cases(toy_sep),]
</code>```

It gives close to what I want. However the problem is match returns the first location , while I want all the matches. In the example 1 is returned in the Match column in matches dataframe for A but I want all the ids. A has id's  9 and 10 (from the id column in toy dataframe) as well as 1. Thanks for any help using base/data.table/dplyr

Adding the desired output. Note that the numbers on the top right cell  need not be separated by a "|" . :

```<code>d_out<-structure(list(id = c(3L, 5L, 6L, 7L, 4L, 6L), Name = c("C",
"E", "F", "G", "D", "F"), Alt = c("A|W|are", "H|f|j|i_m|am",
"L|E|B|i|j", "x|C|xx|yy", "M|Q|G", "L|E|B|i|j"), Place = c(8L,
13L, 8L, 3L, 12L, 8L), Alias_id = c("A", "A", "B", "B", "C",
"C"), Alias = c("A", "H", "E", "C", "G", "B"), Match = c("1|9|10",
"8", "5", "3", "7", "2")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .Names = c("id", "Name", "Alt", "Place",
"Alias_id", "Alias", "Match"), spec = structure(list(cols = structure(list(
    id = structure(list(), class = c("collector_integer", "collector"
    )), Name = structure(list(), class = c("collector_character",
    "collector")), Alt = structure(list(), class = c("collector_character",
    "collector")), Place = structure(list(), class = c("collector_integer",
    "collector")), Alias_id = structure(list(), class = c("collector_character",
    "collector")), Alias = structure(list(), class = c("collector_character",
    "collector")), Match = structure(list(), class = c("collector_character",
    "collector"))), .Names = c("id", "Name", "Alt", "Place",
"Alias_id", "Alias", "Match")), default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))
</code>```

答:
Try this.</p>

```<code>  toy_sep<-toy %>%
  separate(Alt ,
           into=LETTERS[1:5],
           sep="\\|",
           extra="merge",
           remove=FALSE) %>%
  gather(Alias_id,Alias,A:E) %>%
  mutate(Match=apply(t(Alias),
                     2,
                     FUN = function(x){
                       ind=grep(x,toy$Name)
                       ifelse(!is.na(sum(ind))&length(ind) >= 1 ,
                              paste0(ind,collapse = "|"),
                              NA)
                       }
                     )
         )
  matches<-toy_sep[complete.cases(toy_sep),]
</code>```

Body:
I have a data frame named toy like so:

    toy<- structure(list(id = 1:10, Name = c("A", "B", "C", "D", "E", "F",
"G", "H", "A", "A"), Alt = c("X|Y|a", "O|P|dev", "A|W|are", "M|Q|G",
"H|f|j|i_m|am", "L|E|B|i|j", "x|C|xx|yy", NA, NA, NA), Place = c(1L,
4L, 8L, 12L, 13L, 8L, 3L, 1L, 1L, 1L)), .Names = c("id", "Name",
"Alt", "Place"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-10L), spec = structure(list(cols = structure(list(id = structure(list(), class = c("collector_integer",
"collector")), Name = structure(list(), class = c("collector_character",
"collector")), Alt = structure(list(), class = c("collector_character",
"collector")), Place = structure(list(), class = c("collector_integer",
"collector"))), .Names = c("id", "Name", "Alt", "Place")), default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))

My purpose is to find matching characters in the Name column that is also in the Alt column. I have tried the following using dplyr:

toy_sep<-toy %>% separate(Alt , into=LETTERS[1:5],sep="\\|",extra="merge",remove=FALSE) %>% gather(Alias_id,Alias,A:E) %>% mutate(Match=match(Alias,Name))

From this the output for whereever there is a match looks like:

matches<-toy_sep[complete.cases(toy_sep),]

It gives close to what I want. However the problem is match returns the first location , while I want all the matches. In the example 1 is returned in the Match column in matches dataframe for A but I want all the ids. A has id's  9 and 10 (from the id column in toy dataframe) as well as 1. Thanks for any help using base/data.table/dplyr

Adding the desired output. Note that the numbers on the top right cell  need not be separated by a "|" . :

d_out<-structure(list(id = c(3L, 5L, 6L, 7L, 4L, 6L), Name = c("C",
"E", "F", "G", "D", "F"), Alt = c("A|W|are", "H|f|j|i_m|am",
"L|E|B|i|j", "x|C|xx|yy", "M|Q|G", "L|E|B|i|j"), Place = c(8L,
13L, 8L, 3L, 12L, 8L), Alias_id = c("A", "A", "B", "B", "C",
"C"), Alias = c("A", "H", "E", "C", "G", "B"), Match = c("1|9|10",
"8", "5", "3", "7", "2")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .Names = c("id", "Name", "Alt", "Place",
"Alias_id", "Alias", "Match"), spec = structure(list(cols = structure(list(
    id = structure(list(), class = c("collector_integer", "collector"
    )), Name = structure(list(), class = c("collector_character",
    "collector")), Alt = structure(list(), class = c("collector_character",
    "collector")), Place = structure(list(), class = c("collector_integer",
    "collector")), Alias_id = structure(list(), class = c("collector_character",
    "collector")), Alias = structure(list(), class = c("collector_character",
    "collector")), Match = structure(list(), class = c("collector_character",
    "collector"))), .Names = c("id", "Name", "Alt", "Place",
"Alias_id", "Alias", "Match")), default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))

Body:
Try this.

  toy_sep<-toy %>%
  separate(Alt ,
           into=LETTERS[1:5],
           sep="\\|",
           extra="merge",
           remove=FALSE) %>%
  gather(Alias_id,Alias,A:E) %>%
  mutate(Match=apply(t(Alias),
                     2,
                     FUN = function(x){
                       ind=grep(x,toy$Name)
                       ifelse(!is.na(sum(ind))&length(ind) >= 1 ,
                              paste0(ind,collapse = "|"),
                              NA)
                       }
                     )
         )
  matches<-toy_sep[complete.cases(toy_sep),]


问:
Installing PHP 5.3.29 from Sources on Ubuntu 14 with Apache 2 Module
I successfully installed PHP 5.3.29 on Ubuntu 14 with Apache 2 separately.

I installed PHP with the following method:

```<code>sudo -i
wget http://in1.php.net/distributions/php-5.3.29.tar.bz2
tar -xvf php-5.3.29.tar.bz2
cd php-5.3.29
./configure
make
make install
</code>```

However, PHP and Apache do not seem to have any linkage. That means I have installed both Apache and PHP, but Apache does not run PHP.

What I have tried:

From this site: https://docs.moodle.org/28/en/Compiling_PHP_from_source

"Configuring Apache and PHP", it asked me to add this in the Apache configuration file:

LoadModule php5_module  modules/libphp5.so

However, I do not have "libphp5.so" module.

Some people asked me to run this:

```<code>sudo apt-get install libapache2-mod-php5
</code>```

But after running the command, it installed PHP 5.5.9 for me, but I need PHP 5.3.29.

How can I make Apache run PHP 5.3.29 which I have installed?

答:
Wittich's answer is fabulous! I used it in order to replace php 5.1 with php 5.6 on my unix website. Unlike Wittich, I wasn't trying to get two versions running simultaneously; I was simply trying to do an upgrade from an older version of php that was integrated with apache to a newer version that would run from cgi.

For some reason, several of Wittich's commands (such as the SetHandler command) prevented Apache from loading after I tried them. I ended up having to simplify his answer so that Apache would run correctly. I made 6 changes in Wittich's procedures:

I used yum instead of apt-get because apt-get wouldn't run on my Unix system.

Since I was installing php 5.6 not php 5.3, I changed all instances of "php53" to "php56" in the configure command's switches. This was not necessary for everything to work, but it will help you understand my paths below:

In one of my httpd configuration folders (/etc/httpd/conf.d), I found a file that was already set up for a cgi implementation of php (php_cgi.conf). Its contents were:

    scriptAlias /phppath/ "/var/www/cgi-bin/cgi_wrapper/"

    Action php-script /phppath/cgi_wrapper

The contents and existence of this file let me skip or change several of Wittich's steps. I neither created php53-cgi, nor did I create php53.conf.

Instead of creating php53-cgi, I replaced the contents of the existing file (/var/www/cgi-bin/cgi-wrapper/cgi-wrapper) with the contents suggested for php53-cgi. Due to the other lines preventing apache from rebooting properly, I ended up with the contents of that file just being his first and last lines (without the slash before the number sign):

    \#!/bin/sh

    exec /usr/bin/php56/php-cgi

Instead of creating php53.conf, I replaced a single command in the php.conf file (/etc/httpd/conf.d/php.conf). I changed the add-handler for php command so that it now reads:

    AddHandler php-script .php

I didn't change the httpd.conf files at all since my goal was simply to replace the old php, not create different versions of php that would run on different virtual hosts. However, I believe that I could have set up my websites to run old version and the new one in different directories, simply by changing the httpd.conf file so that the old AddHandler would appear in some directories while the new AddHandler would appear in others.

So, in summary, it is easy to convert Wittich's answer into a way to upgrade from an older apache based php version to a newer cgi-based version if you have an existing php_cgi.conf file that you can hijack and use as a guide.

I found a posting by David Brogdon to be a good complement to Wittich's answer for those who are new to the configure, make, and make install commands:

http://www.onlamp.com/pub/a/php/2000/11/17/php_admin.html

I searched the Internet for hours and never found anything as helpful as Brogdon's post and Wittich's  answer. Wittich's answer must have worked perfectly on his Unix system, but I had to modify it a bit in order to get it to work on mine.

Body:
I successfully installed PHP 5.3.29 on Ubuntu 14 with Apache 2 separately.

I installed PHP with the following method:

sudo -i
wget http://in1.php.net/distributions/php-5.3.29.tar.bz2
tar -xvf php-5.3.29.tar.bz2
cd php-5.3.29
./configure
make
make install

However, PHP and Apache do not seem to have any linkage. That means I have installed both Apache and PHP, but Apache does not run PHP.

What I have tried:

From this site: https://docs.moodle.org/28/en/Compiling_PHP_from_source

"Configuring Apache and PHP", it asked me to add this in the Apache configuration file:

LoadModule php5_module  modules/libphp5.so

However, I do not have "libphp5.so" module.

Some people asked me to run this:

sudo apt-get install libapache2-mod-php5

But after running the command, it installed PHP 5.5.9 for me, but I need PHP 5.3.29.

How can I make Apache run PHP 5.3.29 which I have installed?


问:
OpenSSl library for Android
Where it is possible to download OpenSSL library for Android 7.0?
From this subject I took for Android 6 Error "Could not load SSL library" on Android with TidHTTP</p>

答:
If you use the new components for REST in last versions of Delphi you can connect HTTPS without SSL libraries.

¿Can you change TidHttp for THTTPClient?

Here you can find a sample article that explain how to download an image from web using this component. Works in Android and no need external libraries.

Title: OpenSSl library for Android


问:
Linq to Sql How To delete table along with all relationships
I have a table "User" With a relationship to around 7 other tables. If I try to delete the user it won't let me unless I delete all the data in the other tables that has a userId. Is there a way to delete everything automatically without having to delete each one of the tables with that UserId  one table at a time?</p>

答:
You can use cascade delete.
Code first: In OnModelCreating method of context class:</p>

```<code>modelBuilder.Entity<Table1>()
.HasOptional(c => c.User)
.WithMany(c => c.Table1s)
.HasForeignKey(c => c.UsereID).WillCascadeOnDelete(true);

modelBuilder.Entity<Table2>()
.HasRequired(c => c.User)
.WithMany(c => c.Table2s)
.HasForeignKey(c => c.UsereID).WillCascadeOnDelete(true);
</code>```

Body:
You can use cascade delete.
Code first: In OnModelCreating method of context class:

modelBuilder.Entity<Table1>()
.HasOptional(c => c.User)
.WithMany(c => c.Table1s)
.HasForeignKey(c => c.UsereID).WillCascadeOnDelete(true);

modelBuilder.Entity<Table2>()
.HasRequired(c => c.User)
.WithMany(c => c.Table2s)
.HasForeignKey(c => c.UsereID).WillCascadeOnDelete(true);