问:
How to use sended post data on server side
I have a simple script to upload a file. Actually everything is working fine.

```<code>private void UploadCSV()
{
    Uri address = new Uri("https://www.mydomain.xy/inc.upload.php");
    string fileName = @"C:\test.csv";

    using (WebClient client = new WebClient())
    {
        var parameters = new NameValueCollection();
        parameters.Add("test", "aaaa");
        client.QueryString = parameters;
        client.UploadProgressChanged += WebClientUploadProgressChanged;
        client.UploadFileCompleted += WebClientUploadCompleted;
        client.UploadFileAsync(address, "POST", fileName);

    }
}
</code>```

Now as you can see, I try so send some data via POST test what contains aaaa. But now matter how I try to select the data serverside... there is nothing....

I tried $_POST['test'], $_POST['data']['test'].... but no results.

How can I access the extra Data ?

答:
client.QueryString = parameters;

This will append a query string to the URL that you send the data to.

Even though the request method is POST, PHP always provides the query string parameters in $_GET.

Body:
I have a simple script to upload a file. Actually everything is working fine.

private void UploadCSV()
{
    Uri address = new Uri("https://www.mydomain.xy/inc.upload.php");
    string fileName = @"C:\test.csv";

    using (WebClient client = new WebClient())
    {
        var parameters = new NameValueCollection();
        parameters.Add("test", "aaaa");
        client.QueryString = parameters;
        client.UploadProgressChanged += WebClientUploadProgressChanged;
        client.UploadFileCompleted += WebClientUploadCompleted;
        client.UploadFileAsync(address, "POST", fileName);

    }
}

Now as you can see, I try so send some data via POST test what contains aaaa. But now matter how I try to select the data serverside... there is nothing....

I tried $_POST['test'], $_POST['data']['test'].... but no results.

How can I access the extra Data ?


来源: stackexchange

问:
Need to fade in fade out text in sequence
I came across text that fades in and fades out one after the other.

In developer mode, I was able to see the opacity vary for the texts from 0 to 1 to 0 in a sequence. How is this achieved?

```<code><div class="text" style="opacity: 0;">The</div>
<div class="text" style="opacity: 0;">Nomads</div>
</code>```

答:
you can use the following:

obviously I'm going to use JQuery:

```<code>jQuery('<div_name>').css('opacity', '<opacity_value>');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I came across text that fades in and fades out one after the other.

In developer mode, I was able to see the opacity vary for the texts from 0 to 1 to 0 in a sequence. How is this achieved?

The

Nomads

Body:
you can use the following:

obviously I'm going to use JQuery:

jQuery('<div_name>').css('opacity', '<opacity_value>');


问:
how to change forms as radiobutton are selected
I have swing frame with 3 radio buttons and a panel below these buttons.The panel has to be different for each options of the radio-buttons.
I have to change the panel as these radiobuttons are clicked by the user.

i tried :

```<code>public RadioFrame() {
    initComponents();
    groupbuttons();
    changePanel();
}

private void groupbuttons(){
   //code to group these 3 buttons.
}

private void changePanel(){
  if (jradioButton1.isSelected()){
     //change the panel for radiobutton1
  }
  if (jradioButton2.isSelected()){
     //change the panel for radiobutton2
  }      if (jradioButton3.isSelected()){
     //change the panel for radiobutton3
  }
}
</code>```

but this works only when the frame is loaded for the first time,it doesn't change as the user selects different radiobutton as the program runs.

how can i solve this ?

答:
You can use a JPanel with a CardLayout. Each page is a JPanel and a card inside the outer JPanel.

UPDATE:

To switch from one card to another, you would do:

```<code>CardLayout layout = (CardLayout)cardPanel.getLayout();
layout.show(cardPanel, "card name");
</code>```

You can easily design you pages in the Netbeans visual editor.

UPDATE 2:

In your case:

```<code>CardLayout layout = (CardLayout)cardPanel.getLayout();
if (jradioButton1.isSelected()){
    layout.show(cardPanel, "panel1");
}
if (jradioButton2.isSelected()){
    layout.show(cardPanel, "panel2");
}
if (jradioButton3.isSelected()){
    layout.show(cardPanel, "panel3");
}
</code>```

Body:
I have swing frame with 3 radio buttons and a panel below these buttons.The panel has to be different for each options of the radio-buttons.
I have to change the panel as these radiobuttons are clicked by the user.

i tried :

public RadioFrame() {
    initComponents();
    groupbuttons();
    changePanel();
}

private void groupbuttons(){
   //code to group these 3 buttons.
}

private void changePanel(){
  if (jradioButton1.isSelected()){
     //change the panel for radiobutton1
  }
  if (jradioButton2.isSelected()){
     //change the panel for radiobutton2
  }      if (jradioButton3.isSelected()){
     //change the panel for radiobutton3
  }
}

but this works only when the frame is loaded for the first time,it doesn't change as the user selects different radiobutton as the program runs.

how can i solve this ?

Body:
You can use a JPanel with a CardLayout. Each page is a JPanel and a card inside the outer JPanel.

UPDATE:

To switch from one card to another, you would do:

CardLayout layout = (CardLayout)cardPanel.getLayout();
layout.show(cardPanel, "card name");

You can easily design you pages in the Netbeans visual editor.

UPDATE 2:

In your case:

CardLayout layout = (CardLayout)cardPanel.getLayout();
if (jradioButton1.isSelected()){
    layout.show(cardPanel, "panel1");
}
if (jradioButton2.isSelected()){
    layout.show(cardPanel, "panel2");
}
if (jradioButton3.isSelected()){
    layout.show(cardPanel, "panel3");
}


问:
How to compile PJSIP for Android?
I'm trying to compile PJSIP for Android. I follow official tutorial from this site: https://trac.pjsip.org/repos/wiki/Getting-Started/Android.
Unfortunately when I execute command "make dep" I get this error:

```<code>/Applications/Xcode.app/Contents/Developer/usr/bin/make -f Samples.mak dependmake[2]: Nothing to be done for `depend'.
</code>```

My steps:

- I cloned repo from svn. Also tried release package.

- I added config_site.h. Exactly the same as in tutorial.

- Android NDK export is defined in bash_profile.

- Execution of ./configure-android goes without any problems.

I'm using MacOS for building. I also tried on Ubuntu but I get the same error...

In MacOS I also have SWIG installed throught brew package manager.

Any ideas why I get this error?
Thanks in advance for any help.

答:
Ok, I found out how to make it work. You have to modify Makefile in (project_root)/pjsip-apps/build and move line:

```<code>$(MAKE) -f Samples.mak $@
</code>```

to saparate section without "depend":

```<code>clean realclean:
    $(MAKE) -f Samples.mak $@
</code>```

Title: How to compile PJSIP for Android?

Body:
I'm trying to compile PJSIP for Android. I follow official tutorial from this site: https://trac.pjsip.org/repos/wiki/Getting-Started/Android.
Unfortunately when I execute command "make dep" I get this error:

/Applications/Xcode.app/Contents/Developer/usr/bin/make -f Samples.mak dependmake[2]: Nothing to be done for `depend'.

My steps:

- I cloned repo from svn. Also tried release package.

- I added config_site.h. Exactly the same as in tutorial.

- Android NDK export is defined in bash_profile.

- Execution of ./configure-android goes without any problems.

I'm using MacOS for building. I also tried on Ubuntu but I get the same error...

In MacOS I also have SWIG installed throught brew package manager.

Any ideas why I get this error?
Thanks in advance for any help.

Body:
Ok, I found out how to make it work. You have to modify Makefile in (project_root)/pjsip-apps/build and move line:

$(MAKE) -f Samples.mak $@

to saparate section without "depend":

clean realclean:
    $(MAKE) -f Samples.mak $@


问:
Simple "WHERE" query gone wrong
I am having trouble creating a new column within a materialized view. I am trying to create this column so that when a row = "Average" within the expected clickthrough rate column it will return the calculation of how many impressions there are within that row.  As far as I can see everything is set up accordingly.  I am however getting the  following error message.

```<code>ERROR:  syntax error at or near "clickthrough"
LINE 2: SELECT SUM("Impressions" * 1 ) WHERE Expected clickthrough r...
                                                  ^
********** Error **********

ERROR: syntax error at or near "clickthrough"
SQL state: 42601
Character: 94
</code>```

It appears to me that any different variation that I make here ends up in a similar error message.

Does anyone know a solution to this one?  Is the entire query wrong?

```<code>CREATE MATERIALIZED VIEW adwords_calculated AS
SELECT SUM("Impressions" * 1 ) WHERE Expected clickthrough rate = "Average"
AS Average Clickthrough Rate
from adwords_initial;
</code>```

Current Columns

```<code>Impressions| Expected clickthrough rate
-----------+----------------------------
1          |--
66         |--
12         |Average
13         |--
1000       |Above Average
45         |Average
4          |Below Average
</code>```

Desire Result

```<code>Impressions| Expected clickthrough rate |Average Clickthrough Rate
-----------+----------------------------+-----------------
1          |--                          |0
66         |--                          |0
12         |Average                     |12
13         |--                          |0
1000       |Above Average               |0
45         |Average                     |45
4          |Below Average               |0
</code>```

Final result, (additional columns added per request in the comments.

```<code>Impressions| Expected clickthrough rate |Average CTR| Country
-----------+----------------------------+-----------+----------
1          |--                          |0          |USA
66         |--                          |0          |Germany
12         |Average                     |12         |Austria
13         |--                          |0          |UK
1000       |Above Average               |0          |China
45         |Average                     |45         |USA
4          |Below Average               |0          |Germany
</code>```

答:
If you really need column names like that, you must escape them with double quotes. String literals must be enclosed in single quotes. Also, the order of clauses is wrong. It should be

```<code>SELECT expression AS alias
FROM table
WHERE condition;
</code>```

Title: Simple "WHERE" query gone wrong

Body:
I am having trouble creating a new column within a materialized view. I am trying to create this column so that when a row = "Average" within the expected clickthrough rate column it will return the calculation of how many impressions there are within that row.  As far as I can see everything is set up accordingly.  I am however getting the  following error message.

ERROR:  syntax error at or near "clickthrough"
LINE 2: SELECT SUM("Impressions" * 1 ) WHERE Expected clickthrough r...
                                                  ^
********** Error **********

ERROR: syntax error at or near "clickthrough"
SQL state: 42601
Character: 94

It appears to me that any different variation that I make here ends up in a similar error message.

Does anyone know a solution to this one?  Is the entire query wrong?

CREATE MATERIALIZED VIEW adwords_calculated AS
SELECT SUM("Impressions" * 1 ) WHERE Expected clickthrough rate = "Average"
AS Average Clickthrough Rate
from adwords_initial;

Current Columns

Impressions| Expected clickthrough rate
-----------+----------------------------
1          |--
66         |--
12         |Average
13         |--
1000       |Above Average
45         |Average
4          |Below Average

Desire Result

Impressions| Expected clickthrough rate |Average Clickthrough Rate
-----------+----------------------------+-----------------
1          |--                          |0
66         |--                          |0
12         |Average                     |12
13         |--                          |0
1000       |Above Average               |0
45         |Average                     |45
4          |Below Average               |0

Final result, (additional columns added per request in the comments.

Impressions| Expected clickthrough rate |Average CTR| Country
-----------+----------------------------+-----------+----------
1          |--                          |0          |USA
66         |--                          |0          |Germany
12         |Average                     |12         |Austria
13         |--                          |0          |UK
1000       |Above Average               |0          |China
45         |Average                     |45         |USA
4          |Below Average               |0          |Germany

Body:
If you really need column names like that, you must escape them with double quotes. String literals must be enclosed in single quotes. Also, the order of clauses is wrong. It should be

SELECT expression AS alias
FROM table
WHERE condition;


问:
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service
I'm getting this error in my Hibernate desktop application:

```<code>Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
</code>```

It's not creating SessionFactory and giving this exception:

```<code>Executing E:\Vishal\summer\EmpMan\dist\run1432002073\EmpMan.jar using platform C:\Program Files (x86)\Java\jdk1.8.0_131\jre/bin/java
Jul 04, 2017 2:24:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Jul 04, 2017 2:24:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 04, 2017 2:24:35 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:~/EmpMan]
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=sa, password=****}
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
</code>```

That's it. I'm getting only this much information.

My hibernate.cfg.xml file configuration:

```<code><hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:~/EmpMan</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">sa</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <!-- Names the annotated entity class -->
        <mapping class="models.AdminDetails"/>
        <mapping class="models.EmployeeDetails" />
        <mapping class="models.DepartmentDetails" />
        <mapping class="models.DailyDataDetails"/>
    </session-factory>

</hibernate-configuration>
</code>```

Notice:

=> I'm using h2 database and I want to configure embedded database

=> I'm using netbeans and Java8 with hibernate version 5.2.10

=> I'm new to h2 database

=> Where to locate my EmpMan database in my project?

答: Problem Solved : I have already exist same named database so i changed name and now it's working :) Thank you guys</p>

Body:
I'm getting this error in my Hibernate desktop application:

Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

It's not creating SessionFactory and giving this exception:

Executing E:\Vishal\summer\EmpMan\dist\run1432002073\EmpMan.jar using platform C:\Program Files (x86)\Java\jdk1.8.0_131\jre/bin/java
Jul 04, 2017 2:24:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Jul 04, 2017 2:24:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 04, 2017 2:24:35 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:~/EmpMan]
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=sa, password=****}
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 04, 2017 2:24:35 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

That's it. I'm getting only this much information.

My hibernate.cfg.xml file configuration:

<hibernate-configuration>

    <session-factory>

        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:~/EmpMan</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">sa</property>

        <property name="connection.pool_size">1</property>

        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">create</property>

        <mapping class="models.AdminDetails"/>
        <mapping class="models.EmployeeDetails" />
        <mapping class="models.DepartmentDetails" />
        <mapping class="models.DailyDataDetails"/>
    </session-factory>

</hibernate-configuration>

Notice:

=> I'm using h2 database and I want to configure embedded database

=> I'm using netbeans and Java8 with hibernate version 5.2.10

=> I'm new to h2 database

=> Where to locate my EmpMan database in my project?


问:
After upgrading to gradle 3.0.0-alpha5 libraries are not resolved at compile time
I recently upgraded to the new gradle 3.0.0-alpha5 after which some libraries are not resolved at compile time. However, all works fine at runtime, but when I try to include the missing libraries, I get runtime error.

this works at runtime but libraries are not resolved at compile time:

```<code>compile('jp.wasabeef:picasso-transformations:2.1.2') {
        exclude group: 'com.squareup.picasso'
}
</code>```

this resolves the libraries but fails at runtime:

```<code>compile 'jp.wasabeef:picasso-transformations:2.1.2'
</code>```

答:
I was having same problem recently. My workaround for the problem is as below.

First of all remove this library from the project and sync the project.

After successful sync you will get errors.

Now add this library again to the project and sync again.

Now your problem will be solved.

Body:
I recently upgraded to the new gradle 3.0.0-alpha5 after which some libraries are not resolved at compile time. However, all works fine at runtime, but when I try to include the missing libraries, I get runtime error.

this works at runtime but libraries are not resolved at compile time:

compile('jp.wasabeef:picasso-transformations:2.1.2') {
        exclude group: 'com.squareup.picasso'
}

this resolves the libraries but fails at runtime:

compile 'jp.wasabeef:picasso-transformations:2.1.2'


问:
svn directory as webroot
What I would like to do is point the webroot from my dev webserver to some dir that is in some way linked to svn so when I commit changes they will be automatically visible on my dev webserver.

Any clue how I can do this?

EDIT

i'm creating a django project so i'm justing the Django development server

答: Having a production server auto-update is probably not a great idea.  But if you'd like to do that with dev boxes, look into a continuous integration service like Hudson.  It can watch your source repository and automatically update one or more working copies every time you commit code.  If you have any other work which needs to be done (eg, execute builds, restart daemons/services, flush some caches, etc.), this can do that work as well.</p>

ContentLicense: CC BY-SA 2.5

Title: svn directory as webroot


问:
Can I exactly mimic inheritance behavior with delegation by composition in Python?
In python, I want to mimic the following behavior with delegation by composition:

```<code>class Object1(object):

    def __init__(self):
        pass

    def method1(self):
        print "This is method 1 from object 1"
        return self.method2()

    def method2(self):
        raise Exception

class Object2(Object1):

    def method2(self):
        print "This is method 2 from object 2"

obj2 = Object2()
obj2.method1()
</code>```

The output is:

```<code>This is method 1 from object 1
This is method 2 from object 2
</code>```

In other words, I want to be able to create a class that copies the behavior of an already existing class except for certain methods. However, it is important that once my program goes into a method of the already existing class, it returns to the new class in case I have overridden the function. However, with the following code this is not the case:

```<code>class Object3(object):

    def __init__(self):
        pass

    def method1(self):
        print "This is method 1 from object 3"
        return self.method2()

    def method2(self):
        raise Exception

class Object4(object):

    def __init__(self):
        self.obj = Object3()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)

    def method2(self):
        print "This is method 2 from object 4"

obj4 = Object4()
obj4.method1()
</code>```

Instead of method2 from Object4 being called from method1 of Object3 (the behavior I want), method2 from Object3 is called (and an exception is raised). Is there any way to achieve the behavior I want without making changes to Object3?

答:
Since there is no reference to Object4 instance (obj4) available to Object3 class, it will be calling method2 of self, i.e. Object3.

This answer might provide more clarity and a possible solution.

Body:
In python, I want to mimic the following behavior with delegation by composition:

class Object1(object):

    def __init__(self):
        pass

    def method1(self):
        print "This is method 1 from object 1"
        return self.method2()

    def method2(self):
        raise Exception

class Object2(Object1):

    def method2(self):
        print "This is method 2 from object 2"

obj2 = Object2()
obj2.method1()

The output is:

This is method 1 from object 1
This is method 2 from object 2

In other words, I want to be able to create a class that copies the behavior of an already existing class except for certain methods. However, it is important that once my program goes into a method of the already existing class, it returns to the new class in case I have overridden the function. However, with the following code this is not the case:

class Object3(object):

    def __init__(self):
        pass

    def method1(self):
        print "This is method 1 from object 3"
        return self.method2()

    def method2(self):
        raise Exception

class Object4(object):

    def __init__(self):
        self.obj = Object3()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)

    def method2(self):
        print "This is method 2 from object 4"

obj4 = Object4()
obj4.method1()

Instead of method2 from Object4 being called from method1 of Object3 (the behavior I want), method2 from Object3 is called (and an exception is raised). Is there any way to achieve the behavior I want without making changes to Object3?


问:
Find all combinations matching certain criteria in an array in Ruby
I have the following array:

```<code>a = ["melon | apple", "kiwi | melon", "apple | orange", "pineapple | kiwi"]
</code>```

I want all strings of yielded by connecting the latter part (after "|") of a string element and the former part (before "|") of the following string element. a.combination_with_criteria(3).to_a should output:

```<code>["kiwi | melon", "melon | apple", "apple | orange"]
["pineapple | kiwi", "kiwi | melon", "melon | apple"]
</code>```

a.combination(3).to_a gives all possible combinations but in random order.

Maybe it's better to work with hashes for this purpose.

答:
a.combination(3).to_a gives all possible combinations but in random order.

Let's see:

```<code>a.combination(3).to_a
#=> [
#     ["melon | apple", "kiwi | melon", "apple | orange"],
#     ["melon | apple", "kiwi | melon", "pineapple | kiwi"],
#     ["melon | apple", "apple | orange", "pineapple | kiwi"],
#     ["kiwi | melon", "apple | orange", "pineapple | kiwi"]
#   ]
</code>```

Apparently, it contains neither ["kiwi | melon", "melon | apple", "apple | orange"] nor ["pineapple | kiwi", "kiwi | melon", "melon | apple"].

To get those as well, you have to use permutation instead:

```<code>a.permutation(3).to_a
#=> [
#     ["melon | apple", "kiwi | melon", "apple | orange"],
#     ["melon | apple", "kiwi | melon", "pineapple | kiwi"],
#     ["melon | apple", "apple | orange", "kiwi | melon"],
#     ["melon | apple", "apple | orange", "pineapple | kiwi"],
#     ["melon | apple", "pineapple | kiwi", "kiwi | melon"],
#     ["melon | apple", "pineapple | kiwi", "apple | orange"],
#     ["kiwi | melon", "melon | apple", "apple | orange"],      <--- here
#     ["kiwi | melon", "melon | apple", "pineapple | kiwi"],
#     ["kiwi | melon", "apple | orange", "melon | apple"],
#     ["kiwi | melon", "apple | orange", "pineapple | kiwi"],
#     ["kiwi | melon", "pineapple | kiwi", "melon | apple"],
#     ["kiwi | melon", "pineapple | kiwi", "apple | orange"],
#     ["apple | orange", "melon | apple", "kiwi | melon"],
#     ["apple | orange", "melon | apple", "pineapple | kiwi"],
#     ["apple | orange", "kiwi | melon", "melon | apple"],
#     ["apple | orange", "kiwi | melon", "pineapple | kiwi"],
#     ["apple | orange", "pineapple | kiwi", "melon | apple"],
#     ["apple | orange", "pineapple | kiwi", "kiwi | melon"],
#     ["pineapple | kiwi", "melon | apple", "kiwi | melon"],
#     ["pineapple | kiwi", "melon | apple", "apple | orange"],
#     ["pineapple | kiwi", "kiwi | melon", "melon | apple"],    <--- here
#     ["pineapple | kiwi", "kiwi | melon", "apple | orange"],
#     ["pineapple | kiwi", "apple | orange", "melon | apple"],
#     ["pineapple | kiwi", "apple | orange", "kiwi | melon"]
#   ]
</code>```

You probably know that select can be used to filter out the correct elements, but how does the condition look like?

Let's take a matching pair:

```<code>a = 'kiwi | melon'
b = 'melon | apple'
</code>```

We can split those by ' | ' to get the parts:

```<code>a.split(' | ') #=> ["kiwi", "melon"]
b.split(' | ') #=> ["melon", "apple"]
</code>```

It's a match if a's last word matches b's first word:

```<code>a.split(' | ').last == b.split(' | ').first
#=> true
</code>```

To check this for each consecutive pair of strings in an array, we can use each_cons:

```<code>['kiwi | melon', 'melon | apple', 'apple | orange'].each_cons(2) do |a, b|
  p a.split(' | ').last == b.split(' | ').first
end
</code>```

It first passes 'kiwi | melon' and 'melon | apple' to the block and then 'melon | apple' and 'apple | orange'.

For this array, the output is:

```<code>true
true
</code>```

To determine if the block returns true for all pairs, we can append all? to each_cons:

```<code>['kiwi | melon', 'melon | apple', 'apple | orange'].each_cons(2).all? do |a, b|
  a.split(' | ').last == b.split(' | ').first
end
</code>```

And this is exactly, what we can pass to select:

```<code>a.permutation(3).select do |sub_array|
  sub_array.each_cons(2).all? do |a, b|
    a.split(' | ').last == b.split(' | ').first
  end
end
#=> [
#     ["kiwi | melon", "melon | apple", "apple | orange"],
#     ["pineapple | kiwi", "kiwi | melon", "melon | apple"]
#   ]
</code>```

Note that this still creates a huge temporary array of all permutations and it splits the strings for each comparison, so you might want to look for a more optimized solution. But this should get you started.

Body:
I have the following array:

a = ["melon | apple", "kiwi | melon", "apple | orange", "pineapple | kiwi"]

I want all strings of yielded by connecting the latter part (after "|") of a string element and the former part (before "|") of the following string element. a.combination_with_criteria(3).to_a should output:

["kiwi | melon", "melon | apple", "apple | orange"]
["pineapple | kiwi", "kiwi | melon", "melon | apple"]

a.combination(3).to_a gives all possible combinations but in random order.

Maybe it's better to work with hashes for this purpose.

Body:
a.combination(3).to_a gives all possible combinations but in random order.

Let's see:

a.combination(3).to_a
#=> [
#     ["melon | apple", "kiwi | melon", "apple | orange"],
#     ["melon | apple", "kiwi | melon", "pineapple | kiwi"],
#     ["melon | apple", "apple | orange", "pineapple | kiwi"],
#     ["kiwi | melon", "apple | orange", "pineapple | kiwi"]
#   ]

Apparently, it contains neither ["kiwi | melon", "melon | apple", "apple | orange"] nor ["pineapple | kiwi", "kiwi | melon", "melon | apple"].

To get those as well, you have to use permutation instead:

a.permutation(3).to_a
#=> [
#     ["melon | apple", "kiwi | melon", "apple | orange"],
#     ["melon | apple", "kiwi | melon", "pineapple | kiwi"],
#     ["melon | apple", "apple | orange", "kiwi | melon"],
#     ["melon | apple", "apple | orange", "pineapple | kiwi"],
#     ["melon | apple", "pineapple | kiwi", "kiwi | melon"],
#     ["melon | apple", "pineapple | kiwi", "apple | orange"],
#     ["kiwi | melon", "melon | apple", "apple | orange"],      <--- here
#     ["kiwi | melon", "melon | apple", "pineapple | kiwi"],
#     ["kiwi | melon", "apple | orange", "melon | apple"],
#     ["kiwi | melon", "apple | orange", "pineapple | kiwi"],
#     ["kiwi | melon", "pineapple | kiwi", "melon | apple"],
#     ["kiwi | melon", "pineapple | kiwi", "apple | orange"],
#     ["apple | orange", "melon | apple", "kiwi | melon"],
#     ["apple | orange", "melon | apple", "pineapple | kiwi"],
#     ["apple | orange", "kiwi | melon", "melon | apple"],
#     ["apple | orange", "kiwi | melon", "pineapple | kiwi"],
#     ["apple | orange", "pineapple | kiwi", "melon | apple"],
#     ["apple | orange", "pineapple | kiwi", "kiwi | melon"],
#     ["pineapple | kiwi", "melon | apple", "kiwi | melon"],
#     ["pineapple | kiwi", "melon | apple", "apple | orange"],
#     ["pineapple | kiwi", "kiwi | melon", "melon | apple"],    <--- here
#     ["pineapple | kiwi", "kiwi | melon", "apple | orange"],
#     ["pineapple | kiwi", "apple | orange", "melon | apple"],
#     ["pineapple | kiwi", "apple | orange", "kiwi | melon"]
#   ]

You probably know that select can be used to filter out the correct elements, but how does the condition look like?

Let's take a matching pair:

a = 'kiwi | melon'
b = 'melon | apple'

We can split those by ' | ' to get the parts:

a.split(' | ') #=> ["kiwi", "melon"]
b.split(' | ') #=> ["melon", "apple"]

It's a match if a's last word matches b's first word:

a.split(' | ').last == b.split(' | ').first
#=> true

To check this for each consecutive pair of strings in an array, we can use each_cons:

['kiwi | melon', 'melon | apple', 'apple | orange'].each_cons(2) do |a, b|
  p a.split(' | ').last == b.split(' | ').first
end

It first passes 'kiwi | melon' and 'melon | apple' to the block and then 'melon | apple' and 'apple | orange'.

For this array, the output is:

true
true

To determine if the block returns true for all pairs, we can append all? to each_cons:

['kiwi | melon', 'melon | apple', 'apple | orange'].each_cons(2).all? do |a, b|
  a.split(' | ').last == b.split(' | ').first
end

And this is exactly, what we can pass to select:

a.permutation(3).select do |sub_array|
  sub_array.each_cons(2).all? do |a, b|
    a.split(' | ').last == b.split(' | ').first
  end
end
#=> [
#     ["kiwi | melon", "melon | apple", "apple | orange"],
#     ["pineapple | kiwi", "kiwi | melon", "melon | apple"]
#   ]

Note that this still creates a huge temporary array of all permutations and it splits the strings for each comparison, so you might want to look for a more optimized solution. But this should get you started.


问:
Deleting certain rows without a loop
I have a dataframe with car repair data. It also tells me if a car broke down (and got repaired). I would like to get rid of all rows with repair events after the car broke down.

```<code>Car <- c('A','A','B')
Damage <-c("Wheels","Motor","Motor")
date <-c('01-01-2015','01-01-2016','01-01-2016')
Broke_down <-c(1,0,1)

df <- as.data.frame(cbind(Car,date,Damage,Broke_down))
</code>```

Basically, I want to remove all lines that occur for a car after the dummy was 1.

So in this case the output would have to be:

```<code>"Car"        "date"          "Damage"     "Broke_down"
 A           01-01-2015       Wheels         1
 B           01-01-2016       Motor          1
</code>```

Best,
Felix

答:
Based on the update in OP's post

```<code>library(data.table)
setDT(df)[, .SD[cummin(Broke_down) > 0], Car]
#    Car       date Damage Broke_down
#1:   A 01-01-2015 Wheels          1
#2:   B 01-01-2016  Motor          1
</code>```

Or with ave from base R

```<code>df[with(df, ave(Broke_down, Car, FUN = cummin) > 0),]
#  Car       date Damage Broke_down
#1   A 01-01-2015 Wheels          1
#3   B 01-01-2016  Motor          1
</code>```

Title: Deleting certain rows without a loop

Body:
I have a dataframe with car repair data. It also tells me if a car broke down (and got repaired). I would like to get rid of all rows with repair events after the car broke down.

Car <- c('A','A','B')
Damage <-c("Wheels","Motor","Motor")
date <-c('01-01-2015','01-01-2016','01-01-2016')
Broke_down <-c(1,0,1)

df <- as.data.frame(cbind(Car,date,Damage,Broke_down))

Basically, I want to remove all lines that occur for a car after the dummy was 1.

So in this case the output would have to be:

"Car"        "date"          "Damage"     "Broke_down"
 A           01-01-2015       Wheels         1
 B           01-01-2016       Motor          1

Best,
Felix

Body:
Based on the update in OP's post

library(data.table)
setDT(df)[, .SD[cummin(Broke_down) > 0], Car]
#    Car       date Damage Broke_down
#1:   A 01-01-2015 Wheels          1
#2:   B 01-01-2016  Motor          1

Or with ave from base R

df[with(df, ave(Broke_down, Car, FUN = cummin) > 0),]
#  Car       date Damage Broke_down
#1   A 01-01-2015 Wheels          1
#3   B 01-01-2016  Motor          1


问:
How to detect key press event and key hold down event without using pygame
I am currently looking for a library that is able to detect/monitor the keyboard.
My intention is to detect when a key is being held down and while it occurs something should happen.

Most SO posts suggest to use pygame, but i find it a bit too much, to involve a library such as that for this simple task. i've also tried with pynput, which resulted only detecting one press rather than a stream of presses.

any suggestions on how i can make this while loop detect a key is being pressed / held down...

My attempt with while loop:

```<code>from pynput import keyboard

def on_press(key):
    while key == keyboard.Key.cmd_l:
        try:
            print('- Started recording -'.format(key))
        except IOError:
            print "Error"
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
</code>```

The while solution make it stuck in the while loop, making it impossible to get out of it.

答:
One of the simplest way I found is to use pynput module.can be found here with nice examples as well

```<code>from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False
</code>```

Collect events until released

```<code>with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()
</code>```

above is the example worked out for me and to install, go

```<code>sudo pip install pynput (pip3 if python3.*)
</code>```

Body:
I am currently looking for a library that is able to detect/monitor the keyboard.
My intention is to detect when a key is being held down and while it occurs something should happen.

Most SO posts suggest to use pygame, but i find it a bit too much, to involve a library such as that for this simple task. i've also tried with pynput, which resulted only detecting one press rather than a stream of presses.

any suggestions on how i can make this while loop detect a key is being pressed / held down...

My attempt with while loop:

from pynput import keyboard

def on_press(key):
    while key == keyboard.Key.cmd_l:
        try:
            print('- Started recording -'.format(key))
        except IOError:
            print "Error"
    else:
        print('incorrect character {0}, press cmd_l'.format(key))

def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.cmd_l:
        print('{0} stop'.format(key))
        keyboard.Listener.stop
        return False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

The while solution make it stuck in the while loop, making it impossible to get out of it.

Body:
One of the simplest way I found is to use pynput module.can be found here with nice examples as well

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

Collect events until released

with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

above is the example worked out for me and to install, go

sudo pip install pynput (pip3 if python3.*)


问:
Morphia does not recognize my @ID annotated field
I have a simple POSO GroupACLTemplate which I want to persist. It is subclassed from an abstract class. I have annotated it with @Entity and also have an @Id

```<code>@Entity("aclTemplate")
@SerialVersionUID(1L)
class GroupACLTemplate(@(Id@field) id: String, groupRoleAccess: Set[GroupRoleAccess]) extends AclTemplate(id) with Serializable
</code>```

When I deploy my war, I am not seeing any collection of GroupACLTemplate. I also tried this

```<code>class GroupACLTemplate(@Id id: String, groupRoleAccess: Set[GroupRoleAccess]) extends AclTemplate(id) with Serializable
</code>```

I added a test case and tried saving an object like this

```<code>@Inject
var aclTemplateRepository: AclTemplateRepository = _
aclTemplateRepository.save(aclTemplate.head)
</code>```

The error says

```<code>NoId complained about com.java.sample.acl.GroupACLTemplate. : No field is annotated with @Id; but it is required
</code>```

Am I missing something here?

答: you should use the Id from morphia instead of the one from spring data</p>

Body:
I have a simple POSO GroupACLTemplate which I want to persist. It is subclassed from an abstract class. I have annotated it with @Entity and also have an @Id

@Entity("aclTemplate")
@SerialVersionUID(1L)
class GroupACLTemplate(@(Id@field) id: String, groupRoleAccess: Set[GroupRoleAccess]) extends AclTemplate(id) with Serializable

When I deploy my war, I am not seeing any collection of GroupACLTemplate. I also tried this

class GroupACLTemplate(@Id id: String, groupRoleAccess: Set[GroupRoleAccess]) extends AclTemplate(id) with Serializable

I added a test case and tried saving an object like this

@Inject
var aclTemplateRepository: AclTemplateRepository = _
aclTemplateRepository.save(aclTemplate.head)

The error says

NoId complained about com.java.sample.acl.GroupACLTemplate. : No field is annotated with @Id; but it is required

Am I missing something here?


问:
iOS location services in the background to occur at smaller intervals or distances
the following code is my app delegate file, that I updated for swift 3.0.2

```<code>import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var locationManager: CLLocationManager?
var significatLocationManager : CLLocationManager?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if(UIApplication.shared.backgroundRefreshStatus == UIBackgroundRefreshStatus.available){
        print("yes")
    }else{
        print("no")
    }

    if launchOptions != nil{

        let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary

        if remoteNotif != nil {
            self.significatLocationManager = CLLocationManager()
            self.significatLocationManager?.delegate = self
            self.significatLocationManager?.requestAlwaysAuthorization()
            if #available(iOS 9.0, *) {
                self.significatLocationManager!.allowsBackgroundLocationUpdates = true
            }
            self.significatLocationManager?.startMonitoringSignificantLocationChanges()

        }else{

            self.locationManager           = CLLocationManager()
            self.locationManager?.delegate = self
            self.locationManager?.requestAlwaysAuthorization()
            if #available(iOS 9.0, *) {
                self.locationManager!.allowsBackgroundLocationUpdates = true
            }

            self.locationManager?.startMonitoringSignificantLocationChanges()
        }

    }else{

        self.locationManager           = CLLocationManager()
        self.locationManager?.delegate = self
        self.locationManager?.requestAlwaysAuthorization()
        if #available(iOS 9.0, *) {
            self.locationManager!.allowsBackgroundLocationUpdates = true
        }

        self.locationManager?.startMonitoringSignificantLocationChanges()

    }

    return true
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){

    //let locationArray = locations as NSArray
    //let locationObj = locationArray.lastObject as! CLLocation
    //let coord = locationObj.coordinate

    let currentLocation = locations.last!
    //print("Current location: \(currentLocation)")
    print("delegate longitude: \(currentLocation.coordinate.longitude)")
    print("delegate latitude: \(currentLocation.coordinate.latitude)")

    let t_longtitude = String(currentLocation.coordinate.longitude)
    let t_latitude = String(currentLocation.coordinate.latitude)
    let longtitude:Double = currentLocation.coordinate.longitude as Double
    let latitude:Double = currentLocation.coordinate.latitude as Double
    let svd_longtitude:Double = (UserDefaults.standard.object(forKey: "longtitude") as? Double)!
    let svd_latitude:Double = (UserDefaults.standard.object(forKey: "latitude") as? Double)!
    let coordinate1 = CLLocation(latitude: latitude, longitude: longtitude)
    let coordinate2 = CLLocation(latitude: svd_latitude, longitude: svd_longtitude)
    let distanceInMeters = coordinate1.distance(from: coordinate2) // result is in meters
    print("distanceInMeters: \(distanceInMeters)")
    UserDefaults.standard.set(latitude, forKey: "latitude")
    UserDefaults.standard.set(longtitude, forKey: "longtitude")
    UserDefaults.standard.synchronize()
    let device_id = UIDevice.current.identifierForVendor!.uuidString
    let status = update_device(longtitude: t_longtitude, latitude: t_latitude, device_id: device_id)
    print("status: \(status)")
}

func applicationDidEnterBackground(_ application: UIApplication) {

    if self.significatLocationManager != nil {

        self.significatLocationManager?.startMonitoringSignificantLocationChanges()
    }else{

        self.locationManager?.startMonitoringSignificantLocationChanges()
    }

}

func update_device(longtitude: String, latitude:String, device_id:String) -> Int {

    print("update device")

    let deviceID = UIDevice.current.identifierForVendor!.uuidString
    var status:Int = 0

    var request = URLRequest(url: URL(string: "https://someurl")!)

    request.httpMethod = "POST"

    let postString = "device_id=\(deviceID)&longtitude=\(longtitude)&latitude=\(latitude)"

    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString:String = (String(data: data, encoding: .utf8))!
        print("responseString = \(String(describing: responseString))")

        let dict = self.convertToDictionary(text: responseString)

        //UserDefaults.standard.set(dict, forKey: "myUserDetails")
        //UserDefaults.standard.synchronize()
        //self.activityIndicator.stopAnimating()

        //let status:Int = dict?["status"] as! Int
        print("status: \(status)")
        status = dict?["status"] as! Int

    }

    task.resume()
    return status

}

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
       return nil
   }

  }
</code>```

I have asked for allow always, updated info.plist with

```<code><key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to your location</string>
<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>
</code>```

The code works and my db is getting filled, but when app is in the background didUpdateLocations is triggered to far apart from location to location. What can I do to make app call didUpdateLocations when change between former location and new location is less then 200 meters

thanks

答:
You can set location for 100 meteres like this, it will update you if location is changed to 100 meteres from current location</p>

```<code>_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
</code>```

Body:
the following code is my app delegate file, that I updated for swift 3.0.2

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var locationManager: CLLocationManager?
var significatLocationManager : CLLocationManager?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if(UIApplication.shared.backgroundRefreshStatus == UIBackgroundRefreshStatus.available){
        print("yes")
    }else{
        print("no")
    }

    if launchOptions != nil{

        let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary

        if remoteNotif != nil {
            self.significatLocationManager = CLLocationManager()
            self.significatLocationManager?.delegate = self
            self.significatLocationManager?.requestAlwaysAuthorization()
            if #available(iOS 9.0, *) {
                self.significatLocationManager!.allowsBackgroundLocationUpdates = true
            }
            self.significatLocationManager?.startMonitoringSignificantLocationChanges()

        }else{

            self.locationManager           = CLLocationManager()
            self.locationManager?.delegate = self
            self.locationManager?.requestAlwaysAuthorization()
            if #available(iOS 9.0, *) {
                self.locationManager!.allowsBackgroundLocationUpdates = true
            }

            self.locationManager?.startMonitoringSignificantLocationChanges()
        }

    }else{

        self.locationManager           = CLLocationManager()
        self.locationManager?.delegate = self
        self.locationManager?.requestAlwaysAuthorization()
        if #available(iOS 9.0, *) {
            self.locationManager!.allowsBackgroundLocationUpdates = true
        }

        self.locationManager?.startMonitoringSignificantLocationChanges()

    }

    return true
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){

    //let locationArray = locations as NSArray
    //let locationObj = locationArray.lastObject as! CLLocation
    //let coord = locationObj.coordinate

    let currentLocation = locations.last!
    //print("Current location: \(currentLocation)")
    print("delegate longitude: \(currentLocation.coordinate.longitude)")
    print("delegate latitude: \(currentLocation.coordinate.latitude)")

    let t_longtitude = String(currentLocation.coordinate.longitude)
    let t_latitude = String(currentLocation.coordinate.latitude)
    let longtitude:Double = currentLocation.coordinate.longitude as Double
    let latitude:Double = currentLocation.coordinate.latitude as Double
    let svd_longtitude:Double = (UserDefaults.standard.object(forKey: "longtitude") as? Double)!
    let svd_latitude:Double = (UserDefaults.standard.object(forKey: "latitude") as? Double)!
    let coordinate1 = CLLocation(latitude: latitude, longitude: longtitude)
    let coordinate2 = CLLocation(latitude: svd_latitude, longitude: svd_longtitude)
    let distanceInMeters = coordinate1.distance(from: coordinate2) // result is in meters
    print("distanceInMeters: \(distanceInMeters)")
    UserDefaults.standard.set(latitude, forKey: "latitude")
    UserDefaults.standard.set(longtitude, forKey: "longtitude")
    UserDefaults.standard.synchronize()
    let device_id = UIDevice.current.identifierForVendor!.uuidString
    let status = update_device(longtitude: t_longtitude, latitude: t_latitude, device_id: device_id)
    print("status: \(status)")
}

func applicationDidEnterBackground(_ application: UIApplication) {

    if self.significatLocationManager != nil {

        self.significatLocationManager?.startMonitoringSignificantLocationChanges()
    }else{

        self.locationManager?.startMonitoringSignificantLocationChanges()
    }

}

func update_device(longtitude: String, latitude:String, device_id:String) -> Int {

    print("update device")

    let deviceID = UIDevice.current.identifierForVendor!.uuidString
    var status:Int = 0

    var request = URLRequest(url: URL(string: "https://someurl")!)

    request.httpMethod = "POST"

    let postString = "device_id=\(deviceID)&longtitude=\(longtitude)&latitude=\(latitude)"

    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString:String = (String(data: data, encoding: .utf8))!
        print("responseString = \(String(describing: responseString))")

        let dict = self.convertToDictionary(text: responseString)

        //UserDefaults.standard.set(dict, forKey: "myUserDetails")
        //UserDefaults.standard.synchronize()
        //self.activityIndicator.stopAnimating()

        //let status:Int = dict?["status"] as! Int
        print("status: \(status)")
        status = dict?["status"] as! Int

    }

    task.resume()
    return status

}

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
       return nil
   }

  }

I have asked for allow always, updated info.plist with

<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to your location</string>
<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

The code works and my db is getting filled, but when app is in the background didUpdateLocations is triggered to far apart from location to location. What can I do to make app call didUpdateLocations when change between former location and new location is less then 200 meters

thanks

Body:
You can set location for 100 meteres like this, it will update you if location is changed to 100 meteres from current location

_locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;


问:
Presenting a UIViewController with background transparent in swift 3.0
I am presenting a viewController with transparent background. But the components on that viewController is invisible when it is presented. A blank viewController is seen.I have given alpha value and black background color.
This is my code when  i call the transparent viewController

```<code>if indexPath.row==0
{
   let modalViewController = PopUpViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    present(modalViewController, animated: true, completion: nil)
 }
</code>```

But there is a orange color UIView present on this Controller which is invisible Thanks in advance

答:
You just have to present your second Viewcontroller, which has a transparent background, modally. with the following config:

and that's the result :

for those who may not familiar with Opacity: in the situation like this, for transparency,  it's better to use Opacity instead of Alpha

Body:
I am presenting a viewController with transparent background. But the components on that viewController is invisible when it is presented. A blank viewController is seen.I have given alpha value and black background color.
This is my code when  i call the transparent viewController

if indexPath.row==0
{
   let modalViewController = PopUpViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    present(modalViewController, animated: true, completion: nil)
 }

But there is a orange color UIView present on this Controller which is invisible Thanks in advance


问:
Encrypting emails generated by ASP.NET
I'm working on a UK NHS project whereby confidential information needs to be sent via email to a known number of select users using Microsoft Outlook. It is our intention to manually install a client certificate on these machines only, and we have a server certificate loaded onto the server by the clients ISP

However I can only seem to find 3rd party solutions using mainly COM dlls to send encrypted mail (e.g. http://www.aspencrypt.com/) and the ISP won't allow 3rd party software on the servers.

Is it Is it possible to encrypt outgoing SMTP Generated emails using the System.Net.Main Namespace (or similar) using our server certificate?

答: You can use Exchange Web Services to send mail using NHS.net mail. The DOH approves using NHS.net for sending confidential patient data within the nhs.net system.</p>

Title: Encrypting emails generated by ASP.NET


问:
How to add the search bar to mobile menu in wordpress?
I've added this code to my functions.php file:

```<code>function wpgood_nav_search( $items, $args ) {
$items .= '<li>' . get_search_form( false ) . '</li>';
return $items;
}
add_filter( 'wp_nav_menu_items','wpgood_nav_search', 10, 2 );
</code>```

I've found it here:
adding search bar to the nav menu in wordpress

The problem: this code adds the search bar to desktop and mobile menus, but I need to add the search bar only to my mobile menu, because the desktop version of my site already has a search widget in the left sidebar.

How can I do this? Please, help me. Thanks!

Initializiation of my menus in functions.php :

```<code>// Initialize navigation menus
register_nav_menus(
    array(
        'primary-menu' => esc_html__( 'Primary Menu', 'bento' ),
        'footer-menu' => esc_html__( 'Footer Menu', 'bento' ),
    )
);
</code>```

Thank you so much for your help! Finally I have decided to use my initial code and edit the searchbar's position and style with css, because I am not so good in coding:)

答:
Use the javascript code for adding the search box for mobile menu

```<code>$("ul.primary-mobile-menu').append('
// your html code to append
<li><form role="search" method="get" id="searchform" class="search-form" action="https://bookyspace.com/"><div class="search-form-wrap"> <input type="text" value="" name="s" id="s" class="search-form-input" placeholder="Знайти.."> <input type="submit" id="searchsubmit" class="button submit-button" value=""></div></form></li>
');
</code>```

Thanks

Body:
I've added this code to my functions.php file:

function wpgood_nav_search( $items, $args ) {
$items .= '
' . get_search_form( false ) . '
';
return $items;
}
add_filter( 'wp_nav_menu_items','wpgood_nav_search', 10, 2 );

I've found it here:
adding search bar to the nav menu in wordpress

The problem: this code adds the search bar to desktop and mobile menus, but I need to add the search bar only to my mobile menu, because the desktop version of my site already has a search widget in the left sidebar.

How can I do this? Please, help me. Thanks!

Initializiation of my menus in functions.php :

// Initialize navigation menus
register_nav_menus(
    array(
        'primary-menu' => esc_html__( 'Primary Menu', 'bento' ),
        'footer-menu' => esc_html__( 'Footer Menu', 'bento' ),
    )
);

Thank you so much for your help! Finally I have decided to use my initial code and edit the searchbar's position and style with css, because I am not so good in coding:)

Body:
Use the javascript code for adding the search box for mobile menu

$("ul.primary-mobile-menu').append('
// your html code to append
<li><form role="search" method="get" id="searchform" class="search-form" action="https://bookyspace.com/"><div class="search-form-wrap"> <input type="text" value="" name="s" id="s" class="search-form-input" placeholder="Знайти.."> <input type="submit" id="searchsubmit" class="button submit-button" value=""></div></form></li>
');

Thanks


问:
How to assign very large numbers to variable in java?
I'm getting "integer number too large: 1000000000001" for the following code line.  How do I make it so that maxValue can hold 1 quadrillion or 1 trillion?</p>

```<code>long maxValue = 1000000000001;      //1,000,000,000,001
</code>```

答:
This answer is complete.

Java Language Specification:

An integer literal is of type long if it is suffixed with an ASCII
  letter L or l (ell); otherwise it is of type int (§4.2.1).

Body:
I'm getting "integer number too large: 1000000000001" for the following code line.  How do I make it so that maxValue can hold 1 quadrillion or 1 trillion?

long maxValue = 1000000000001;      //1,000,000,000,001


问:
part of the store relies on some other part
As a scenario, the user can click a button to create a list of timestamps that shows the corresponding times when the clicks are made. User can also click on an item on the list to remove an item.

In terms of the store, there's a counter state that keeps track of how many times the button has been clicked, and then there's another state that keeps track of a list of timestamps. And each item on list state has an id field that derive from the counter state. So one part of the store depends on another part.

As an attempt, I dispatch one action, and both reducers handle the same action, and it works fine, but only that it's not DRY. Before dispatching, I have to add 1 to the counter state in order to get the new id which I use as the action payload, after dispatching, I add 1 to the counter state again to return the new counter state. That's repeating myself.

What's the general standard way of handling a problem of this nature?

答:
The general simple way is to use thunks. You need to setup a middleware, check out the docs:
https://github.com/gaearon/redux-thunk

This allows you to dispatch a function instead of a simple action. Within that function, you can access state and dispatch as many times as you want.

In your scenario, you would first increment the counter, then retrieve the length to get your new id, and then dispatch another action to create a timestamp.

Some imaginary code for your action creators:

```<code>// basic action creators to be handled in your reducers
function incrementCounter(){
   return { type: 'INCREMENT'}
}
function createTimestamp(id){
   return { type: 'CREATE_TS', id }
}
// this is the thunk
function incrementAndTimestamp(){
   return (dispatch, getState) => {
     // increment the counter
     dispatch(incrementCounter())
     // generate an "id" from the resulting state
     const newId = getState().counter.length
     // and use that id to further update your state
     dispatch(createTimestamp(newId))
   }
}
</code>```

You will need to handle those 2 different actions in your reducers and you have now two separate pieces of code. The thunk is the glue that dispatches, gets the data from one part, and uses it to affect the other part.

Body:
The general simple way is to use thunks. You need to setup a middleware, check out the docs:
https://github.com/gaearon/redux-thunk

This allows you to dispatch a function instead of a simple action. Within that function, you can access state and dispatch as many times as you want.

In your scenario, you would first increment the counter, then retrieve the length to get your new id, and then dispatch another action to create a timestamp.

Some imaginary code for your action creators:

// basic action creators to be handled in your reducers
function incrementCounter(){
   return { type: 'INCREMENT'}
}
function createTimestamp(id){
   return { type: 'CREATE_TS', id }
}
// this is the thunk
function incrementAndTimestamp(){
   return (dispatch, getState) => {
     // increment the counter
     dispatch(incrementCounter())
     // generate an "id" from the resulting state
     const newId = getState().counter.length
     // and use that id to further update your state
     dispatch(createTimestamp(newId))
   }
}

You will need to handle those 2 different actions in your reducers and you have now two separate pieces of code. The thunk is the glue that dispatches, gets the data from one part, and uses it to affect the other part.


问:
Recover current value in checkBox during gridView Editing - WebForm C#
I have a simple checkBox in Editable gridView :

```<code><asp:TemplateField HeaderText="Editable">
  <ItemTemplate>
      <asp:Label runat="server" Text="<%# Item.IsEditable %>" />
  </ItemTemplate>
  <EditItemTemplate>
      <asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
  </EditItemTemplate>
</asp:TemplateField>
</code>```

When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist

GridView

I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.

```<code>public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
 try
   {
    if (ModelState.IsValid)
      {
       CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
          if (item.IsEditable)
              chbEdit.Checked = true;

        new TypeService().Update(new Type
        {
          IsEditable = item.IsEditable,
        });
        this.GridView.DataBind();
      }
    }
    catch
    {
      throw;
    }
}
</code>```

It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.

```<code>SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"
</code>```

Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)

Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)

Evy

答:
```<code>CheckBox chbx = GridView1.HeaderRow.FindControl("CheckBoxEditable") as CheckBox;
  if (chbx != null && chbx.Checked)
{
  //code here
}
else
{
  //else condtion
}
</code>```

hope this helps

Body:
I have a simple checkBox in Editable gridView :

<asp:TemplateField HeaderText="Editable">
  <ItemTemplate>
      <asp:Label runat="server" Text="<%# Item.IsEditable %>" />
  </ItemTemplate>
  <EditItemTemplate>
      <asp:CheckBox ID="CheckBoxEditable " runat="server" Text="Editable"></asp:CheckBox>
  </EditItemTemplate>
</asp:TemplateField>

When I click on edit button in the row, I would like that checkBox is already checked if value is true. (IsEditable is a boolean)
Text Field is easy because I have a BindItem on Text property in EditItemTemplate. But it's not the same for checkBox or dropdownlist

GridView

I use a UpdateItem Method to update my data in database. I tried a small condition to check my checkBox but it does'nt work.

public void GridViewRisquesAggravants_UpdateItem(IndexViewModel item)
{
 try
   {
    if (ModelState.IsValid)
      {
       CheckBox chbEdit = (CheckBox)GridView.Rows[this.GridView.EditIndex].FindControl("CheckBoxEditable")
          if (item.IsEditable)
              chbEdit.Checked = true;

        new TypeService().Update(new Type
        {
          IsEditable = item.IsEditable,
        });
        this.GridView.DataBind();
      }
    }
    catch
    {
      throw;
    }
}

It makes sense because I am not in the right function to declare this. But I just have 3 methods in my webform.

SelectMethod="GridView_GetData"
UpdateMethod="GridView_UpdateItem"
DeleteMethod="GridView_DeleteItem"

Where can I do this?
(And I have the same problem with datas on dropdownList. I don't know where I recover current value during editing)

Thanks in advance
(Sorry I am beginner about webforms and my english is not perfect)

Evy

Body:
CheckBox chbx = GridView1.HeaderRow.FindControl("CheckBoxEditable") as CheckBox;
  if (chbx != null && chbx.Checked)
{
  //code here
}
else
{
  //else condtion
}

hope this helps


问:
Remove focus from dynamically created button
I have added a button to the DevExpress extra bar like below.

```<code>    Dim bbiBtn As New DevExpress.XtraBars.BarButtonItem
    bbiBtn.Caption = "Delete"
    bbiBtn.Name = "bbiDelete
    bbiBtn.Tag = "Delete"
    bbiBtn.ButtonStyle = BarButtonStyle.Check
    barMain.AddItem(bbiBtn) 'barMain is  DevExpress extra bar
</code>```

Now when I click the button and task inside the click event is performed but the button is still focused. I want this to be removed.
I tried making other fields like a label to be focused. I also loop through all item inside the bar and reset it and refresh like below.

```<code> For Each btn As DevExpress.XtraBars.BarButtonItem In barMain.Manager.Items
      If btn.Name = "bbiDelete" Then
        btn.Reset()
        btn.Refresh()
      End If
    Next
</code>```

But none of this worked. Could you please help me on this.

答:
Does this one fix your problem?

ButtonName.focus()

If not use this.

ButtonName.Select()

Add this code if after you created your button.

By this code you can set where you want to focus your button. Set focus on any type of button not the one that you dynamically created.

Body:
I have added a button to the DevExpress extra bar like below.

    Dim bbiBtn As New DevExpress.XtraBars.BarButtonItem
    bbiBtn.Caption = "Delete"
    bbiBtn.Name = "bbiDelete
    bbiBtn.Tag = "Delete"
    bbiBtn.ButtonStyle = BarButtonStyle.Check
    barMain.AddItem(bbiBtn) 'barMain is  DevExpress extra bar

Now when I click the button and task inside the click event is performed but the button is still focused. I want this to be removed.
I tried making other fields like a label to be focused. I also loop through all item inside the bar and reset it and refresh like below.

 For Each btn As DevExpress.XtraBars.BarButtonItem In barMain.Manager.Items
      If btn.Name = "bbiDelete" Then
        btn.Reset()
        btn.Refresh()
      End If
    Next

But none of this worked. Could you please help me on this.


问:
Rails 3: Using a gem as my main app
I want to use the code of a gem as my main application code instead of just installing it with "bundle install".

How can I create an entire rails app based on a gem and using that gem as my app?

Thank you.

答: You are looking for Rails Engines instead I believe. If not, then can you explain your problem further?</p>

Title: Rails 3: Using a gem as my main app


问:
No need to cast the result of findViewById?
Recently I found that AndroidStudio reminds me to remove some class cast. I remember that in the old time, we have to cast the result of findViewById, but now it's not necessary.

The result of findViewById is still View, so i want to know why we don't need to cast the class?

I can't find any documents mentioned that, can anyone find any document?

答:
Starting with API 26, findViewById uses inference for its return type, so you no longer have to cast.

Old definition:

View findViewById(int id)
```

<p>New definition:</p>

<pre class="lang-java prettyprint-override"><code><T extends View> T findViewById(int id)
</code>```

So if your compileSdk is at least 26, it means that you can make use of this :)

ContentLicense: CC BY-SA 4.0

Body:
Starting with API 26, findViewById uses inference for its return type, so you no longer have to cast.

Old definition:

View findViewById(int id)

New definition:

<T extends View> T findViewById(int id)

So if your compileSdk is at least 26, it means that you can make use of this :)


问:
Do I need to add thread locking to simple variables?
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

```<code>enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}
</code>```

答:
For the purpose of simulating your issue, I traced the following code snippet (iOS App environment):

```<code>import UIKit

func delay (
    _ seconds: Double,
    queue: DispatchQueue = DispatchQueue.main,
    after: @escaping ()->()) {

    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

class ViewController: UIViewController {
    var myValue = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        addOneThousand()
        addOneThousand()
        addOneThousand()

        // calling this is just for logging the value after a delay
        // just for making sure that all threads execution is completed...
        delay(3.0) {
            print(self.myValue)
        }
    }

    func addOneThousand() {
        DispatchQueue(label: "com.myapp.myqueue").async {
            for _ in 0...999 {
                self.myValue += 1
            }

            print(self.myValue)
        }
    }
}
</code>```

For the first look, the expectation would be: the value of myValue should be 3000 since addOneThousand() has been called three times, but after running the app 10 times -on my machine (simulator)- sequentially, the output was:

1582
1582
1582
1582

3000
3000
3000
3000

2523
2523
2523
2523

2591
2591
2591
2591

1689
1689
1689
1689

1556
1556
1556
1556

1991
1991
1991
1991

1914
1914
1914
1914

2416
2416
2416
2416

1889
1889
1889
1889

The most important thing that the fourth value for each result (the output after waiting for the delay) is most of the times is unexpected (not 3000). If I am not mistaking, I assume that what we are facing here is a race condition.

An appropriate solution for such a case is to let the execution of the threads to be serialized; after editing addOneThousand() (sync instead of async. You might want to check this answer):

```<code>func addOneThousand() {
    DispatchQueue(label: "com.myapp.myqueue").sync {
        for _ in 0...999 {
            self.myValue += 1
        }

        print(self.myValue)
    }
}
</code>```

the output for 10 sequential runs was:

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

That represents the expected result.

I hope it helpful.

Body:
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}

Body:
For the purpose of simulating your issue, I traced the following code snippet (iOS App environment):

import UIKit

func delay (
    _ seconds: Double,
    queue: DispatchQueue = DispatchQueue.main,
    after: @escaping ()->()) {

    let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
    queue.asyncAfter(deadline: time, execute: after)
}

class ViewController: UIViewController {
    var myValue = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        addOneThousand()
        addOneThousand()
        addOneThousand()

        // calling this is just for logging the value after a delay
        // just for making sure that all threads execution is completed...
        delay(3.0) {
            print(self.myValue)
        }
    }

    func addOneThousand() {
        DispatchQueue(label: "com.myapp.myqueue").async {
            for _ in 0...999 {
                self.myValue += 1
            }

            print(self.myValue)
        }
    }
}

For the first look, the expectation would be: the value of myValue should be 3000 since addOneThousand() has been called three times, but after running the app 10 times -on my machine (simulator)- sequentially, the output was:

1582
1582
1582
1582

3000
3000
3000
3000

2523
2523
2523
2523

2591
2591
2591
2591

1689
1689
1689
1689

1556
1556
1556
1556

1991
1991
1991
1991

1914
1914
1914
1914

2416
2416
2416
2416

1889
1889
1889
1889

The most important thing that the fourth value for each result (the output after waiting for the delay) is most of the times is unexpected (not 3000). If I am not mistaking, I assume that what we are facing here is a race condition.

An appropriate solution for such a case is to let the execution of the threads to be serialized; after editing addOneThousand() (sync instead of async. You might want to check this answer):

func addOneThousand() {
    DispatchQueue(label: "com.myapp.myqueue").sync {
        for _ in 0...999 {
            self.myValue += 1
        }

        print(self.myValue)
    }
}

the output for 10 sequential runs was:

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

1000
2000
3000
3000

That represents the expected result.

I hope it helpful.


问:
Haxe - How do you implement async await for Flash Targets
I currently have this code:

```<code>package sage.sys;

import com.dongxiguo.continuation.Async;

#if flash
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
#end

class FileSystem implements Async
{
    public static function fetchText(url:String, callback:String->Void) : Void
    {
        var urlLoader = new URLLoader();
        var onLoaderError = function(e : Event) : Void {
        callback(e.type);
    };

    urlLoader.addEventListener(Event.COMPLETE, function(_) : Void {
        callback(Std.string(urlLoader.data));
    });

    urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError);
    urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoaderError);

    try {
        urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
        urlLoader.load(new URLRequest(url));
    }
    catch (e : Dynamic)
    {
        callback(Std.string(e));
    }
}

@async
public static function fetch(url:String):String
{
    var result = @await fetchText(url);
    return result;
}
}
</code>```

When I try to run it, it doesn't wait at the await, and returns from the function. How can I make the @await actually enforce itself and and stop running outside the function till the value is resolved from the async call?

Lib used: https://github.com/proletariatgames/haxe-continuation

答:
You can't really. The function, in which you call fetchText() will never "wait" in that sense.

However according to the documentation of "haxe-continuation" it will put everything after your @await FileSystem.fetchText() expression into a new function, which will be passed as the callback parameter of fetchText(). So in code it kind of "looks" like it is waiting.

According to the documentation you have to make sure that you put @async in front of the function which uses fetchText(). According to that something like this should work (untested):

```<code>@async function someFunction(): Void {
  var result1 = @await FileSystem.fetchText(someUrl);
  var result2 = @await FileSystem.fetchText(anotherUrl);
  trace(result1);
  trace(result2);
}
</code>```

The 2 traces at the end of the function should happen after result1 and result2 are fetched, even though someFunction() actually returned before the traces already.

It might be helpful to see your code which calls fetchText().

Body:
I currently have this code:

package sage.sys;

import com.dongxiguo.continuation.Async;

#if flash
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
#end

class FileSystem implements Async
{
    public static function fetchText(url:String, callback:String->Void) : Void
    {
        var urlLoader = new URLLoader();
        var onLoaderError = function(e : Event) : Void {
        callback(e.type);
    };

    urlLoader.addEventListener(Event.COMPLETE, function(_) : Void {
        callback(Std.string(urlLoader.data));
    });

    urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError);
    urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoaderError);

    try {
        urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
        urlLoader.load(new URLRequest(url));
    }
    catch (e : Dynamic)
    {
        callback(Std.string(e));
    }
}

@async
public static function fetch(url:String):String
{
    var result = @await fetchText(url);
    return result;
}
}

When I try to run it, it doesn't wait at the await, and returns from the function. How can I make the @await actually enforce itself and and stop running outside the function till the value is resolved from the async call?

Lib used: https://github.com/proletariatgames/haxe-continuation

Body:
You can't really. The function, in which you call fetchText() will never "wait" in that sense.

However according to the documentation of "haxe-continuation" it will put everything after your @await FileSystem.fetchText() expression into a new function, which will be passed as the callback parameter of fetchText(). So in code it kind of "looks" like it is waiting.

According to the documentation you have to make sure that you put @async in front of the function which uses fetchText(). According to that something like this should work (untested):

@async function someFunction(): Void {
  var result1 = @await FileSystem.fetchText(someUrl);
  var result2 = @await FileSystem.fetchText(anotherUrl);
  trace(result1);
  trace(result2);
}

The 2 traces at the end of the function should happen after result1 and result2 are fetched, even though someFunction() actually returned before the traces already.

It might be helpful to see your code which calls fetchText().


问:
Variation of indices of an array or matrix
If I use this syntax:

```<code>mX=[1:5];
A=rand(5,1);
C(mX)=sum(A(1:mX));
</code>```

Why doesn't the content of C(mX) vary with varying mX?

Instead of doing

```<code>C(1)=A(1)
C(2)=A(1)+A(2), etc
</code>```

it does:

```<code>C(1)=A(1)
C(2)=A(1)
C(3)=A(1), etc
</code>```

Is there any way to vary C(mX) without resorting to a loop?

答:
To answer your first question:

```<code>mX=1:5;
A=rand(5,1);
C(mX)=sum(A(1:mX));
</code>```

makes the sum over A(1:[1 2 3 4 5]), which results in A(1:1), and hence all your C(mX) values will be filled with purely the element A(1).

What you want to do is make a cumulative sum, which can be done, as @leanderMoesinger mentioned with cumsum:

```<code>A=rand(5,1);
C = cumsum(A)
C =
    0.0975
    0.3760
    0.9229
    1.8804
    2.8453
</code>```

If you want to learn more about indexing I can highly recommend the following post: Linear indexing, logical indexing, and all that

If you want not all elements of A, but e.g. up to element three you can do

```<code>mX = 1:3;
A = rand(5,1);
C = cumsum(A(mX)); calculate only to mX

mX = [1 3 5];
C = cumsum(A(mX)) % Also works if you only want elements 1 3 and 5 to appear

% If you want elements of C 1 3 and 5 use
tmp = cumsum(A);
C = tmp(mX);
</code>```

Body:
If I use this syntax:

mX=[1:5];
A=rand(5,1);
C(mX)=sum(A(1:mX));

Why doesn't the content of C(mX) vary with varying mX?

Instead of doing

C(1)=A(1)
C(2)=A(1)+A(2), etc

it does:

C(1)=A(1)
C(2)=A(1)
C(3)=A(1), etc

Is there any way to vary C(mX) without resorting to a loop?

Body:
To answer your first question:

mX=1:5;
A=rand(5,1);
C(mX)=sum(A(1:mX));

makes the sum over A(1:[1 2 3 4 5]), which results in A(1:1), and hence all your C(mX) values will be filled with purely the element A(1).

What you want to do is make a cumulative sum, which can be done, as @leanderMoesinger mentioned with cumsum:

A=rand(5,1);
C = cumsum(A)
C =
    0.0975
    0.3760
    0.9229
    1.8804
    2.8453

If you want to learn more about indexing I can highly recommend the following post: Linear indexing, logical indexing, and all that

If you want not all elements of A, but e.g. up to element three you can do

mX = 1:3;
A = rand(5,1);
C = cumsum(A(mX)); calculate only to mX

mX = [1 3 5];
C = cumsum(A(mX)) % Also works if you only want elements 1 3 and 5 to appear

% If you want elements of C 1 3 and 5 use
tmp = cumsum(A);
C = tmp(mX);


问:
How to link a .a file in C++
I'm trying to get the yaml-cpp parser working on my computer. I followed the instructions on the README, which generated the file libyaml-cpp.a with no errors or warnings. Then I copied that file into a directory, let's call it /path/to/files, where I also put b.yaml, and main.cpp, which contains the following text:

```<code>// main.cpp

int main(int argc, const char *argv[])
{
  YAML::Node config = YAML::LoadFile("b.yaml");
  return 0;
}
</code>```

This comes from the first line of the yaml-cpp tutorial. I tried compiling this while linking to the yaml-cpp library in a few different ways, all of which lead to the same compile-time error: use of undeclared identifier 'YAML'. Here are some of the things I tried:

g++ main.cpp -lyaml-cpp -L/path/to/files

g++ main.cpp libyaml-cpp.a

g++ main.cpp libyaml-cpp.a -lyaml-cpp -L/path/to/files

and so on. How do I compile this correctly or more properly debug  this process?

==EDIT==

Now my main.cpp file looks like this:

```<code>// main.cpp

#include <iostream>
#include "yaml.h"

int main(int argc, const char *argv[])
{
  YAML::Node config = YAML::LoadFile("b.yaml");
  return 0;
}
</code>```

Here's my compile command and error message:

```<code>$ g++ main.cpp -lyaml-cpp -I/Users/benlindsay/scratch/yaml-cpp/include -L/Users/benlindsay/scratch/yaml-cpp/build
main.cpp:10:3: error: use of undeclared identifier 'YAML'
  YAML::Node config = YAML::LoadFile("b.yaml");
  ^
main.cpp:10:23: error: use of undeclared identifier 'YAML'
  YAML::Node config = YAML::LoadFile("b.yaml");
                      ^
2 errors generated.
make: *** [a.out] Error 1
</code>```

/Users/benlindsay/scratch/yaml-cpp/include contains a yaml-cpp directory, which in turn contains all the .h files including yaml.h. /Users/benlindsay/scratch/yaml-cpp/build contains the lyaml-cpp.a file.

答:
Ok, I downloaded yaml-cpp and tried out, Here is a working version

```<code>#include <iostream>
#include "yaml-cpp/yaml.h" //You need to prepend the yaml-cpp

int main(int argc, const char *argv[])
{
     YAML::Node config = YAML::LoadFile("b.yaml");
     //return 0; In cpp, return 0 is not required on main, hence commented
}
</code>```

The compile using g++ -std=c++11 main.cpp -lyaml-cpp -I/Users/benlindsay/scratch/yaml-cpp/include -L/Users/benlindsay/scratch/yaml-cpp/build

Title: How to link a .a file in C++

Body:
I'm trying to get the yaml-cpp parser working on my computer. I followed the instructions on the README, which generated the file libyaml-cpp.a with no errors or warnings. Then I copied that file into a directory, let's call it /path/to/files, where I also put b.yaml, and main.cpp, which contains the following text:

// main.cpp

int main(int argc, const char *argv[])
{
  YAML::Node config = YAML::LoadFile("b.yaml");
  return 0;
}

This comes from the first line of the yaml-cpp tutorial. I tried compiling this while linking to the yaml-cpp library in a few different ways, all of which lead to the same compile-time error: use of undeclared identifier 'YAML'. Here are some of the things I tried:

g++ main.cpp -lyaml-cpp -L/path/to/files

g++ main.cpp libyaml-cpp.a

g++ main.cpp libyaml-cpp.a -lyaml-cpp -L/path/to/files

and so on. How do I compile this correctly or more properly debug  this process?

==EDIT==

Now my main.cpp file looks like this:

// main.cpp

#include <iostream>
#include "yaml.h"

int main(int argc, const char *argv[])
{
  YAML::Node config = YAML::LoadFile("b.yaml");
  return 0;
}

Here's my compile command and error message:

$ g++ main.cpp -lyaml-cpp -I/Users/benlindsay/scratch/yaml-cpp/include -L/Users/benlindsay/scratch/yaml-cpp/build
main.cpp:10:3: error: use of undeclared identifier 'YAML'
  YAML::Node config = YAML::LoadFile("b.yaml");
  ^
main.cpp:10:23: error: use of undeclared identifier 'YAML'
  YAML::Node config = YAML::LoadFile("b.yaml");
                      ^
2 errors generated.
make: *** [a.out] Error 1

/Users/benlindsay/scratch/yaml-cpp/include contains a yaml-cpp directory, which in turn contains all the .h files including yaml.h. /Users/benlindsay/scratch/yaml-cpp/build contains the lyaml-cpp.a file.

Body:
Ok, I downloaded yaml-cpp and tried out, Here is a working version

#include <iostream>
#include "yaml-cpp/yaml.h" //You need to prepend the yaml-cpp

int main(int argc, const char *argv[])
{
     YAML::Node config = YAML::LoadFile("b.yaml");
     //return 0; In cpp, return 0 is not required on main, hence commented
}

The compile using g++ -std=c++11 main.cpp -lyaml-cpp -I/Users/benlindsay/scratch/yaml-cpp/include -L/Users/benlindsay/scratch/yaml-cpp/build


问:
How to merge multiple PDFs using TCPDF?
Merge to PDF using TCPDF I write some code form merge in CakePHP.</p>

```<code>$pdf->writeHTML($html, true, false, true, false, '');

//$pdf->AddPage($html, $pvalue['ClientCaseMedicalRecord']['medical_document']);

$pdf->lastPage();
//$pdf->Output(WWW_ROOT.'files/client_case_record/example_049.pdf', 'F');

$pdf->AddPage();
$pdf->AddPage(WWW_ROOT.'files/client_case_record/example_049.pdf', 'all');
$pdf->AddPage(WWW_ROOT.$pvalue['ClientCaseMedicalRecord']['medical_document'], 'all');
// $pdf->merge('file', 'samplepdfs/TEST2.pdf');
$pdf->Output(WWW_ROOT.'files/client_case_record/example_019.pdf', 'F');
</code>```

答: Use FPDI (example) to import PDF's in your new PDF. FPDI works with TCPDF in the same way as with FPDF.</p>

Title: How to merge multiple PDFs using TCPDF?

Body:
Merge to PDF using TCPDF I write some code form merge in CakePHP.

$pdf->writeHTML($html, true, false, true, false, '');

//$pdf->AddPage($html, $pvalue['ClientCaseMedicalRecord']['medical_document']);

$pdf->lastPage();
//$pdf->Output(WWW_ROOT.'files/client_case_record/example_049.pdf', 'F');

$pdf->AddPage();
$pdf->AddPage(WWW_ROOT.'files/client_case_record/example_049.pdf', 'all');
$pdf->AddPage(WWW_ROOT.$pvalue['ClientCaseMedicalRecord']['medical_document'], 'all');
// $pdf->merge('file', 'samplepdfs/TEST2.pdf');
$pdf->Output(WWW_ROOT.'files/client_case_record/example_019.pdf', 'F');


问:
how can we show/hide div tags using value of radio buttons in jquery or javascript?
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

```

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

答:
I wrote code as per you describe in your post. May be useful to solve your problem.

$(document).ready(function() {
    $('input[type=radio][name=vehicleList]').change(function() {
        if (this.value == '1') {
            $("#FourWheeler").hide();
    $("#TwoWheeler").show();
        }
        else if (this.value == '2') {
            $("#FourWheeler").show();
            $("#TwoWheeler").hide();
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vehicleList">
 <label>
    <input type="radio" name="vehicleList" id="two" value="1" />Two Wheeler
  </label>
  <label>
    <input type="radio" name="vehicleList" id="four" value="2" />Four Wheeler
  </label>
</div>

<h5>Output : </h5>
<div id="TwoWheeler" style="display:none">
  <label>
    <input type="radio" name="TwoWheeler" value="6" />Electric
  </label>
  <label>
    <input type="radio" name="TwoWheeler" value="7" />Petrol
  </label>
</div>
<div id="FourWheeler" style="display:none">
  <label>
    <input type="radio" name="FourWheeler" value="1" />Electric
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="2" />Petrol
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="3" />Diesel
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="4" />CNG
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="5" />LPG
  </label>
</div></code>```

Body:
hi i am very new to jquery and i am working on show and hide div tags using values of radio buttons. here is my HTML.

    <input type="radio" name="vehicleList" id="two" onclick="fuelList()" value="1" />Two Wheeler

    <input type="radio" name="vehicleList" id="four" onclick="fuelList()" value="2" />Four Wheeler

    <input type="radio" name="TwoWheeler" value="6" />Electric

    <input type="radio" name="TwoWheeler" value="7" />Petrol

    <input type="radio" name="FourWheeler" value="1" />Electric

    <input type="radio" name="FourWheeler" value="2" />Petrol

    <input type="radio" name="FourWheeler" value="3" />Diesel

    <input type="radio" name="FourWheeler" value="4" />CNG

    <input type="radio" name="FourWheeler" value="5" />LPG

now i need help in writing a jquery code for showing the div tag with id = "two wheeler" when radio button value = 1 and div tag with id = "four wheeler" when radio button value = 2.

thnaks in advance.

sorry for anyone who couldnt understand my question.

Body:
I wrote code as per you describe in your post. May be useful to solve your problem.

$(document).ready(function() {
    $('input[type=radio][name=vehicleList]').change(function() {
        if (this.value == '1') {
            $("#FourWheeler").hide();
    $("#TwoWheeler").show();
        }
        else if (this.value == '2') {
            $("#FourWheeler").show();
            $("#TwoWheeler").hide();
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vehicleList">
 <label>
    <input type="radio" name="vehicleList" id="two" value="1" />Two Wheeler
  </label>
  <label>
    <input type="radio" name="vehicleList" id="four" value="2" />Four Wheeler
  </label>
</div>

<h5>Output : </h5>
<div id="TwoWheeler" style="display:none">
  <label>
    <input type="radio" name="TwoWheeler" value="6" />Electric
  </label>
  <label>
    <input type="radio" name="TwoWheeler" value="7" />Petrol
  </label>
</div>
<div id="FourWheeler" style="display:none">
  <label>
    <input type="radio" name="FourWheeler" value="1" />Electric
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="2" />Petrol
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="3" />Diesel
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="4" />CNG
  </label>
  <label>
    <input type="radio" name="FourWheeler" value="5" />LPG
  </label>
</div>