问:
How to use for loop in fortran
My professor told me something interesting during the class today.
professor said "if you use the preprocessor, you can use for loop in fortran".
but I know that fortran not support the for loop.
I think I can use it in that format,I don't know how it works.</p>

答:
The for loop is in Fortran is called the DO loop, but it is the same. You can call any loop that uses an integer (or integral) counter and counts in specific steps a for loop no matter which keyword is actually used in the language.

The do loop in Fortran IS a for loop:

```<code>    do i = 1, 10, 2
      do something with i
    end do
</code>```

can be called a for loop without any problem. The for keyword was invented after the invention of Fortran.

Some languages, like C, have more general for loops, but that does not matter here.

ContentLicense: CC BY-SA 4.0

Title: How to use for loop in fortran

Body:
The for loop is in Fortran is called the DO loop, but it is the same. You can call any loop that uses an integer (or integral) counter and counts in specific steps a for loop no matter which keyword is actually used in the language.

The do loop in Fortran IS a for loop:

    do i = 1, 10, 2
      do something with i
    end do

can be called a for loop without any problem. The for keyword was invented after the invention of Fortran.

Some languages, like C, have more general for loops, but that does not matter here.


来源: stackexchange

问:
How do I POST multiple outputs with this ajax functions?
I have a function that send one output i.e. 'OPTIONS' as json using ajax. Now I need to POST multiple say two outputs. How do I modify this function so that I could POST two valiues.
Here is my ajax function.</p>

```<code>function ADDLISITEM(form)
    {
    var options = form.txtInput.value;
    options = JSON.stringify(options);
    var url = "send_mysql.php"
    var request = null;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    request=new XMLHttpRequest();
     }
    else
    {// code for IE6, IE5
    request=new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Connection", "close");
    request.onreadystatechange = function(){
        if (request.readyState == 4) {
            if (request.status == 200) {
                //alert('POST');
        } else {
            alert(request.status); // fails here
        }
        }
    }
    request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));
    }
    </script>
</code>```

答:
Add another parameter to the request.send call like this:

```<code>var someOtherValue = JSON.stringify({actual : "data", goes : "here"});
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+') + "&someOtherValue=" + encodeURIComponent(someOtherValue).replace(/%20/g, '+'));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a function that send one output i.e. 'OPTIONS' as json using ajax. Now I need to POST multiple say two outputs. How do I modify this function so that I could POST two valiues.
Here is my ajax function.

function ADDLISITEM(form)
    {
    var options = form.txtInput.value;
    options = JSON.stringify(options);
    var url = "send_mysql.php"
    var request = null;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    request=new XMLHttpRequest();
     }
    else
    {// code for IE6, IE5
    request=new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Connection", "close");
    request.onreadystatechange = function(){
        if (request.readyState == 4) {
            if (request.status == 200) {
                //alert('POST');
        } else {
            alert(request.status); // fails here
        }
        }
    }
    request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));
    }
    </script>

Body:
Add another parameter to the request.send call like this:

var someOtherValue = JSON.stringify({actual : "data", goes : "here"});
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+') + "&someOtherValue=" + encodeURIComponent(someOtherValue).replace(/%20/g, '+'));


问:
External tester submission error (Beta App Review). Entitlements for Apple Pay
I am getting an error while submitting an app for External tester in App store. In the application, I have used Apple Pay feature.
While submitting app for External tester in Testflight at that time I am getting error

Apps that use the entitlements [com.apple.developer.in-app-payments] must have a privacy policy for [UK English]. If your app doesn’t use these entitlements, remove them from your app and upload a new binary.

I have already added privacy policy link in App store.
Unneccessary Privacy Policy For Entitlements?

答: There is a specific privacy policy URL field under "Test Information" that is required for TestFlight testing.  Make sure you have entered your privacy policy URL there for UK English.</p>

ContentLicense: CC BY-SA 3.0


问:
Node Sass couldn't find a binding for your current environment
I am having issues building an app because node-sass keeps failing with the error.

ERROR in Missing binding /Users/warren/Sites/random-docs/my-cms/node_modules/node-sass/vendor/darwin-x64-11/binding.node

  Node Sass could not find a binding for your current environment: OS X 64-bit with Node 0.10.x

I have tried running

```<code>npm rebuild node-sass
</code>```

which says

Binary is fine; exiting.

When running node -v I get v6.2.2

Which is different to what the sass error says "Node 0.10.x". I can't figure out why it is getting the wrong version. I have also tried removing the node_modules folder and running npm update or npm install, both of which did not resolve the issue. Any ideas?

答:
This usually happens because the environment has changed since running npm install.
Running npm rebuild node-sass builds the binding for the current environment.

Body:
I am having issues building an app because node-sass keeps failing with the error.

ERROR in Missing binding /Users/warren/Sites/random-docs/my-cms/node_modules/node-sass/vendor/darwin-x64-11/binding.node

  Node Sass could not find a binding for your current environment: OS X 64-bit with Node 0.10.x

I have tried running

npm rebuild node-sass

which says

Binary is fine; exiting.

When running node -v I get v6.2.2

Which is different to what the sass error says "Node 0.10.x". I can't figure out why it is getting the wrong version. I have also tried removing the node_modules folder and running npm update or npm install, both of which did not resolve the issue. Any ideas?


问:
android retrofit await method to finish outside of response
I need to run a BroadcastReceiver to make a webcall in the background and display a notification to the user via notificationmanager. However, the method is running synchronously and displaying a notification before the webcall is finished. How do i await the void method that contains the retrofit webcall?
Below is the web method i need to await.</p>

```<code>public static void getFriendList(String id, final ApiInterface api, final MainActivity activity, final boolean isUpdate)
{
    Call<List<String>> call = api.getFriendList(ServiceGenerator.API_KEY, id,"friend");
    call.enqueue(new Callback<List<String>>() {
        @Override
        public void onResponse(Call<List<String>> call, Response<List<String>> response) {
            try {
                List<String> idsList = new ArrayList<>();
                for (String idGroup : response.body()) {
                    idsList.add(idGroup);
                }

                for (String ids : idsList) {
                    getPlayerSummaries(ids, api, activity, isUpdate); // another web call
                }
            } catch(Exception ex) {
                System.out.println("TEST----------------------FAILED IN RESPONSE" + ex);
            }
        }

        @Override
        public void onFailure(Call<List<String>> call, Throwable t) {
            System.out.println("TEST----------------------FAILED IN FAILURE" + t.getMessage());
        }
    });
}
</code>```

答: False. Execute is for Synchronous calls. Anyways, I think I figured out a solution. I will use sync calls inside an async task. This way, I know when it's finished outside of the web method. </p>

Body:
I need to run a BroadcastReceiver to make a webcall in the background and display a notification to the user via notificationmanager. However, the method is running synchronously and displaying a notification before the webcall is finished. How do i await the void method that contains the retrofit webcall?
Below is the web method i need to await.

public static void getFriendList(String id, final ApiInterface api, final MainActivity activity, final boolean isUpdate)
{
    Call<List<String>> call = api.getFriendList(ServiceGenerator.API_KEY, id,"friend");
    call.enqueue(new Callback<List<String>>() {
        @Override
        public void onResponse(Call<List<String>> call, Response<List<String>> response) {
            try {
                List<String> idsList = new ArrayList<>();
                for (String idGroup : response.body()) {
                    idsList.add(idGroup);
                }

                for (String ids : idsList) {
                    getPlayerSummaries(ids, api, activity, isUpdate); // another web call
                }
            } catch(Exception ex) {
                System.out.println("TEST----------------------FAILED IN RESPONSE" + ex);
            }
        }

        @Override
        public void onFailure(Call<List<String>> call, Throwable t) {
            System.out.println("TEST----------------------FAILED IN FAILURE" + t.getMessage());
        }
    });
}


问:
How to enable visual styles without a manifest
According to the docs:

"If you want your application to use ComCtl32.dll version 6, you must add an application manifest or compiler directive to specify that version 6 should be used if it is available."

Notice the logical OR above? So what is this mysterious compiler directive?

I've got a native Win32 C++ application that is wholly contained in a single .cpp file. There are no resource files, manifest files, etc. I'd like to keep it that way, but I would also like to use visual styles.

答:
If you had kept reading, you would have found the answer:

If you are using Microsoft Visual C++ 2005 or later, you can add the following compiler directive to your source code instead of manually creating a manifest. For readability, the directive is broken into two lines here.

```<code>#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls'
version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
</code>```

Body:
If you had kept reading, you would have found the answer:

If you are using Microsoft Visual C++ 2005 or later, you can add the following compiler directive to your source code instead of manually creating a manifest. For readability, the directive is broken into two lines here.

#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls'
version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")


问:
What's the logic of unix_timestamp function convert the 2-digit format year to 4-digit format year in the Hive?
For example, the below hive script

```<code>select
from_unixtime(unix_timestamp('30-Apr-50', 'dd-MMM-yy'), 'yyyy-MM-dd') as date1,
from_unixtime(unix_timestamp('30-Apr-45', 'dd-MMM-yy'), 'yyyy-MM-dd') as date2,
from_unixtime(unix_timestamp('30-Apr-35', 'dd-MMM-yy'), 'yyyy-MM-dd') as date3;
</code>```

The result is as below

```<code>date1       date2       date3
1950-04-30  1945-04-30  2035-04-30
</code>```

What's the logic behind the unix_timestamp function that convert the 2-digit year to 4-digit year? Is there a fix threshold for the 2-digit year when converting it becomes 20**? If there is, what is the threshold? Is there kind of parameter ('Century Break' as real situation) that we can set the century according to some condition?

答:
Year:  ...

For parsing with the abbreviated year pattern ("y" or
"yy"), SimpleDateFormat must interpret the abbreviated year relative
to some century.

It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created.

For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat instance created on Jan 1, 1997, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" would be interpreted as May 4, 1964.

SimpleDateFormat

```<code>hive> select current_date;
2017-03-28

-- 20 years after today

hive> select from_unixtime(unix_timestamp('37-03-28','yy-MM-dd'));
2037-03-28 00:00:00

hive> select from_unixtime(unix_timestamp('37-03-29','yy-MM-dd'));
1937-03-29 00:00:00

-- 80 years before today

hive> select from_unixtime(unix_timestamp('37-03-29','yy-MM-dd'));
1937-03-29 00:00:00

hive> select from_unixtime(unix_timestamp('37-03-28','yy-MM-dd'));
2037-03-28 00:00:00
</code>```

Code walk-through

hive/ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFUnixTimeStamp.java

```<code>public class GenericUDFUnixTimeStamp extends GenericUDFToUnixTimeStamp {
...

public Object evaluate(DeferredObject[] arguments) throws HiveException {
    return (arguments.length == 0) ? currentTimestamp : super.evaluate(arguments);
  }
</code>```

hive/ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFToUnixTimeStamp.java

```<code>import java.text.SimpleDateFormat;
...

public class GenericUDFToUnixTimeStamp extends GenericUDF {
...
  private transient final SimpleDateFormat formatter = new SimpleDateFormat(lasPattern);
...
  public Object evaluate(DeferredObject[] arguments) throws HiveException {
...
        retValue.set(formatter.parse(textVal).getTime() / 1000);
...
  }
}
</code>```

Body:
For example, the below hive script

select
from_unixtime(unix_timestamp('30-Apr-50', 'dd-MMM-yy'), 'yyyy-MM-dd') as date1,
from_unixtime(unix_timestamp('30-Apr-45', 'dd-MMM-yy'), 'yyyy-MM-dd') as date2,
from_unixtime(unix_timestamp('30-Apr-35', 'dd-MMM-yy'), 'yyyy-MM-dd') as date3;

The result is as below

date1       date2       date3
1950-04-30  1945-04-30  2035-04-30

What's the logic behind the unix_timestamp function that convert the 2-digit year to 4-digit year? Is there a fix threshold for the 2-digit year when converting it becomes 20**? If there is, what is the threshold? Is there kind of parameter ('Century Break' as real situation) that we can set the century according to some condition?

Body:
Year:  ...

For parsing with the abbreviated year pattern ("y" or
"yy"), SimpleDateFormat must interpret the abbreviated year relative
to some century.

It does this by adjusting dates to be within 80 years before and 20 years after the time the SimpleDateFormat instance is created.

For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat instance created on Jan 1, 1997, the string "01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64" would be interpreted as May 4, 1964.

SimpleDateFormat

hive> select current_date;
2017-03-28

-- 20 years after today

hive> select from_unixtime(unix_timestamp('37-03-28','yy-MM-dd'));
2037-03-28 00:00:00

hive> select from_unixtime(unix_timestamp('37-03-29','yy-MM-dd'));
1937-03-29 00:00:00

-- 80 years before today

hive> select from_unixtime(unix_timestamp('37-03-29','yy-MM-dd'));
1937-03-29 00:00:00

hive> select from_unixtime(unix_timestamp('37-03-28','yy-MM-dd'));
2037-03-28 00:00:00

Code walk-through

hive/ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFUnixTimeStamp.java

public class GenericUDFUnixTimeStamp extends GenericUDFToUnixTimeStamp {
...

public Object evaluate(DeferredObject[] arguments) throws HiveException {
    return (arguments.length == 0) ? currentTimestamp : super.evaluate(arguments);
  }

hive/ql/src/java/org/apache/hadoop/hive/ql/udf/generic/GenericUDFToUnixTimeStamp.java

import java.text.SimpleDateFormat;
...

public class GenericUDFToUnixTimeStamp extends GenericUDF {
...
  private transient final SimpleDateFormat formatter = new SimpleDateFormat(lasPattern);
...
  public Object evaluate(DeferredObject[] arguments) throws HiveException {
...
        retValue.set(formatter.parse(textVal).getTime() / 1000);
...
  }
}


问:
Gradle Scala Plugin - how to specify zincClasspath
I am trying to use the Scala plugin with Gradle to build my project on an Ubuntu VM. This is what my build.gradle file looks like:

```<code>apply plugin: 'scala'
repositories {
     mavenCentral()
}

dependencies {
    compile 'org.scala-lang:scala-library:2.11.8'
}
</code>```

when I run gradle build from the command line, I get the following error:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
A problem was found with the configuration of task ':compileScala'.
> No value has been specified for property 'zincClasspath'.
</code>```

I have looked around for where to specify this zincClasspath property, but can't find anything.

I have tried to force the zincClasspath to use an older version of the scala library, but it doesn't seem to work.

Any help is much appreciated

Edit:

One thing to add, this exact project builds fine on my local Windows machine, but not on my Ubuntu VM....

答:
I ran into this issue again recently, adding the following to my Gradle build script seemed to fix it:</p>

```<code>ScalaCompileOptions.metaClass.daemonServer = true
ScalaCompileOptions.metaClass.fork = true
ScalaCompileOptions.metaClass.useAnt = false
ScalaCompileOptions.metaClass.useCompileDaemon = false
</code>```

Body:
I am trying to use the Scala plugin with Gradle to build my project on an Ubuntu VM. This is what my build.gradle file looks like:

apply plugin: 'scala'
repositories {
     mavenCentral()
}

dependencies {
    compile 'org.scala-lang:scala-library:2.11.8'
}

when I run gradle build from the command line, I get the following error:

FAILURE: Build failed with an exception.

* What went wrong:
A problem was found with the configuration of task ':compileScala'.
> No value has been specified for property 'zincClasspath'.

I have looked around for where to specify this zincClasspath property, but can't find anything.

I have tried to force the zincClasspath to use an older version of the scala library, but it doesn't seem to work.

Any help is much appreciated

Edit:

One thing to add, this exact project builds fine on my local Windows machine, but not on my Ubuntu VM....

Body:
I ran into this issue again recently, adding the following to my Gradle build script seemed to fix it:

ScalaCompileOptions.metaClass.daemonServer = true
ScalaCompileOptions.metaClass.fork = true
ScalaCompileOptions.metaClass.useAnt = false
ScalaCompileOptions.metaClass.useCompileDaemon = false


问:
Javascript promise returns unexpected token error
Hi am trying to use request module with promise in nodeJS.

Here is my Script

```<code>require('promise');
var request = require('request');
const requestget = function (url) {
  return  new Promise((resolve, reject) {
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            resolve(body);

         } else {
            reject(error);
         }
       });
  });
}
requestget('http://www.modulus.io').then(console.log);
</code>```

but am getting the following error.

```<code>/home/xyz/reques.js:14
  return  new Promise((resolve, reject) {
                                        ^
SyntaxError: Unexpected token {
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3
</code>```

I really don't know what's wrong in this script any one can help me out.

答:
On this line, you need to make sure you are defining a function. You can do this using arrow functions like so:

```<code>return new Promise((resolve, reject) => {
</code>```

Arrow functions have the syntax (param1, param2) => {function body}, which is the same thing as saying function(param1, param2) {function body}. You can read more about them here.

Body:
Hi am trying to use request module with promise in nodeJS.

Here is my Script

require('promise');
var request = require('request');
const requestget = function (url) {
  return  new Promise((resolve, reject) {
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            resolve(body);

         } else {
            reject(error);
         }
       });
  });
}
requestget('http://www.modulus.io').then(console.log);

but am getting the following error.

/home/xyz/reques.js:14
  return  new Promise((resolve, reject) {
                                        ^
SyntaxError: Unexpected token {
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

I really don't know what's wrong in this script any one can help me out.

Body:
On this line, you need to make sure you are defining a function. You can do this using arrow functions like so:

return new Promise((resolve, reject) => {

Arrow functions have the syntax (param1, param2) => {function body}, which is the same thing as saying function(param1, param2) {function body}. You can read more about them here.


问:
Odoo template page doesn't update when xml changes
Just started Odoo for a client, and I have a major problem with a template.

a simple template that has some divs and headers.
I also have a record for it to show in the main menu.

Everything works when i first create it.
However if it happens that i want to add or change some html, those changes don't show on the website page (even after I refresh/upgrade the theme).
The website builder allows me to change the text and whatnot, but that's not what I need. I want to be able to change the html structure from the XML. But as soon as the page is created the first time... I'm not allowed to. The page will only display the page as first created.

Hope it's clear and thank you in advance for any help.

Joe

答:
when changes done in view or template in odoo you need to update module so that the changes reflect in view.
so try to update your module from apps or update from terminal

login into your database and run following command in terminal and reload page from browser.

For odoo 8,9

```<code>python openerp-server -u your_module_name
</code>```

For odoo 10

```<code>python odoo-bin -u your_module_name
</code>```

Body:
when changes done in view or template in odoo you need to update module so that the changes reflect in view.
so try to update your module from apps or update from terminal

login into your database and run following command in terminal and reload page from browser.

For odoo 8,9

python openerp-server -u your_module_name

For odoo 10

python odoo-bin -u your_module_name


问:
inserting data by choosing from one of multiple levels
with 2 dataframes as

```<code>df1

  num organism tier    A    B    C    D    E
1   1      Ham    1 <NA>    a <NA> <NA>    b
2   1      Ham    1 <NA>    c <NA> <NA>    b
3   1      Sta    1    b <NA> <NA>    a    b
4   1      Sta    1    a <NA> <NA>    a    c
5   1      Sta    1 <NA> <NA> <NA> <NA> <NA>
6   2      Sta    2    c    c <NA>    a    b
7   2      Sta    2    a    c <NA>    b    a
8   3      Ham    3 <NA> <NA> <NA> <NA> <NA>

df2

  num tier name
1   1    1  Ham
2   1    1  Sta
3   2    2  Sta
4   3    3  Ham
</code>```

i would like to find the columns which match the num, organism, and tier from df1 and insert the information from df1$A to df1$E.
instead of inserting all the data, is there a way to choose only the highest level?

for example, if levels 'a' > 'b' > 'c',
insert 'a' if 'a' is present,
insert 'b' if 'b' is present wihout any 'a's,
and so on.
lastly, if only NAs or present, insert NA.

my final result should look as

```<code>df3

  num tier name    A     B    C    D    E
1   1    1  Ham  <NA>    a <NA> <NA>    b
2   1    1  Sta    a  <NA> <NA>    a    b
3   2    2  Sta    a     c <NA>    a    a
4   3    3  Ham  <NA> <NA> <NA> <NA> <NA>
</code>```

答:
I don't think you even need df2. Just aggregate after assigning the correct levels to an ordered factor:

```<code>ids <- match(c("num","organism","tier"), names(df1))
df1[-ids] <- lapply(df1[-ids], ordered, levels=c("c","b","a") )
aggregate(df1[-ids], df1[ids], FUN = max, na.rm=TRUE)

#  num organism tier    A    B    C    D    E
#1   1      Ham    1 <NA>    a <NA> <NA>    b
#2   1      Sta    1    a <NA> <NA>    a    b
#3   2      Sta    2    a    c <NA>    a    a
#4   3      Ham    3 <NA> <NA> <NA> <NA> <NA>
</code>```

Ignore the warnings() - R just warns that you have taken the max of nothing, in the case where you only have NA values.

Body:
with 2 dataframes as

df1

  num organism tier    A    B    C    D    E
1   1      Ham    1 <NA>    a <NA> <NA>    b
2   1      Ham    1 <NA>    c <NA> <NA>    b
3   1      Sta    1    b <NA> <NA>    a    b
4   1      Sta    1    a <NA> <NA>    a    c
5   1      Sta    1 <NA> <NA> <NA> <NA> <NA>
6   2      Sta    2    c    c <NA>    a    b
7   2      Sta    2    a    c <NA>    b    a
8   3      Ham    3 <NA> <NA> <NA> <NA> <NA>

df2

  num tier name
1   1    1  Ham
2   1    1  Sta
3   2    2  Sta
4   3    3  Ham

i would like to find the columns which match the num, organism, and tier from df1 and insert the information from df1$A to df1$E.
instead of inserting all the data, is there a way to choose only the highest level?

for example, if levels 'a' > 'b' > 'c',
insert 'a' if 'a' is present,
insert 'b' if 'b' is present wihout any 'a's,
and so on.
lastly, if only NAs or present, insert NA.

my final result should look as

df3

  num tier name    A     B    C    D    E
1   1    1  Ham  <NA>    a <NA> <NA>    b
2   1    1  Sta    a  <NA> <NA>    a    b
3   2    2  Sta    a     c <NA>    a    a
4   3    3  Ham  <NA> <NA> <NA> <NA> <NA>

Body:
I don't think you even need df2. Just aggregate after assigning the correct levels to an ordered factor:

ids <- match(c("num","organism","tier"), names(df1))
df1[-ids] <- lapply(df1[-ids], ordered, levels=c("c","b","a") )
aggregate(df1[-ids], df1[ids], FUN = max, na.rm=TRUE)

#  num organism tier    A    B    C    D    E
#1   1      Ham    1 <NA>    a <NA> <NA>    b
#2   1      Sta    1    a <NA> <NA>    a    b
#3   2      Sta    2    a    c <NA>    a    a
#4   3      Ham    3 <NA> <NA> <NA> <NA> <NA>

Ignore the warnings() - R just warns that you have taken the max of nothing, in the case where you only have NA values.


问:
Running from command line-writing to file
I'm kinda new here. I'm trying to run a java program through the command line but I need to output to a file. So, in the command line I run:

[my filepath]> javac filename.java

And then I run

[my filepath]> javac filename.java > outputfileIneed.txt

In filename.java, I use System.out.println(), and the computer creates a text file in the appropriate location, but the file is blank. What do I write to fix this? This seems to be more of a java problem; is there a command other than System.out.println() to print to a text file from commmand line?

Please ask for more information if you need.

答:
You need to compile your java file first.

```<code>javac filename.java
</code>```

Then, you need to run your class file using

```<code>java filename > outputfileIneed.txt
</code>```

Also, System.out.println() is for console output, not for writing to file. .

If you java program compiles and executes successfully and prints output to the console. Then, above line will do your job.

==Updated==

If you are using PrintWriter in your java code. Then, you can use below sample code.

```<code>public class Testing {

  public static void main(String[] args) throws IOException {

    File file = new File ("C:/Users/Me/Desktop/directory/outputfileineed.txt");
    PrintWriter printWriter = new PrintWriter ("outputfileineed.txt");
    printWriter.println ("hello");
    printWriter.close ();
  }
}
</code>```

Please note that, once you include above line of code in your java file. Then, you only need to compile your java file again and run as show below

```<code>java filename
</code>```

Body:
You need to compile your java file first.

javac filename.java

Then, you need to run your class file using

java filename > outputfileIneed.txt

Also, System.out.println() is for console output, not for writing to file. .

If you java program compiles and executes successfully and prints output to the console. Then, above line will do your job.

==Updated==

If you are using PrintWriter in your java code. Then, you can use below sample code.

public class Testing {

  public static void main(String[] args) throws IOException {

    File file = new File ("C:/Users/Me/Desktop/directory/outputfileineed.txt");
    PrintWriter printWriter = new PrintWriter ("outputfileineed.txt");
    printWriter.println ("hello");
    printWriter.close ();
  }
}

Please note that, once you include above line of code in your java file. Then, you only need to compile your java file again and run as show below

java filename


问:
converting a string into a double
I am looking for a way to get floating point input from a user.

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

My safe get string:

```<code>void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}
</code>```

What would be the best way to write this get_double function?

答:
Why are you not using fgets()?

You're looking for atof().

(Thanks to R. for fixing my idiotic suggestion in part 1)

Title: converting a string into a double

Body:
I am looking for a way to get floating point input from a user.

My way of going about this is to use a self-made getstrn function and plug that into another function which would convert the string into a double.

My safe get string:

void safeGetString(char arr[], int limit){
    int c, i;
    i = 0;
    c = getchar();
    while (c != '\n'){
        if (i < limit -1){
            arr[i] = c;
            i++;
        }
        c = getchar();
    }
    arr[i] = '\0';
}

What would be the best way to write this get_double function?


问:
paypal API refund
Currently I am working on paypal NVP API,

Our customers have a paypal account. And each customer has given me permission to refund these commands. To do this, they added the name of my API paypal account and they check the option: issus a refund for a specific transaction.

they provide me the transaction id for each order ,and my application is supposed to make a refund.

Here is a summary of my program:

```<code>url = 'https://api-3t.paypal.com/nvp'
params =  {
    'USER':'name of my api',
    'PWD': 'pass word of my api',
    'SIGNATURE':'my signature'
     }
 params['METHOD'] = 'RefundTransaction'
 params['VERSION'] = 94
 params['TRANSACTIONID'] = transaction_id
 params['currencyCode'] =  currency
 params['REFUNDTYPE'] = 'Full'
 http.post(url,params)
</code>```

but at the end of execution it returns me:

```<code>{'res': 'TIMESTAMP=2013%2d11%2d26T15%3a43%3a16Z&CORRELATIONID=848a8035cc65&ACK=Failure& VERSION=51%2e0&BUILD=8620107&L_ERRORCODE0=10007&L_SHORTMESSAGE0=Permission%20denied&L_LONGMESSAGE0=You%20do%20not%20have%20permission%20to%20refund%20this%20transaction&L_SEVERITYCODE0=Error', 'code': 200}
</code>```

it means that I have not permession to this transaction, While our customers have added me to their paypal account.

How can I address this?

答:
Here is the best working example to Refund with NVP

```<code>class PayPalRefund
{
private $API_Username, $API_Password, $Signature, $API_Endpoint, $version;
function __construct($intializeData)
{

    if($intializeData['mode'] == "live")
    {
        $this->API_Endpoint = "https://api-3t.paypal.com/nvp";
    }else{
       $this->API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
    }
    $this->API_Username = $intializeData['username'];
    $this->API_Password = $intializeData['password'];
    $this->Signature = $intializeData['signature'];
    $this->version = "51.0";
}

/**
 * This function actually Sends the CURL Request for Refund
 * @param string - $requestString
 * @return array - returns the response
 */
function sendRefundRequest($requestString)
{
    $this->API_UserName  = urlencode($this->API_Username);
    $this->API_Password  = urlencode($this->API_Password);
    $this->API_Signature = urlencode($this->Signature);

    $this->version = urlencode($this->version);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->API_Endpoint);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    // Set the API operation, version, and API signature in the request.
    $reqStr = "METHOD=RefundTransaction&VERSION={$this->version}&PWD={$this->API_Password}&USER={$this->API_UserName}&SIGNATURE={$this->API_Signature}$requestString";

    // Set the request as a POST FIELD for curl.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $reqStr);

    // Get response from the server.
    $curlResponse = curl_exec($ch);

    if(!$curlResponse)
        return array("ERROR_MESSAGE"=>"RefundTransaction failed".curl_error($ch)."(".curl_errno($ch).")");

    // Extract the response details.
    $httpResponseAr = explode("&", $curlResponse);

    $aryResponse = array();
    foreach ($httpResponseAr as $i => $value)
    {
        $tmpAr = explode("=", $value);
        if(sizeof($tmpAr) > 1)
        {
            $aryResponse[$tmpAr[0]] = urldecode($tmpAr[1]);
        }
    }

    if((0 == sizeof($aryResponse)) || !array_key_exists('ACK', $aryResponse))
        return array("ERROR_MESSAGE"=>"Invalid HTTP Response for POST request ($reqStr) to {$this->API_Endpoint}");

    return $aryResponse;
}

/**
 * @param array $aryData
 * @return array
 */
function refundAmount($aryData)
{
    if(trim(@$aryData['currencyCode'])=="")
        return array("ERROR_MESSAGE"=>"Currency Code is Missing");
    if(trim(@$aryData['refundType'])=="")
        return array("ERROR_MESSAGE"=>"Refund Type is Missing");
    if(trim(@$aryData['transactionID'])=="")
        return array("ERROR_MESSAGE"=>"Transaction ID is Missing");

    $requestString = "&TRANSACTIONID={$aryData['transactionID']}&REFUNDTYPE={$aryData['refundType']}&CURRENCYCODE={$aryData['currencyCode']}";

    if(trim(@$aryData['invoiceID'])!="")
        $requestString = "&INVOICEID={$aryData['invoiceID']}";

    if(isset($aryData['memo']))
        $requestString .= "&NOTE={$aryData['memo']}";

    if(strcasecmp($aryData['refundType'], 'Partial') == 0)
    {
        if(!isset($aryData['amount']))
        {
            return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to mention Amount");
        }
        else
        {
            $requestString = $requestString."&AMT={$aryData['amount']}";
        }

        if(!isset($aryData['memo']))
        {
            return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to enter text for Memo");
        }
    }

    $resCurl = $this->sendRefundRequest($requestString);
    return $resCurl;
}

}
</code>```

Once Class is ready, you can call functions in your Business logic

```<code>        require_once('PaypalRefund.php');
        /* Refund Type ('Partial', 'Full')*/
        $intializeData = array('email'=>$this->credentials->email,
                              'username'=>$this->credentials->username,
                              'password'=>$this->credentials->password,
                              'signature'=>$this->credentials->signature,
                              'mode'=>'sandbox',  //'live'
                              );
        $aryData['transactionID'] = $data['transaction_id'];
        $aryData['refundType'] = "Full"; //Partial or Full
        $aryData['currencyCode'] = $data['currency_code'];
        $aryData['amount'] = $data['amount'];   //$data['amount'];
        $aryData['memo'] = $data['notes'];

        // Paypal Refund API Call
        $ref = new PaypalRefund($intializeData);
        $aryRes = $ref->refundAmount($aryData);
        echo "```"; print_r($aryRes);echo "```";die;
</code>```

You will get Response upfront as well as on IPN URL (if set).

Thanks

Title: paypal API refund

Body:
Currently I am working on paypal NVP API,

Our customers have a paypal account. And each customer has given me permission to refund these commands. To do this, they added the name of my API paypal account and they check the option: issus a refund for a specific transaction.

they provide me the transaction id for each order ,and my application is supposed to make a refund.

Here is a summary of my program:

url = 'https://api-3t.paypal.com/nvp'
params =  {
    'USER':'name of my api',
    'PWD': 'pass word of my api',
    'SIGNATURE':'my signature'
     }
 params['METHOD'] = 'RefundTransaction'
 params['VERSION'] = 94
 params['TRANSACTIONID'] = transaction_id
 params['currencyCode'] =  currency
 params['REFUNDTYPE'] = 'Full'
 http.post(url,params)

but at the end of execution it returns me:

{'res': 'TIMESTAMP=2013%2d11%2d26T15%3a43%3a16Z&CORRELATIONID=848a8035cc65&ACK=Failure& VERSION=51%2e0&BUILD=8620107&L_ERRORCODE0=10007&L_SHORTMESSAGE0=Permission%20denied&L_LONGMESSAGE0=You%20do%20not%20have%20permission%20to%20refund%20this%20transaction&L_SEVERITYCODE0=Error', 'code': 200}

it means that I have not permession to this transaction, While our customers have added me to their paypal account.

How can I address this?

Body:
Here is the best working example to Refund with NVP

class PayPalRefund
{
private $API_Username, $API_Password, $Signature, $API_Endpoint, $version;
function __construct($intializeData)
{

    if($intializeData['mode'] == "live")
    {
        $this->API_Endpoint = "https://api-3t.paypal.com/nvp";
    }else{
       $this->API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
    }
    $this->API_Username = $intializeData['username'];
    $this->API_Password = $intializeData['password'];
    $this->Signature = $intializeData['signature'];
    $this->version = "51.0";
}

/**
 * This function actually Sends the CURL Request for Refund
 * @param string - $requestString
 * @return array - returns the response
 */
function sendRefundRequest($requestString)
{
    $this->API_UserName  = urlencode($this->API_Username);
    $this->API_Password  = urlencode($this->API_Password);
    $this->API_Signature = urlencode($this->Signature);

    $this->version = urlencode($this->version);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->API_Endpoint);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    // Set the API operation, version, and API signature in the request.
    $reqStr = "METHOD=RefundTransaction&VERSION={$this->version}&PWD={$this->API_Password}&USER={$this->API_UserName}&SIGNATURE={$this->API_Signature}$requestString";

    // Set the request as a POST FIELD for curl.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $reqStr);

    // Get response from the server.
    $curlResponse = curl_exec($ch);

    if(!$curlResponse)
        return array("ERROR_MESSAGE"=>"RefundTransaction failed".curl_error($ch)."(".curl_errno($ch).")");

    // Extract the response details.
    $httpResponseAr = explode("&", $curlResponse);

    $aryResponse = array();
    foreach ($httpResponseAr as $i => $value)
    {
        $tmpAr = explode("=", $value);
        if(sizeof($tmpAr) > 1)
        {
            $aryResponse[$tmpAr[0]] = urldecode($tmpAr[1]);
        }
    }

    if((0 == sizeof($aryResponse)) || !array_key_exists('ACK', $aryResponse))
        return array("ERROR_MESSAGE"=>"Invalid HTTP Response for POST request ($reqStr) to {$this->API_Endpoint}");

    return $aryResponse;
}

/**
 * @param array $aryData
 * @return array
 */
function refundAmount($aryData)
{
    if(trim(@$aryData['currencyCode'])=="")
        return array("ERROR_MESSAGE"=>"Currency Code is Missing");
    if(trim(@$aryData['refundType'])=="")
        return array("ERROR_MESSAGE"=>"Refund Type is Missing");
    if(trim(@$aryData['transactionID'])=="")
        return array("ERROR_MESSAGE"=>"Transaction ID is Missing");

    $requestString = "&TRANSACTIONID={$aryData['transactionID']}&REFUNDTYPE={$aryData['refundType']}&CURRENCYCODE={$aryData['currencyCode']}";

    if(trim(@$aryData['invoiceID'])!="")
        $requestString = "&INVOICEID={$aryData['invoiceID']}";

    if(isset($aryData['memo']))
        $requestString .= "&NOTE={$aryData['memo']}";

    if(strcasecmp($aryData['refundType'], 'Partial') == 0)
    {
        if(!isset($aryData['amount']))
        {
            return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to mention Amount");
        }
        else
        {
            $requestString = $requestString."&AMT={$aryData['amount']}";
        }

        if(!isset($aryData['memo']))
        {
            return array("ERROR_MESSAGE"=>"For Partial Refund - It is essential to enter text for Memo");
        }
    }

    $resCurl = $this->sendRefundRequest($requestString);
    return $resCurl;
}

}

Once Class is ready, you can call functions in your Business logic

        require_once('PaypalRefund.php');
        /* Refund Type ('Partial', 'Full')*/
        $intializeData = array('email'=>$this->credentials->email,
                              'username'=>$this->credentials->username,
                              'password'=>$this->credentials->password,
                              'signature'=>$this->credentials->signature,
                              'mode'=>'sandbox',  //'live'
                              );
        $aryData['transactionID'] = $data['transaction_id'];
        $aryData['refundType'] = "Full"; //Partial or Full
        $aryData['currencyCode'] = $data['currency_code'];
        $aryData['amount'] = $data['amount'];   //$data['amount'];
        $aryData['memo'] = $data['notes'];

        // Paypal Refund API Call
        $ref = new PaypalRefund($intializeData);
        $aryRes = $ref->refundAmount($aryData);
        echo "<pre>"; print_r($aryRes);echo "</pre>";die;

You will get Response upfront as well as on IPN URL (if set).

Thanks


问:
Not able to assign On Delete Set null and on updated set Null in mysql
bank_api_uat_user Table

```<code>CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bank_name` varchar(255) DEFAULT NULL,
  `role` varchar(10) NOT NULL,
  `bank_code` char(10) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(20) NOT NULL,
  `api_key` varchar(255) NOT NULL,
  `Client_Secret` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_name` (`user_name`),
  KEY `user_name_2` (`user_name`),
  KEY `id` (`id`,`user_name`),
  KEY `role` (`role`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
</code>```

create_role Table

```<code>CREATE TABLE IF NOT EXISTS `create_role` (
  `date` datetime NOT NULL,
  `Role_name` varchar(50) NOT NULL,
  `Role_code` varchar(5) NOT NULL,
  PRIMARY KEY (`Role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

I want to assign referential integrity to bank_api_uat_user table each time i add constraint it gives below error
MySQL said: Documentation

1215 - Cannot add foreign key constraint

Below query used to create foreign key.

```<code>ALTER TABLE `bank_api_uat_user` ADD  CONSTRAINT `const_file_role` FOREIGN KEY (`role`) REFERENCES `test`.`create_role`(`Role_code`) ON DELETE SET NULL ON UPDATE SET NULL;
</code>```

答:
Its important to make a child column Null for setting null reference option.

the above queries work if role is declared as NULL

```<code>CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bank_name` varchar(255) DEFAULT NULL,
  `role` varchar(10) NULL,
  `bank_code` char(10) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(20) NOT NULL,
  `api_key` varchar(255) NOT NULL,
  `Client_Secret` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_name` (`user_name`),
  KEY `user_name_2` (`user_name`),
  KEY `id` (`id`,`user_name`),
  KEY `role` (`role`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
</code>```

Full explanation can be find here : https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

Body:
bank_api_uat_user Table

CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bank_name` varchar(255) DEFAULT NULL,
  `role` varchar(10) NOT NULL,
  `bank_code` char(10) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(20) NOT NULL,
  `api_key` varchar(255) NOT NULL,
  `Client_Secret` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_name` (`user_name`),
  KEY `user_name_2` (`user_name`),
  KEY `id` (`id`,`user_name`),
  KEY `role` (`role`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;

create_role Table

CREATE TABLE IF NOT EXISTS `create_role` (
  `date` datetime NOT NULL,
  `Role_name` varchar(50) NOT NULL,
  `Role_code` varchar(5) NOT NULL,
  PRIMARY KEY (`Role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

I want to assign referential integrity to bank_api_uat_user table each time i add constraint it gives below error
MySQL said: Documentation

1215 - Cannot add foreign key constraint

Below query used to create foreign key.

ALTER TABLE `bank_api_uat_user` ADD  CONSTRAINT `const_file_role` FOREIGN KEY (`role`) REFERENCES `test`.`create_role`(`Role_code`) ON DELETE SET NULL ON UPDATE SET NULL;

Body:
Its important to make a child column Null for setting null reference option.

the above queries work if role is declared as NULL

CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bank_name` varchar(255) DEFAULT NULL,
  `role` varchar(10) NULL,
  `bank_code` char(10) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(20) NOT NULL,
  `api_key` varchar(255) NOT NULL,
  `Client_Secret` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_name` (`user_name`),
  KEY `user_name_2` (`user_name`),
  KEY `id` (`id`,`user_name`),
  KEY `role` (`role`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;

Full explanation can be find here : https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html


问:
C# Inserting a DataSet Into SQL Database
I'm trying to insert a dataset into an SQL database but I am having difficulties passing my dataset as an argument to my DB class. I am not sure if it is allowed to pass as an argument. If not, what are my alternatives?

The way I create my dataset:

```<code>public static void getLogs() {
    string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\someDir";
    SQLiteConnection cn = new SQLiteConnection("Data Source=" + path + ";Version=3;New=False;Compress=True;");
    cn.Open();
    SQLiteDataAdapter sd = new SQLiteDataAdapter("SELECT * FROM table", cn);

    DataSet ds = new DataSet();
    sd.Fill(ds);

    cn.Close();

    db.InsertLogs(Form1.adminID, Form1.deviceID, ds);
}
</code>```

My database class and insert method looks like the following:

```<code>public void InsertLogs(string user_id, string device_id, DataSet history)
{
    string query = "INSERT INTO table (column1, column2, column3, column4, column5, column6, column7) VALUES (@value1, @value2, @value3, @value4, @value5, @value6, @value7);";

    if (OpenConnection() == true)
    {
        foreach (DataTable table in history.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.Parameters.AddWithValue("@value1", int.Parse(user_id));
                cmd.Parameters.AddWithValue("@value2", int.Parse(device_id));
                cmd.Parameters.AddWithValue("@value3", row[0]);
                cmd.Parameters.AddWithValue("@value4", row[1]);
                cmd.Parameters.AddWithValue("@value5", row[2]);
                cmd.Parameters.AddWithValue("@value6", row[3]);
                cmd.Parameters.AddWithValue("@value7", row[4]);
                cmd.ExecuteNonQuery();
            }
        }
        CloseConnection();
    }
}
</code>```

Thank you

答:
1.- Go to SQL Server, under your DB name go to "programmability\Types\User-Defined Table Types, right click and create a new one:

```<code>USE DBNAME
GO

-- Create the data type
CREATE TYPE ValuesToInsert AS TABLE
(
    Value1 INT NOT NULL,
    Value2 INT NOT NULL,
    Value3 VARCHAR(20)
)
GO
</code>```

2.-  Create a SP to receive the table as parameter, parameter must be the new User-Defined table type created in step 1

```<code>USE [DBNAME]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--
CREATE PROCEDURE [dbo].[spImportData]
    @DataImported dbo.ValuesToInsert READONLY
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO [dbo].[TableName] (Value1, Value2, Value3)
    SELECT Value1, Value2, Value3
    FROM @DataImported
</code>```

3.- Pass a datatable from your code to DB, in this case using Dapper.net as following:

```<code>DataTable dtExcelData = new DataTable();
 //Fill dtExcelData and pass as parameter
 ParametersCollection param = new ParametersCollection();
 param.Add(CreateParameter("@DataImported", dtExcelData));
 ExecuteDataSet("spImportData", CommandType.StoredProcedure, param);
</code>```

Body:
I'm trying to insert a dataset into an SQL database but I am having difficulties passing my dataset as an argument to my DB class. I am not sure if it is allowed to pass as an argument. If not, what are my alternatives?

The way I create my dataset:

public static void getLogs() {
    string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\someDir";
    SQLiteConnection cn = new SQLiteConnection("Data Source=" + path + ";Version=3;New=False;Compress=True;");
    cn.Open();
    SQLiteDataAdapter sd = new SQLiteDataAdapter("SELECT * FROM table", cn);

    DataSet ds = new DataSet();
    sd.Fill(ds);

    cn.Close();

    db.InsertLogs(Form1.adminID, Form1.deviceID, ds);
}

My database class and insert method looks like the following:

public void InsertLogs(string user_id, string device_id, DataSet history)
{
    string query = "INSERT INTO table (column1, column2, column3, column4, column5, column6, column7) VALUES (@value1, @value2, @value3, @value4, @value5, @value6, @value7);";

    if (OpenConnection() == true)
    {
        foreach (DataTable table in history.Tables)
        {
            foreach (DataRow row in table.Rows)
            {
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.Parameters.AddWithValue("@value1", int.Parse(user_id));
                cmd.Parameters.AddWithValue("@value2", int.Parse(device_id));
                cmd.Parameters.AddWithValue("@value3", row[0]);
                cmd.Parameters.AddWithValue("@value4", row[1]);
                cmd.Parameters.AddWithValue("@value5", row[2]);
                cmd.Parameters.AddWithValue("@value6", row[3]);
                cmd.Parameters.AddWithValue("@value7", row[4]);
                cmd.ExecuteNonQuery();
            }
        }
        CloseConnection();
    }
}

Thank you

Body:
1.- Go to SQL Server, under your DB name go to "programmability\Types\User-Defined Table Types, right click and create a new one:

USE DBNAME
GO

-- Create the data type
CREATE TYPE ValuesToInsert AS TABLE
(
    Value1 INT NOT NULL,
    Value2 INT NOT NULL,
    Value3 VARCHAR(20)
)
GO

2.-  Create a SP to receive the table as parameter, parameter must be the new User-Defined table type created in step 1

USE [DBNAME]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--
CREATE PROCEDURE [dbo].[spImportData]
    @DataImported dbo.ValuesToInsert READONLY
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    INSERT INTO [dbo].[TableName] (Value1, Value2, Value3)
    SELECT Value1, Value2, Value3
    FROM @DataImported

3.- Pass a datatable from your code to DB, in this case using Dapper.net as following:

DataTable dtExcelData = new DataTable();
 //Fill dtExcelData and pass as parameter
 ParametersCollection param = new ParametersCollection();
 param.Add(CreateParameter("@DataImported", dtExcelData));
 ExecuteDataSet("spImportData", CommandType.StoredProcedure, param);


问:
What is cooks-kim algorithm
I was reading about sorting of presorted list in which few numbers are unsorted, someone said that cooks-kim algorithm is best for such cases, I googled about it but no relevant links.

Please let me know if anyone knows about it

Thank you

答: There's one research paper of them... You can view it if you have ACM account</p>

Title: What is cooks-kim algorithm


问:
SSIS send mail task failing after deployment
I am working SQL Server 2016 and things are working in Visual Studio, but when I deployed my project to the Integration service catalog, SSIS send email task failed.

I am getting below mentioned error:

Send Mail Task: Error: An error occurred with the following error message:

Failure sending mail.

  System.Net.WebException: Unable to connect to the remote server    System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions IPaddress:25

Not sure what is happening and why it is failing only after deployment. Send email tasks are working fine, when I execute from Visual Studio.

答:
I'm not giving you a solution, but anyway:

Maybe your LAN's FW is blocking a connection from server but not from your development PC?


问:
Adding additional values to tables in Lua
I have a input file with different food types

```<code>Corn Fiber 17
Beans Protein 12
Milk Protien 15
Butter Fat 201
Eggs Fat 2
Bread Fiber 12
Eggs Cholesterol 4
Eggs Protein 8
Milk Fat 5
</code>```

(Don't take these too seriously. I'm no nutrition expert) Anyway, I have the following script that reads the input file then puts the following into a table

```<code>    file = io.open("food.txt")
foods = {}
nutritions = {}
for line in file:lines()
    do
        local f, n, v = line:match("(%a+) (%a+) (%d+)")
        nutritions[n] = {value = v}
        --foods[f] = {} Not sure how to implement here
    end
file:close()
</code>```

(It's a little messy right now)
Notice also that different foods can have different nutrients. For example, eggs have both protein and fat. I need a way to let the program, know which value I am trying to call. For example:

```<code>> print(foods.Eggs.Fat)
2
> print(foods.Eggs.Protein
8
</code>```

I believe I need two tables, as shown above. The foods table will contain a table of nutritions. This way, I can have multiple food types with multiple different nutrient facts.  However, I am not sure how to handle a table of tables. How can I implement this within my program?

答:
The straightforward way is to test if food[f] exists, to decide whether to create a new table or add elements to existing one.

```<code>foods = {}
for line in file:lines() do
    local f, n, v = line:match("(%a+) (%a+) (%d+)")
    if foods[f] then
        foods[f][n] = v
    else
        foods[f] = {[n] = v}
    end
end
</code>```

Body:
I have a input file with different food types

Corn Fiber 17
Beans Protein 12
Milk Protien 15
Butter Fat 201
Eggs Fat 2
Bread Fiber 12
Eggs Cholesterol 4
Eggs Protein 8
Milk Fat 5

(Don't take these too seriously. I'm no nutrition expert) Anyway, I have the following script that reads the input file then puts the following into a table

    file = io.open("food.txt")
foods = {}
nutritions = {}
for line in file:lines()
    do
        local f, n, v = line:match("(%a+) (%a+) (%d+)")
        nutritions[n] = {value = v}
        --foods[f] = {} Not sure how to implement here
    end
file:close()

(It's a little messy right now)
Notice also that different foods can have different nutrients. For example, eggs have both protein and fat. I need a way to let the program, know which value I am trying to call. For example:

> print(foods.Eggs.Fat)
2
> print(foods.Eggs.Protein
8

I believe I need two tables, as shown above. The foods table will contain a table of nutritions. This way, I can have multiple food types with multiple different nutrient facts.  However, I am not sure how to handle a table of tables. How can I implement this within my program?

Body:
The straightforward way is to test if food[f] exists, to decide whether to create a new table or add elements to existing one.

foods = {}
for line in file:lines() do
    local f, n, v = line:match("(%a+) (%a+) (%d+)")
    if foods[f] then
        foods[f][n] = v
    else
        foods[f] = {[n] = v}
    end
end


问:
Managing the time that user has to wait to play if he exceeded his "Lives" (Android game)
I'm currently developing a quiz game for android.
the player has a specific number of "lives" in the beginning and whenever his answer for a question is wrong, he lose one of his "lives".
And if the number reaches zero he will have to wait some time to be allowed to play again.
I came up with an idea that whenever the lives count reaches zero i save that time added to the time user have to wait.
Then every time i check the Difference between the current time and the saved one.
But if the user changed the date he will pass this restriction.

Is there a better idea for preventing that.

Code:

```<code>private void heartsManager() {
    falseB.setEnabled(false);
    trueB.setEnabled(false);
    heartsCount = Utils.getIntFromPreferences(this,5,"Hearts","SHARED_SAVED_DATA");
    long TimeToUnlock = Utils.getLongFromPreferences(this,0 ,"Saved_Time", "SHARED_SAVED_DATA");
    Date curDate = new Date();
    long currentTime = curDate.getTime();
    if(currentTime<TimeToUnlock) {
        timeDifference = (TimeToUnlock - currentTime);
    }else{
        timeDifference=0;
    }
    if(heartsCount<1&&levelCompleted==levelID) {
        timeCountDown();
    }else {
        hourGlassToHeart.setImageResource(R.drawable.heart);
        hearts.setText(String.valueOf(heartsCount));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                falseB.setEnabled(true);
                trueB.setEnabled(true);
            }
        }, 1500);
    }
}

private void timeCountDown(){
    new CountDownTimer(timeDifference, 1000) {
        public void onTick(long millisUntilFinished) {
            hearts.setText(String.format("%02d:%02d",(millisUntilFinished / 600000),(millisUntilFinished % 60000 / 1000)));
            hourGlassToHeart.setImageResource(R.drawable.hourglass);
        }
        public void onFinish(){
            hourGlassToHeart.setImageResource(R.drawable.heart);
            falseB.setEnabled(true);
            trueB.setEnabled(true);
            heartsCount=heartsCount+1;
            hearts.setText(String.valueOf(heartsCount));
        }
    }.start();
}
</code>```

答:
Make a BroadcastReceiver that detects if the user changed the time (Intent.ACTION_TIME_CHANGED) of the phone. If the user did that, don't trust his local time and query your server for the correct time. Probably meaning that you won't let the user play unless he connects to your server.

```<code>public class TimeChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED))
        {
             //set time changed flag here.
        }
    }

}
</code>```

Don't forget to add the BroadcastReceiver to your manifest or start it.

Opinion: I don't think there's a way around users that change time. Most in the industry accept it because the average user doesn't know about this 'hack'.

Body:
I'm currently developing a quiz game for android.
the player has a specific number of "lives" in the beginning and whenever his answer for a question is wrong, he lose one of his "lives".
And if the number reaches zero he will have to wait some time to be allowed to play again.
I came up with an idea that whenever the lives count reaches zero i save that time added to the time user have to wait.
Then every time i check the Difference between the current time and the saved one.
But if the user changed the date he will pass this restriction.

Is there a better idea for preventing that.

Code:

private void heartsManager() {
    falseB.setEnabled(false);
    trueB.setEnabled(false);
    heartsCount = Utils.getIntFromPreferences(this,5,"Hearts","SHARED_SAVED_DATA");
    long TimeToUnlock = Utils.getLongFromPreferences(this,0 ,"Saved_Time", "SHARED_SAVED_DATA");
    Date curDate = new Date();
    long currentTime = curDate.getTime();
    if(currentTime<TimeToUnlock) {
        timeDifference = (TimeToUnlock - currentTime);
    }else{
        timeDifference=0;
    }
    if(heartsCount<1&&levelCompleted==levelID) {
        timeCountDown();
    }else {
        hourGlassToHeart.setImageResource(R.drawable.heart);
        hearts.setText(String.valueOf(heartsCount));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                falseB.setEnabled(true);
                trueB.setEnabled(true);
            }
        }, 1500);
    }
}

private void timeCountDown(){
    new CountDownTimer(timeDifference, 1000) {
        public void onTick(long millisUntilFinished) {
            hearts.setText(String.format("%02d:%02d",(millisUntilFinished / 600000),(millisUntilFinished % 60000 / 1000)));
            hourGlassToHeart.setImageResource(R.drawable.hourglass);
        }
        public void onFinish(){
            hourGlassToHeart.setImageResource(R.drawable.heart);
            falseB.setEnabled(true);
            trueB.setEnabled(true);
            heartsCount=heartsCount+1;
            hearts.setText(String.valueOf(heartsCount));
        }
    }.start();
}

Body:
Make a BroadcastReceiver that detects if the user changed the time (Intent.ACTION_TIME_CHANGED) of the phone. If the user did that, don't trust his local time and query your server for the correct time. Probably meaning that you won't let the user play unless he connects to your server.

public class TimeChangedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED))
        {
             //set time changed flag here.
        }
    }

}

Don't forget to add the BroadcastReceiver to your manifest or start it.

Opinion: I don't think there's a way around users that change time. Most in the industry accept it because the average user doesn't know about this 'hack'.


答:
You are trying to use arrow functions without arrows.</p>

```<code>require('promise');
var request = require('request');
const requestget = function (url) {
  //Add the arrow on the below line
  return  new Promise((resolve, reject) => {
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            resolve(body);

         } else {
            reject(error);
         }
       });
  });
}
requestget('http://www.modulus.io').then(console.log);
</code>```

Title: Javascript promise returns unexpected token error

Body:
Hi am trying to use request module with promise in nodeJS.

Here is my Script

require('promise');
var request = require('request');
const requestget = function (url) {
  return  new Promise((resolve, reject) {
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            resolve(body);

         } else {
            reject(error);
         }
       });
  });
}
requestget('http://www.modulus.io').then(console.log);

but am getting the following error.

/home/xyz/reques.js:14
  return  new Promise((resolve, reject) {
                                        ^
SyntaxError: Unexpected token {
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

I really don't know what's wrong in this script any one can help me out.

Body:
You are trying to use arrow functions without arrows.

require('promise');
var request = require('request');
const requestget = function (url) {
  //Add the arrow on the below line
  return  new Promise((resolve, reject) => {
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            resolve(body);

         } else {
            reject(error);
         }
       });
  });
}
requestget('http://www.modulus.io').then(console.log);


问:
How can I replicate the trashing animation of Mail.app
In my iPhone app, I have put a UIBarBUtton of type UIBarButtonSystemItemTrash in my UIToolBar. When pressed, I'd like to replicate the animation of Mail.app: the bin opens, the UIView folds and flies into it.

Is there a way to access this animation ithrough the iPhone SDK?

Presently I am using a custom made animation, but there are some limits; for example, I cannot animate the bin itself.
Do you have any suggestion? Code samples?

Cheers,

Davide

答:
Use the suckEffect type on an animation. Also: spewEffect, genieEffect, unGenieEffect, twist, tubey, swirl, cameraIris, cameraIrisHollowClose, cameraIrisHollowOpen, rippleEffect, charminUltra, zoomyIn, and zoomyOut. Doesn't work in the simulator.

```<code>CATransition *animation = [CATransition animation];
animation.type = @"suckEffect";
animation.duration = 2.0f;
animation.timingFunction = UIViewAnimationCurveEaseInOut;
view.opacity = 1.0f;
[view.layer addAnimation:animation forKey:@"transitionViewAnimation"];
</code>```

Note: Code snippet was pulled from a larger codebase. I hope it works :)

OwnerDisplayName: nutsmuggler

LastEditorDisplayName: nutsmuggler

Body:
Use the suckEffect type on an animation. Also: spewEffect, genieEffect, unGenieEffect, twist, tubey, swirl, cameraIris, cameraIrisHollowClose, cameraIrisHollowOpen, rippleEffect, charminUltra, zoomyIn, and zoomyOut. Doesn't work in the simulator.

CATransition *animation = [CATransition animation];
animation.type = @"suckEffect";
animation.duration = 2.0f;
animation.timingFunction = UIViewAnimationCurveEaseInOut;
view.opacity = 1.0f;
[view.layer addAnimation:animation forKey:@"transitionViewAnimation"];

Note: Code snippet was pulled from a larger codebase. I hope it works :)

OwnerDisplayName: rpetrich


答: Use strtod, that's what it's for. And fgets can replace your safeGetString function.

Title: converting a string into a double


问:
Nested explicit definitions
For the sake of argument, let's say I want the following program:

```<code>foo =: monad define
  bar =. dyad define
    x * y
  )
  bar/ y * 2 3
)
</code>```

Ideally, for input 3, this would yield 54. However, when putting this into the console, the first of the two )s is treated as the ending for the first define. Is there any way to prevent this? I want to avoid an inline verb, like monad def 'x * y'. My actual verb example is more complex than this.

答:
The absence of nested blocks was an intentional design decision.

The idea is to put pressure on the developer to name blocks. (And, more generally, there's some significant pressure on the developer to favor concise, simple code.)

That said, adverbs (and conjunctions) can be used to tie blocks together.

Title: Nested explicit definitions

Body:
For the sake of argument, let's say I want the following program:

foo =: monad define
  bar =. dyad define
    x * y
  )
  bar/ y * 2 3
)

Ideally, for input 3, this would yield 54. However, when putting this into the console, the first of the two )s is treated as the ending for the first define. Is there any way to prevent this? I want to avoid an inline verb, like monad def 'x * y'. My actual verb example is more complex than this.


问:
Android Studio Error,
When I launch an Android Studio Project I get this Error

```<code>Error:The newly created daemon process has a different context than expected.
Java home is different.
Expecting: 'D:\Program Files\Android\Android Studio\jre' but was: 'C:\Program Files (x86)\Java\jre1.8.0_101'.
Please configure the JDK to match the expected one.
Open JDK Settings
</code>```

But my JDK file is the same as the expected file location, as you can see in this picture

Edit: Now I'm getting a new error

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap

答:
Please click File-->Project Structrue ... --> SDK Location -->JDK location

Replace /Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home to
C:\Program Files (x86)\Java\jre1.8.0_101
As show below

Title: Android Studio Error,

Body:
When I launch an Android Studio Project I get this Error

Error:The newly created daemon process has a different context than expected.
Java home is different.
Expecting: 'D:\Program Files\Android\Android Studio\jre' but was: 'C:\Program Files (x86)\Java\jre1.8.0_101'.
Please configure the JDK to match the expected one.
Open JDK Settings

But my JDK file is the same as the expected file location, as you can see in this picture

Edit: Now I'm getting a new error

Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Please read the following process output to find out more:

Error occurred during initialization of VM
Could not reserve enough space for 1572864KB object heap


问:
Getting not recognized as an internal or external command error
I want to generate test coverage report for espresso and ui automation test cases.For which I am following this link I have added testCoverageEnabled = true in my android studio but when i am running ./gradlew createDebugCoverageReport getting error . is not recognized as an internal or external command, operable program or batch file. and if i remove . then /gradlew is not recognized as an internal or external command,operable program or batch file. Please help me. Maybe i am running command on wrong path.

Output of gradle wrapper

```<code>C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin>gradle wrapper
Starting a Gradle Daemon (subsequent builds will be faster)
:wrapper FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Some problems were found with the configuration of task ':wrapper'.
> Cannot write to file 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle\wrapper\gradle-wrapper.properties' specified for property 'propertiesFile', as ancestor 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle' is not a directory.
> Cannot write to file 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle\wrapper\gradle-wrapper.jar' specified for property 'jarFile', as ancestor 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle' is not a directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
</code>```

答:
You are following a tutorial which does not match your OS.

```<code>./
</code>```

is Unix based and you are windows based.
If gradlew is in the current directory, then you can run.

```<code>.\gradlew createDebugCoverageReport
</code>```

else, run just

```<code>gradlew createDebugCoverageReport
</code>```

from command line, but that is if gradlew is in the system PATH.

else do

```<code>cd \
dir /S gradlew
</code>```

it will display the path to gradlew, you then just need to cd to it, so let's say it is in C:\Program Files\Gradlew\ you just do

```<code>cd "C:\Program Files\Gradlew\"
</code>```

and run gradlew createDebugCoverageReport from there.

Body:
I want to generate test coverage report for espresso and ui automation test cases.For which I am following this link I have added testCoverageEnabled = true in my android studio but when i am running ./gradlew createDebugCoverageReport getting error . is not recognized as an internal or external command, operable program or batch file. and if i remove . then /gradlew is not recognized as an internal or external command,operable program or batch file. Please help me. Maybe i am running command on wrong path.

Output of gradle wrapper

C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin>gradle wrapper
Starting a Gradle Daemon (subsequent builds will be faster)
:wrapper FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Some problems were found with the configuration of task ':wrapper'.
> Cannot write to file 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle\wrapper\gradle-wrapper.properties' specified for property 'propertiesFile', as ancestor 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle' is not a directory.
> Cannot write to file 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle\wrapper\gradle-wrapper.jar' specified for property 'jarFile', as ancestor 'C:\Users\Shivam\Desktop\gradle\gradle-3.4.1-all\gradle-3.4.1\bin\gradle' is not a directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Body:
You are following a tutorial which does not match your OS.

./

is Unix based and you are windows based.
If gradlew is in the current directory, then you can run.

.\gradlew createDebugCoverageReport

else, run just

gradlew createDebugCoverageReport

from command line, but that is if gradlew is in the system PATH.

else do

cd \
dir /S gradlew

it will display the path to gradlew, you then just need to cd to it, so let's say it is in C:\Program Files\Gradlew\ you just do

cd "C:\Program Files\Gradlew\"

and run gradlew createDebugCoverageReport from there.


问:
How to import mysql data into postgresql in Heroku?(Django project)
Recently I need to import mysql data into postgres database in Heroku. Actcually it includes several steps:

convert mysql data to postgresql

import postgresql data to Heroku

After referring plenty of materials and testing several tools in github, finally I succeed. Here I want to share some of my experience and references.

答:
Firstly, I list some tools for converting mysql database format into postgresql format.

mysql-postgresql-converter
: I finally use this tool and succeed. Dump MySQL database in PostgreSQL-compatible format

mysqldump -u username -p --compatible=postgresql databasename > outputfile.sql

then use the converter to transfer data into *.psql file. then load new dump into a fresh PostgreSQL database.

mysql2postgres : It is a tool which is introduced in Heroku Dev Center. Just refer here Migrating from MySQL to Postgres on Heroku. it is based on Ruby. However, as for me, I found some issues after I finish installation and cannot solve it.

You have already activated test-unit 2.5.5, but your Gemfile requires test-unit 3.2.3. #95

py-mysql2pgsql: Similar process with mysql2postgres above by editing a *.yml file for configuration. There is a nice reference table in README file called Data Type Conversion Legend, which compares different data type between MySQL and PostgreSQL. You can manually modify the data type.

** This website lists some other converting methods.

Some basic operations in PostgreSQL:

```<code>$sudo su - postgres
$createtedb testdb
$psql testdb
=# create user username password ' password ';
-- To change a password:
=# alter role username password ' password ';
=# create database databasename with encoding 'utf8';
</code>```

How to list all database in postgres: PostgreSQL - SELECT Database

```<code>postgres-# \l
                         List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
-----------+----------+----------+---------+-------+-----------------------
 postgres  | postgres | UTF8     | C       | C     |
 template0 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 testdb    | postgres | UTF8     | C       | C     |
(4 rows)

postgres-#
</code>```

Now type the below command to connect/select a desired database, here we will connect to the testdb database:

```<code>postgres=# \c testdb;
psql (9.2.4)
Type "help" for help.
You are now connected to database "testdb" as user "postgres".
testdb=#
</code>```

After you create your database, import the converted tables into psql. Kindly note that a database should be created before importing data.

```<code>$psql -h server -d databasename -U username -f data.sql
</code>```

(sometimes a sudo -u postgres should be added before psql)

How to generate dump of psql using pg_dump: creating dump file

```<code>$sudo -u postgres pg_dump -Fc --no-acl --no-owner -h localhost -U postgres databasename > mydb.dump
</code>```

The next step, how to import data into Heroku Postgres?
After previous steps, you may have import data into your local PostgresSQL or generate a pg_dump file. Here two methods will be introduced to transfer data to remote Heroku Postgres.

use pg_dump file.reference
Use the raw file URL in the pg:backups restore command:

```<code>$ heroku pg:backups:restore 'https://s3.amazonaws.com/me/items/3H0q/mydb.dump' DATABASE_URL
</code>```

In this case, you should firstly upload the dump file to somewhere with an HTTP-accessible URL. The dev center in Heroku recommend using Amazon S3.
The DATABASE_URL represents the HEROKU_POSTGRESQL_COLOR_URL of the database you wish to restore to. For example, my database url is postgresql-globular-XXXXX.

use pg:push
pg:push will push data from your local psql database into remote Heroku Postgres database. The command looks like this:

```<code>$heroku pg:push mylocaldb DATABASE_URL --app sushi
</code>```

This command will take the local database "mylocaldb" and push it to the database at DATABASE_URL on the app "sushi". Kindly note that the remote database must be empty before performing pg:push in order to prevent accidental data overwrites and loss.
Actually I use this pg:push method and succeed finally.

More information about Heroku Postgres can be found in official document of Heroku.

**others:

Viewing logs of your web application in Heroku: heroku logs --tail

How to deploy Python and Django Apps on Heroku?

How to write the Procfile of Django Apps?
A common Procfile of Django projects will look like this:

```<code>web: gunicorn yourprojectname.wsgi --log-file -
</code>```

Here web is a single process type. What we need to modify is yourprojectname.wsgi. Just replace your project name in the prefix.

How to add Gunicorn to your application?

```<code>$ pip install gunicorn
$ pip freeze > requirements.txt
</code>```

How to run command line in remote Heroku server?
You can execute the bash command in Heroku.

```<code>$heroku run bash
Running bash attached to terminal... up, run.1
~ $ ls
</code>```

Then you can do some command such ls, cd just like in your local bash.

Also, you can use commands in this pattern to execute manage.py in remote Heroku:heroku run python manage.py runserver

Body:
Firstly, I list some tools for converting mysql database format into postgresql format.

mysql-postgresql-converter
: I finally use this tool and succeed. Dump MySQL database in PostgreSQL-compatible format

mysqldump -u username -p --compatible=postgresql databasename > outputfile.sql

then use the converter to transfer data into *.psql file. then load new dump into a fresh PostgreSQL database.

mysql2postgres : It is a tool which is introduced in Heroku Dev Center. Just refer here Migrating from MySQL to Postgres on Heroku. it is based on Ruby. However, as for me, I found some issues after I finish installation and cannot solve it.

You have already activated test-unit 2.5.5, but your Gemfile requires test-unit 3.2.3. #95

py-mysql2pgsql: Similar process with mysql2postgres above by editing a *.yml file for configuration. There is a nice reference table in README file called Data Type Conversion Legend, which compares different data type between MySQL and PostgreSQL. You can manually modify the data type.

** This website lists some other converting methods.

Some basic operations in PostgreSQL:

$sudo su - postgres
$createtedb testdb
$psql testdb
=# create user username password ' password ';
-- To change a password:
=# alter role username password ' password ';
=# create database databasename with encoding 'utf8';

How to list all database in postgres: PostgreSQL - SELECT Database

postgres-# \l
                         List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
-----------+----------+----------+---------+-------+-----------------------
 postgres  | postgres | UTF8     | C       | C     |
 template0 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 template1 | postgres | UTF8     | C       | C     | =c/postgres          +
           |          |          |         |       | postgres=CTc/postgres
 testdb    | postgres | UTF8     | C       | C     |
(4 rows)

postgres-#

Now type the below command to connect/select a desired database, here we will connect to the testdb database:

postgres=# \c testdb;
psql (9.2.4)
Type "help" for help.
You are now connected to database "testdb" as user "postgres".
testdb=#

After you create your database, import the converted tables into psql. Kindly note that a database should be created before importing data.

$psql -h server -d databasename -U username -f data.sql

(sometimes a sudo -u postgres should be added before psql)

How to generate dump of psql using pg_dump: creating dump file

$sudo -u postgres pg_dump -Fc --no-acl --no-owner -h localhost -U postgres databasename > mydb.dump

The next step, how to import data into Heroku Postgres?
After previous steps, you may have import data into your local PostgresSQL or generate a pg_dump file. Here two methods will be introduced to transfer data to remote Heroku Postgres.

use pg_dump file.reference
Use the raw file URL in the pg:backups restore command:

$ heroku pg:backups:restore 'https://s3.amazonaws.com/me/items/3H0q/mydb.dump' DATABASE_URL

In this case, you should firstly upload the dump file to somewhere with an HTTP-accessible URL. The dev center in Heroku recommend using Amazon S3.
The DATABASE_URL represents the HEROKU_POSTGRESQL_COLOR_URL of the database you wish to restore to. For example, my database url is postgresql-globular-XXXXX.

use pg:push
pg:push will push data from your local psql database into remote Heroku Postgres database. The command looks like this:

$heroku pg:push mylocaldb DATABASE_URL --app sushi

This command will take the local database "mylocaldb" and push it to the database at DATABASE_URL on the app "sushi". Kindly note that the remote database must be empty before performing pg:push in order to prevent accidental data overwrites and loss.
Actually I use this pg:push method and succeed finally.

More information about Heroku Postgres can be found in official document of Heroku.

**others:

Viewing logs of your web application in Heroku: heroku logs --tail

How to deploy Python and Django Apps on Heroku?

How to write the Procfile of Django Apps?
A common Procfile of Django projects will look like this:

web: gunicorn yourprojectname.wsgi --log-file -

Here web is a single process type. What we need to modify is yourprojectname.wsgi. Just replace your project name in the prefix.

How to add Gunicorn to your application?

$ pip install gunicorn
$ pip freeze > requirements.txt

How to run command line in remote Heroku server?
You can execute the bash command in Heroku.

$heroku run bash
Running bash attached to terminal... up, run.1
~ $ ls

Then you can do some command such ls, cd just like in your local bash.

Also, you can use commands in this pattern to execute manage.py in remote Heroku:heroku run python manage.py runserver


问:
Are there any common erros in JQuery XSLT?
I'm having a problem with a JQuery plugin on a frontend-xslt-site in Firefox. Are there any common errors?</p>

答: In my case it turns out that firefox is the only browser that complies to standard and doesn't support document.write in xhtml. It turns out to be a pretty common problem!</p>


问:
Pushing Python introspection to limits
Simple question – can I print the source code of this if?

```<code>if __name__ == '__main__':
  # ...
  # this is the `if` I want to print
  #  V
  if args and args[0][0] == '-':
    if args[0] in ('--help','-h','-?'):
      print_source_of_block(level=2)
    icase = 'i' in args[0]
    desc = 'd' in args[0]
    args = args[1:]
</code>```

Please don't ask me why I need it, nor give me advice on how to write user help. I want to know it because I'm curious.

答: Might want to look at the inspect module (https://docs.python.org/2/library/inspect.html).  Specifically, the inspect.getsource(object) method.

Title: Pushing Python introspection to limits

Body:
Simple question – can I print the source code of this if?

if __name__ == '__main__':
  # ...
  # this is the `if` I want to print
  #  V
  if args and args[0][0] == '-':
    if args[0] in ('--help','-h','-?'):
      print_source_of_block(level=2)
    icase = 'i' in args[0]
    desc = 'd' in args[0]
    args = args[1:]

Please don't ask me why I need it, nor give me advice on how to write user help. I want to know it because I'm curious.


问:
Use of undefined constant SERVICE_HTTP_PATH - assumed 'SERVICE_HTTP_PATH' in YII2
SERVICE_HTTP_PATH is  not getting recognised although it has been added into the XML file which contains this for web service URL.Do I need to include the XML file in the controller? If yes then how? </p>

答: The problem was because I was trying to use Zend format along with YII2. Actually there is no config.inc.in file in Yii2 so we have to read the properties of the XML file using different functions and run a foreach on it so as to achieve the desired URL value.</p>


问:
need some help understanding an aspect of this code
Please refer the code below

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

public class Reverse {

public static void main(String[] args) {

    String words = "";
    String output = "";

    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        words = scan.nextLine();

        for (int i = 0; i < words.length(); i++) {
            output += words.charAt(words.length() - i - 1);
        }
        output += "\n";
    }
    System.out.print(output);

 }
}
</code>```

First of all, sorry for the vague title but I didn't know how to put it any other way. I am new to Java and for uni, we were given a task that read standard input until the end of file and then outputs the reverse of each line.

I was wondering how

```<code>String output
</code>```

is able to output multiple strings at the end. Shouldn't it only be able to hold one string? Sorry if this question doesn't make much sense.

答:
One single string can hold a sequence of characters. You may not know this, but a "new line" is also a character. This means that the following can be stored in a single string:

```<code>Hello World
Bye World
</code>```

It's just a string with the characters "Hello World", followed by a new line character, followed by "Bye World".

In Java, the new line character is denoted by \n.

In the code, you start with an empty string:

```<code>String output = "";
</code>```

Then in the loop, you start appending characters in reverse order to it:

```<code>output += words.charAt(words.length() - i - 1);
</code>```

Just before the end of the iteration of the while loop, you add a new line to the output:

```<code>output += "\n";
</code>```

Body:
Please refer the code below

import java.util.Scanner;

public class Reverse {

public static void main(String[] args) {

    String words = "";
    String output = "";

    Scanner scan = new Scanner(System.in);
    while (scan.hasNextLine()) {
        words = scan.nextLine();

        for (int i = 0; i < words.length(); i++) {
            output += words.charAt(words.length() - i - 1);
        }
        output += "\n";
    }
    System.out.print(output);

 }
}

First of all, sorry for the vague title but I didn't know how to put it any other way. I am new to Java and for uni, we were given a task that read standard input until the end of file and then outputs the reverse of each line.

I was wondering how

String output

is able to output multiple strings at the end. Shouldn't it only be able to hold one string? Sorry if this question doesn't make much sense.

Body:
One single string can hold a sequence of characters. You may not know this, but a "new line" is also a character. This means that the following can be stored in a single string:

Hello World
Bye World

It's just a string with the characters "Hello World", followed by a new line character, followed by "Bye World".

In Java, the new line character is denoted by \n.

In the code, you start with an empty string:

String output = "";

Then in the loop, you start appending characters in reverse order to it:

output += words.charAt(words.length() - i - 1);

Just before the end of the iteration of the while loop, you add a new line to the output:

output += "\n";


问:
Firebase FCM server php-android
I created a simple php code to send a notification to my android devices which have google log in method from firebase implementation. Their tokens are already stored in my database. When I execute my php, it doesn't send the notification. Whoever , if i send a notification trough firebase notification console it works. This is my php code .

```<code>function sendGCM($message, $registration_ids) {
    //FCM URL
    $url = "https://fcm.googleapis.com/fcm/send";
//prepare data
$fields = array (
    'registration_ids' => array ($registration_ids),
    'data' => array ("message" => $message)
);
$fields = json_encode ( $fields );

//header data
$headers = array ('Authorization: key=<YOUR_API_KEY>', 'Content-Type: application/json');

//initiate curl request
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

// execute curl request
$result = curl_exec ( $ch );

//close curl request
curl_close ( $ch );

//return output
return $result;
}
</code>```

Error:
when I execute this php file, throw this error:

```<code>{

    "multicast_id": 5359746182596118281,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
    {
    "error": "InvalidRegistration"
    }
                ]
    }
</code>```

答:
Try this:-</p>

```<code>    <?php

// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'your_key' );
$registrationIds = array($id); //$id is string not array

// prep the bundle
$notification = array
(
    'title'     => 'title',
    'body'      => 'body',
    'icon'      => 'logo',
    'sound'     => 'default',
    'tag'       => 'tag',
    'color'     => '#ffffff'

);

$data = array
(
    'message' => 'message body',
    'click_action' => "PUSH_INTENT"
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'      => $notification,
    'data'              => $data,
    'priority'          => 'normal'

);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

?>
</code>```

Title: Firebase FCM server php-android

Body:
I created a simple php code to send a notification to my android devices which have google log in method from firebase implementation. Their tokens are already stored in my database. When I execute my php, it doesn't send the notification. Whoever , if i send a notification trough firebase notification console it works. This is my php code .

function sendGCM($message, $registration_ids) {
    //FCM URL
    $url = "https://fcm.googleapis.com/fcm/send";
//prepare data
$fields = array (
    'registration_ids' => array ($registration_ids),
    'data' => array ("message" => $message)
);
$fields = json_encode ( $fields );

//header data
$headers = array ('Authorization: key=<YOUR_API_KEY>', 'Content-Type: application/json');

//initiate curl request
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

// execute curl request
$result = curl_exec ( $ch );

//close curl request
curl_close ( $ch );

//return output
return $result;
}

Error:
when I execute this php file, throw this error:

{

    "multicast_id": 5359746182596118281,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
    {
    "error": "InvalidRegistration"
    }
                ]
    }

Body:
Try this:-

    <?php

// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'your_key' );
$registrationIds = array($id); //$id is string not array

// prep the bundle
$notification = array
(
    'title'     => 'title',
    'body'      => 'body',
    'icon'      => 'logo',
    'sound'     => 'default',
    'tag'       => 'tag',
    'color'     => '#ffffff'

);

$data = array
(
    'message' => 'message body',
    'click_action' => "PUSH_INTENT"
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'notification'      => $notification,
    'data'              => $data,
    'priority'          => 'normal'

);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

?>


问:
Using DataFrame.plot to make a chart with subplots -- how to use ax parameter
I can not wrap my head around axes parameter, what it contains and how to use it for making subplots.

Would really appreciate if someone could explain what is going on in the following example

```<code>fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15, 10))
for idx, feature in enumerate(df.columns[:-1]):
  df.plot(feature, "cnt", subplots=True, kind="scatter", ax=axes[idx / 4, idx % 4])
</code>```

Here is the data (UCI Bike sharing dataset):

Here is the output of the code snippet (a pairwise comparison of features and the end results):

To be more specific, here are the parts that I do understand (at least I think I do)

plt.subplots returns a tuple containing a figure and axes object(s) (link)

enumerate() returns a tuple containing index of a feature and its name(link)

df.plot uses column names to put data on subplots within  fig

Here is what I do not understand

What does axes object contain? Again, based on documentation and this answer I do realize that axes contains "Axis, Tick, Line2D, Text, Polygon, etc." but

what do we address using axes[x,y] ?

why in this example author decided to use [idx / 4, idx % 4] as values?

答:
The axes object in your code is a 2D Numpy array of matplotlib Axes objects. Since the call to subplots() asked for 3 rows and 4 columns, the array will be 3 by 4. Indexing into the array like axes[r, c] gives you the Axes object that corresponds to row r and column c, and you can pass that object as the ax keyword argument to a plotting method to make the plot show up on that axis. E.g. if you wanted to plot something in the second row and second column, you would call plot(..., ax=axes[1,1]).

The code uses [idx / 4, idx % 4] as a way of converting the indices (numbers from 0 to 11) into locations in the 3-by-4 grid. Try evaluating that expression yourself with idx set to each value from 0 to 11 in turn, and you'll see how it works out.

Body:
I can not wrap my head around axes parameter, what it contains and how to use it for making subplots.

Would really appreciate if someone could explain what is going on in the following example

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(15, 10))
for idx, feature in enumerate(df.columns[:-1]):
  df.plot(feature, "cnt", subplots=True, kind="scatter", ax=axes[idx / 4, idx % 4])

Here is the data (UCI Bike sharing dataset):

Here is the output of the code snippet (a pairwise comparison of features and the end results):

To be more specific, here are the parts that I do understand (at least I think I do)

plt.subplots returns a tuple containing a figure and axes object(s) (link)

enumerate() returns a tuple containing index of a feature and its name(link)

df.plot uses column names to put data on subplots within  fig

Here is what I do not understand

What does axes object contain? Again, based on documentation and this answer I do realize that axes contains "Axis, Tick, Line2D, Text, Polygon, etc." but

what do we address using axes[x,y] ?

why in this example author decided to use [idx / 4, idx % 4] as values?