问:
Creating a custom widget in PyQT5
I would like to know how one can create a custom widget in pyqt. I've seen many different examples for C++, and a couple non descript examples for pyqt, but nothing that really explains how to do it and implement it. There is especially no examples that basically aren't just modified qt-designer output, and I'm writing my code from scratch so that's not very helpful.

So far, the best example I could find was basically just someone modifying qt-designer code and not really explaining what any of it was doing.

Could someone please show me an example of how to create a custom widget?

Edit:
I'm attempting to create a widget with an embedded QStackedWidget, and buttons on the bottom to cycle the pages.

I also planned on having a seperate widget for each page, but considering I can't actually accomplish step one, I figured I would cross that bridge when I get to it.

答:
In the following it is shown how to implement a QStackedWidget with 2 buttons, the basic idea is to layout the design, for this we analyze that a QVBoxLayout must be placed to place the QStackedWidget and another layout, this second layout will be a QHBoxLayout to have the buttons. Then we connect the signals that handle the transition between pages. Also in this example I have created 3 types of widgets that will be placed on each page.

```<code>from PyQt5.QtWidgets import *

class Widget1(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        for i in range(4):
            lay.addWidget(QPushButton("{}".format(i)))

class Widget2(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        for i in range(4):
            lay.addWidget(QLineEdit("{}".format(i)))

class Widget3(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        for i in range(4):
            lay.addWidget(QRadioButton("{}".format(i)))

class stackedExample(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        self.Stack = QStackedWidget()
        self.Stack.addWidget(Widget1())
        self.Stack.addWidget(Widget2())
        self.Stack.addWidget(Widget3())

        btnNext = QPushButton("Next")
        btnNext.clicked.connect(self.onNext)
        btnPrevious = QPushButton("Previous")
        btnPrevious.clicked.connect(self.onPrevious)
        btnLayout = QHBoxLayout()
        btnLayout.addWidget(btnPrevious)
        btnLayout.addWidget(btnNext)

        lay.addWidget(self.Stack)
        lay.addLayout(btnLayout)

    def onNext(self):
        self.Stack.setCurrentIndex((self.Stack.currentIndex()+1) % 3)

    def onPrevious(self):
        self.Stack.setCurrentIndex((self.Stack.currentIndex()-1) % 3)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = stackedExample()
    w.show()
    sys.exit(app.exec_())
</code>```

Title: Creating a custom widget in PyQT5

Body:
In the following it is shown how to implement a QStackedWidget with 2 buttons, the basic idea is to layout the design, for this we analyze that a QVBoxLayout must be placed to place the QStackedWidget and another layout, this second layout will be a QHBoxLayout to have the buttons. Then we connect the signals that handle the transition between pages. Also in this example I have created 3 types of widgets that will be placed on each page.

from PyQt5.QtWidgets import *

class Widget1(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        for i in range(4):
            lay.addWidget(QPushButton("{}".format(i)))

class Widget2(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        for i in range(4):
            lay.addWidget(QLineEdit("{}".format(i)))

class Widget3(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        for i in range(4):
            lay.addWidget(QRadioButton("{}".format(i)))

class stackedExample(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        self.Stack = QStackedWidget()
        self.Stack.addWidget(Widget1())
        self.Stack.addWidget(Widget2())
        self.Stack.addWidget(Widget3())

        btnNext = QPushButton("Next")
        btnNext.clicked.connect(self.onNext)
        btnPrevious = QPushButton("Previous")
        btnPrevious.clicked.connect(self.onPrevious)
        btnLayout = QHBoxLayout()
        btnLayout.addWidget(btnPrevious)
        btnLayout.addWidget(btnNext)

        lay.addWidget(self.Stack)
        lay.addLayout(btnLayout)

    def onNext(self):
        self.Stack.setCurrentIndex((self.Stack.currentIndex()+1) % 3)

    def onPrevious(self):
        self.Stack.setCurrentIndex((self.Stack.currentIndex()-1) % 3)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = stackedExample()
    w.show()
    sys.exit(app.exec_())


来源: stackexchange

问:
Include model associations from within the model
I need to clean up my code from using:

```<code># class ProjectsController < ApiController
def show
  render json: Project.find_by(id: params[:id]).as_json(include: :user)
end
</code>```

to:

```<code>render json: Project.find_by(id: params[:id]) // should include the association
</code>```

Is there a way to put this logic in the model? Im using Rails 5 API

```<code>class Project < ApplicationRecord
  belongs_to :user, include: :project // I thought this would work

  def self.foo
    self.includes(:user)
  end
end

# in controller
render json: Project.foo.find_by(id: params[:id]) // nothing
</code>```

What if Project belongs to many models and to need to include it by only calling Project.find(1), I will have some nested includes in my controller. Could I put all this logic in the model then Project.find(1) would show all the associations in json format?

答:
In your Project model, override as_json method to include association user:

```<code>def as_json(options = {})
  super(include: :user)
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to clean up my code from using:

# class ProjectsController < ApiController
def show
  render json: Project.find_by(id: params[:id]).as_json(include: :user)
end

to:

render json: Project.find_by(id: params[:id]) // should include the association

Is there a way to put this logic in the model? Im using Rails 5 API

class Project < ApplicationRecord
  belongs_to :user, include: :project // I thought this would work

  def self.foo
    self.includes(:user)
  end
end

# in controller
render json: Project.foo.find_by(id: params[:id]) // nothing

What if Project belongs to many models and to need to include it by only calling Project.find(1), I will have some nested includes in my controller. Could I put all this logic in the model then Project.find(1) would show all the associations in json format?

Body:
In your Project model, override as_json method to include association user:

def as_json(options = {})
  super(include: :user)
end


问:
Java calling a method with object parameters to main method
```<code>play.java: https://pastebin.com/4bzfE76z
values.java: https://pastebin.com/6mnUzKyA
player.java: https://pastebin.com/qiFymMF6
stats.java: https://pastebin.com/P24AUpXV
</code>```

I have a method called start in play.java with object parameters. The objects were originally declared in values.java inside the sValues method. I want to call the method start to the main method of play.java but I'm not sure what to write inside the parameters of the call.

Inside values.java:

```<code>    player user = new player ();
    user.setP_Name (username);
    user.setP_ATK (atk);
    user.setP_HP (hp);

    stats[] enemies = new stats [3];
    enemies [1] = new stats ();
    enemies [1] = gob;
    enemies [1].getName ();
    enemies [1].getHP ();
    enemies [1].getATK ();
    enemies [1].getMANA ();
    enemies [2] = new stats ();
    enemies [2] = orc;
    enemies [2].getName ();
    enemies [2].getHP ();
    enemies [2].getATK ();
    enemies [2].getMANA ();
</code>```

Inside play.java, I use the objects like this:

```<code>System.out.println ("Hitpoints[HP]: " + enemies [i].getHP ());
</code>```

and it works great because I included these two objects into the parameter of the method:

```<code>public static void start (player user, stats[] enemies)
</code>```

However, whenever I want to call start in the main method for it to do the things I want it to, it gives me errors. This is how I've been trying to call it:

```<code>public static void main (String[] args)
{ //main method
start(player, stats);
} //main method
</code>```

Am I doing something wrong? Any help appreciated. I'll gladly add more information if needed. New to coding and not sure what specific details need to be provided.

My errors:

```<code>{ //main method
    player player = new player();
    start(player, stats);
} //main method
</code>```

Error on: start(player, stats);
Cannot find symbol. Symbol: variable stats. Location: class play.

This error is given when I hover over "stats" when using netbeans.

答:
Seems to me you have to create an instance of values.java and then get the player and stats objects from there to pass on to the main method. where are player, stats being declared in the play.java class?

try:

```<code>{
  player player = new player();
  stats[] stats = new stats[5];

  start(player, stats);
} //main method
</code>```

and initialize stats array with desired values

Body:
play.java: https://pastebin.com/4bzfE76z
values.java: https://pastebin.com/6mnUzKyA
player.java: https://pastebin.com/qiFymMF6
stats.java: https://pastebin.com/P24AUpXV

I have a method called start in play.java with object parameters. The objects were originally declared in values.java inside the sValues method. I want to call the method start to the main method of play.java but I'm not sure what to write inside the parameters of the call.

Inside values.java:

    player user = new player ();
    user.setP_Name (username);
    user.setP_ATK (atk);
    user.setP_HP (hp);

    stats[] enemies = new stats [3];
    enemies [1] = new stats ();
    enemies [1] = gob;
    enemies [1].getName ();
    enemies [1].getHP ();
    enemies [1].getATK ();
    enemies [1].getMANA ();
    enemies [2] = new stats ();
    enemies [2] = orc;
    enemies [2].getName ();
    enemies [2].getHP ();
    enemies [2].getATK ();
    enemies [2].getMANA ();

Inside play.java, I use the objects like this:

System.out.println ("Hitpoints[HP]: " + enemies [i].getHP ());

and it works great because I included these two objects into the parameter of the method:

public static void start (player user, stats[] enemies)

However, whenever I want to call start in the main method for it to do the things I want it to, it gives me errors. This is how I've been trying to call it:

public static void main (String[] args)
{ //main method
start(player, stats);
} //main method

Am I doing something wrong? Any help appreciated. I'll gladly add more information if needed. New to coding and not sure what specific details need to be provided.

My errors:

{ //main method
    player player = new player();
    start(player, stats);
} //main method

Error on: start(player, stats);
Cannot find symbol. Symbol: variable stats. Location: class play.

This error is given when I hover over "stats" when using netbeans.

Body:
Seems to me you have to create an instance of values.java and then get the player and stats objects from there to pass on to the main method. where are player, stats being declared in the play.java class?

try:

{
  player player = new player();
  stats[] stats = new stats[5];

  start(player, stats);
} //main method

and initialize stats array with desired values


问:
how to convert a list into a list of tuples?
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas
```

<p>Here's what I have done to read the file but I have no idea how to put them into a list of tuples</p>

```def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent
```

Here's what the output is supposed to be:

答:
Given the lines as you're reading them from the file, the following will work:

```<code>def process_lines(lines):
    result = []
    for line in lines:
        parts = line.strip().split(" ")
        result.append(tuple(int(parts[0]), parts[1]))
    return result
</code>```

A list comprehension is possible here, but it requires a lot of straining. Use listcomps when they simplify your code, avoid them when they make it more complicated. (or when they require you to calculate the same value twice)

Body:
Here's what I have in the text file:

1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas

Here's what I have done to read the file but I have no idea how to put them into a list of tuples

def readRecords(filepath):
    file = open('Students1.txt', 'r')
    filecontent = file.readlines()
    file.close()
    return filecontent

Here's what the output is supposed to be:

Body:
Given the lines as you're reading them from the file, the following will work:

def process_lines(lines):
    result = []
    for line in lines:
        parts = line.strip().split(" ")
        result.append(tuple(int(parts[0]), parts[1]))
    return result

A list comprehension is possible here, but it requires a lot of straining. Use listcomps when they simplify your code, avoid them when they make it more complicated. (or when they require you to calculate the same value twice)


问:
Here api integration react native mobile app
Has anyone tried to use the Here API https://developer.here.com/develop/javascript-api in a react native mobile app? Can the Javascript of Here api be used in a react native mobile app? I am thinking if this is possible or need to use the mobile SDKs.</p>

答: Please go through this https://www.npmjs.com/package/react-native-heremaps it would lead to a solution for android part only.</p>

ContentLicense: CC BY-SA 4.0


问:
ASP.NET MVC: How do you get the current URL of the page in the view?
This is probably easy, although I cant seem to find the solution.
In my view I have links in a partial view which acts as a menu.
I need to apply an active class to the anchors if they are the page currently being viewed.

What I therefore need is a quick and simple method of checking the href of the link against the url of the page?

Any takers? :)

答:
```<code>RouteData.GetRequiredString("action")
</code>```

will give you the action that was used to render this view. As far as good practices are concerned I would recommend you writing an HTML helper that will do the job instead of polluting your views with C#.

ContentLicense: CC BY-SA 2.5

Body:
RouteData.GetRequiredString("action")

will give you the action that was used to render this view. As far as good practices are concerned I would recommend you writing an HTML helper that will do the job instead of polluting your views with C#.


Title: In bash how to transform multimap<K,V> to a map of <K, {V1,V2}>

Body:
I am processing output from a file in bash and need to group values by their keys.

For example, I have the

13,47099
13,54024
13,1
13,39956
13,0
17,126223
17,52782
17,4
17,62617
17,0
23,1022724
23,79958
23,80590
23,230
23,1
23,118224
23,0
23,1049
42,72470
42,80185
42,2
42,89199
42,0
54,70344
54,72824
54,1
54,62969
54,1

in a file and group all values from a particular key into a single line as in

13,47099,54024,1,39956,0
17,126223,52782,4,62617,0
23,1022724,79958,80590,230,1,118224,0,1049
42,72470,80185,2,89199,0
54,70344,72824,1,62969,1

There are about 10000 entries in my input file. How do I transform this data in shell ?

Body:
awk to the rescue!

assuming keys are contiguous...

$ awk -F, 'p!=$1 {if(a) print a; a=p=$1}
                 {a=a FS $2}
           END   {print a}' file

13,47099,54024,1,39956,0
17,126223,52782,4,62617,0
23,1022724,79958,80590,230,1,118224,0,1049
42,72470,80185,2,89199,0
54,70344,72824,1,62969,1


问:
Export command in Jenkins pipeline
How to add an 'export' unix command in a Jenkins pipeline?
I have a Jenkins 'stage' and 'steps' within it. What is the syntax for an export command. I need to set the environment variable 'PATH' using the export command. </p>

答:
You can update the $PATH like this:

```<code>pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {

        // JENKINSHOME is just a name to help readability
        withEnv(['PATH+JENKINSHOME=/home/jenkins/bin']) {
          echo "PATH is: $PATH"
        }
      }
    }
  }
}
</code>```

When I run this the result is:

```<code>[Pipeline] echo
PATH is: /home/jenkins/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
</code>```

What the heck is this PATH+JENKINSHOME syntax? Quoting from a blog at designhammer.com:

This:

```<code>/my/additional/path:$PATH
</code>```

is expressed as:

```<code>PATH+ANYSTRING=/my/additional/path.
</code>```

ANYSTRING is just a name to help readability. If it doesn't help readability, in your view, you can omit it. So this is equivalent:

```<code>PATH+=/my/additional/path
</code>```

The above (withEnv) allows you to update the $PATH for a specific part of your pipeline. To update the $PATH for the entire pipeline, you can't use the PATH+ANYSTRING syntax, but this works:

```<code>pipeline {
  agent { label 'docker' }
  environment {
    PATH = "/hot/new/bin:$PATH"
  }
  stages {
    stage ('build') {
      steps {
        echo "PATH is: $PATH"
      }
    }
  }
}
</code>```

Produces output:

```<code>[Pipeline] echo
PATH is: /hot/new/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
</code>```

Title: Export command in Jenkins pipeline

Body:
You can update the $PATH like this:

pipeline {
  agent { label 'docker' }
  stages {
    stage ('build') {
      steps {

        // JENKINSHOME is just a name to help readability
        withEnv(['PATH+JENKINSHOME=/home/jenkins/bin']) {
          echo "PATH is: $PATH"
        }
      }
    }
  }
}

When I run this the result is:

[Pipeline] echo
PATH is: /home/jenkins/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

What the heck is this PATH+JENKINSHOME syntax? Quoting from a blog at designhammer.com:

This:

/my/additional/path:$PATH

is expressed as:

PATH+ANYSTRING=/my/additional/path.

ANYSTRING is just a name to help readability. If it doesn't help readability, in your view, you can omit it. So this is equivalent:

PATH+=/my/additional/path

The above (withEnv) allows you to update the $PATH for a specific part of your pipeline. To update the $PATH for the entire pipeline, you can't use the PATH+ANYSTRING syntax, but this works:

pipeline {
  agent { label 'docker' }
  environment {
    PATH = "/hot/new/bin:$PATH"
  }
  stages {
    stage ('build') {
      steps {
        echo "PATH is: $PATH"
      }
    }
  }
}

Produces output:

[Pipeline] echo
PATH is: /hot/new/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games


问:
Can c declare two function with the same name, return type but different parameters
Why the following code can be compiled by gcc

```<code>#include <stdio.h>
int func();
int func(int a) { return 1; }
int main() {
   func(10);
   return 0;
}
</code>```

But if i add char func();, gcc say conflicting types for ‘func’

答:
This is not an overload, because you cannot call func() with no arguments. This is a special case of a single function with compatible function declarators, as described in the standard:

If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions.

Changing return type from int to char is one way to break this rule. Another way to break it is to supply a parameter type other than int:

```<code>int func();
int func(char a) { return 1; } // Does not compile
</code>```

If you would like to declare a function that does not take any parameters, the declarator should be as follows:

```<code>int func(void);
</code>```

Now declaring a func that takes an int will result in compile-time error:

```<code>int func(void);
int func(int a) { return 1; } // Does not compile
</code>```

Body:
Why the following code can be compiled by gcc

#include <stdio.h>
int func();
int func(int a) { return 1; }
int main() {
   func(10);
   return 0;
}

But if i add char func();, gcc say conflicting types for ‘func’

Body:
This is not an overload, because you cannot call func() with no arguments. This is a special case of a single function with compatible function declarators, as described in the standard:

If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions.

Changing return type from int to char is one way to break this rule. Another way to break it is to supply a parameter type other than int:

int func();
int func(char a) { return 1; } // Does not compile

If you would like to declare a function that does not take any parameters, the declarator should be as follows:

int func(void);

Now declaring a func that takes an int will result in compile-time error:

int func(void);
int func(int a) { return 1; } // Does not compile


问:
Google Sheets & Twilio Integration
I'm using this code from Greg Baugues (https://www.twilio.com/blog/2016/02/send-sms-from-a-google-spreadsheet.html) to send texts in bulk using Google sheets and Twilio.

I want to tell sendSMS and/or sendAll to skip existing sheet entries where 'sent' appears in the relevant cell, so as to allow the sheet to function as a database as well as a mere messaging machine.

Any ideas?

(The XXX entries are simply to anonymize my Twilio account and phone number).

```<code>function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Send text msg to client", functionName:
"sendAll"}, ];
ss.addMenu("Text", menuEntries);

}

function sendSms(to, body) {
var messages_url = "https://api.twilio.com/2010-04-
01/Accounts/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json";

var payload = {
"To": to,
"Body" : body,
"From" : "+XXXXXXXXXX"
};

var options = {
"method" : "post",
"payload" : payload
};

options.headers = {
"Authorization" : "Basic " +

Utilities.base64Encode
("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
};

UrlFetchApp.fetch(messages_url, options);
}

function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 4)
var data = dataRange.getValues();

for (i in data) {
var row = data[i];
try {
  response_data = sendSms(row[1], row[2]);
  status = "sent";
} catch(err) {
  Logger.log(err);
  status = "error";
}
sheet.getRange(startRow + Number(i), 4).setValue(status);
}
}

function myFunction() {
sendAll();
}
</code>```

答:
This works (thanks Andy):    </p>

```<code>function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 5)
var data = dataRange.getValues();

for (i in data) {

var status;

var row = data[i];
if (row[3] !== "sent") {
  try {
    response_data = sendSms(row[1], row[2]);
    status = "sent";
  } catch(err) {
    Logger.log(err);
     status = "error";
  }
    }
    sheet.getRange(startRow + Number(i), 4).setValue(status);
}
}
</code>```

Title: Google Sheets & Twilio Integration

Body:
I'm using this code from Greg Baugues (https://www.twilio.com/blog/2016/02/send-sms-from-a-google-spreadsheet.html) to send texts in bulk using Google sheets and Twilio.

I want to tell sendSMS and/or sendAll to skip existing sheet entries where 'sent' appears in the relevant cell, so as to allow the sheet to function as a database as well as a mere messaging machine.

Any ideas?

(The XXX entries are simply to anonymize my Twilio account and phone number).

function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Send text msg to client", functionName:
"sendAll"}, ];
ss.addMenu("Text", menuEntries);

}

function sendSms(to, body) {
var messages_url = "https://api.twilio.com/2010-04-
01/Accounts/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages.json";

var payload = {
"To": to,
"Body" : body,
"From" : "+XXXXXXXXXX"
};

var options = {
"method" : "post",
"payload" : payload
};

options.headers = {
"Authorization" : "Basic " +

Utilities.base64Encode
("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
};

UrlFetchApp.fetch(messages_url, options);
}

function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 4)
var data = dataRange.getValues();

for (i in data) {
var row = data[i];
try {
  response_data = sendSms(row[1], row[2]);
  status = "sent";
} catch(err) {
  Logger.log(err);
  status = "error";
}
sheet.getRange(startRow + Number(i), 4).setValue(status);
}
}

function myFunction() {
sendAll();
}

Body:
This works (thanks Andy):

function sendAll() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 5)
var data = dataRange.getValues();

for (i in data) {

var status;

var row = data[i];
if (row[3] !== "sent") {
  try {
    response_data = sendSms(row[1], row[2]);
    status = "sent";
  } catch(err) {
    Logger.log(err);
     status = "error";
  }
    }
    sheet.getRange(startRow + Number(i), 4).setValue(status);
}
}


问:
Why does C# disallow readonly local variables?
Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?</p>

答: Readonly means the only place the instance variable can be set is in the constructor.  When declaring a variable locally it doesn't have an instance (it's just in scope), and it can't be touched by the constructor.</p>

OwnerDisplayName: Brian Genisio

OwnerDisplayName: JPunyon

LastEditorDisplayName: JPunyon


问:
How To Dynamically Create ViewFlow Processes?
I'm trying to set up a service so that a user could feasibly build their own workflows through a GUI or otherwise easy-to-use interface.

When I try anonymously creating nodes and then referring to them by their position in a list, I get stuck - this.nodes[0] (where nodes is the list storing the anonymous nodes) fails because "this" isn't iterable, this.(nodes[0]) is invalid syntax, and nodes[0] (sans this) returns a NoneType object.

How can I go about dynamically generating nodes?

答: There is no such functionality in the Viewflow.</p>


问:
Connect website form to (compiled) java / common lisp program (website as UI)

What I know    (with regard to what might be relevant to my problem)

Java, some Common Lisp, HTML5 and basic JavaScript.

What I have so far

Two finished programs, one written in Java and one written in Common Lisp.
(which both parse an input string from the prompt or a file and, if valid, do some calculations and return a result string.)

A rudimentary Website (on a freehoster) including some text input forms and submit buttons.

What I'd like to know

Is it possible (and if so: how?) to connect my website to my (compiled) programs?

More precisely:

I want to offer the functionality of my programs to visitors of my website.
As you can guess the visitor should be able to enter the data in a text field (e.g. a <textarea>), submit it and my website sends/feeds the data to my program to process it.
The output of the program should then be displayed on the website.

I thought this would be a pretty ordinary task but googling it just left me confused and disillusioned. (It seems I have to do something "on the server-side", use PHP and frameworks and what not.)

I just don't know what to do next.

Maybe I'm searching with the wrong target words (english not being my mother tongue) or maybe I just can't see the wood for the trees, but I'm a bit lost and it don't know where to go next. Learn php? Read about "server-side"? Familiarize myself with framework foo?

Therefore I would be really grateful for some clear advice on how to proceed from here, i.e.: How do I connect those different worlds (my basic website with the funcionality of my programs)?

What is my next step?

Does someone happen to know a good book / tutorial / youtube video regarding this next step?

Or, if this is asking too much (if so, I apologize, but I simply don't know how small or big the problem is that I am describing) maybe some keywords to point me in the right direction so that I can google "tutorial for foo" or "book on bar"
(so that I know I'm getting somewhere when I work through this tutorial/book).

I very much appreciate any concrete help.

答:
A PHP page can run external applications, so if your programs can be run from a terminal session / shell you can probably get them to run in PHP.

You can use the exec() command, see the PHP manual page for it -  http://php.net/manual/en/function.exec.php

```<code>echo exec('whoami');
</code>```

Or you can build a command line and run that through the shell using backticks  (``) or shell_exec like this:

```<code>$zip_cmd = "zip -D $tmp_folder$zip_file_1 subfolder/*";
$result = `$zip_cmd`;
</code>```

Body:
A PHP page can run external applications, so if your programs can be run from a terminal session / shell you can probably get them to run in PHP.

You can use the exec() command, see the PHP manual page for it -  http://php.net/manual/en/function.exec.php

echo exec('whoami');

Or you can build a command line and run that through the shell using backticks  (``) or shell_exec like this:

$zip_cmd = "zip -D $tmp_folder$zip_file_1 subfolder/*";
$result = `$zip_cmd`;


问:
iOS FMDB multithreading operation failure
yep,i try to operation database in multi-thread with fmdb.
i create a timer to work to query database with 1.5s interval in child thread.
in the same time , it may operation the database in main-thread with delete,add,edit operation.
i find the delete add edit operation may fail if the query is operating.it say the database is locked.
i dont know how fmdb work in multi-thread,this is my code:

```<code>-(NSArray *)list{

NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
NSMutableArray *list = [NSMutableArray array];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    FMResultSet *set = [db executeQuery:@"SELECT * FROM t_messagesCache ORDER BY triggerTime ASC;"];

    while (set.next) {

        MXNIMMessageModel *message = [MXNIMMessageModel new];
        message.msgType = [set intForColumn:@"msgType"];
        message.uid = [set stringForColumn:@"uid"];
        message.msg = [set stringForColumn:@"msg"];
        message.nickname = [set stringForColumn:@"nickname"]; ;
        message.name = [set stringForColumn:@"name"];
        message.url = [set stringForColumn:@"url"];
        message.ext = [set stringForColumn:@"ext"];
        message.dur = [set intForColumn:@"dur"];
        message.w = [set intForColumn:@"w"];
        message.h = [set intForColumn:@"h"];
        message.size = [set intForColumn:@"size"];
        message.lastInterval = [set intForColumn:@"lastInterval"];
        message.md5 = [set stringForColumn:@"md5"];
        message.sort = [set intForColumn:@"sort"];
        message.triggerTime = [set stringForColumn:@"triggerTime"];
        message.teamId = [set stringForColumn:@"teamId"];

        [list addObject:message];

    }
    [db close];

}];
return list;
</code>```

}

```<code>- (BOOL)deleteMessageModelByUid:(NSString *)uid
</code>```

{

```<code>__block BOOL result;
NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    result = [db executeUpdateWithFormat:@"DELETE FROM t_messagesCache WHERE uid = %@",uid];
    [db close];
}];

return result;
</code>```

}

答:
You can use GCD SERIAL QUEUE to keep all FBMD operations on a thread.

First, define a global serial queue:

```<code>@interface ExampleClass
@property(nonatomic,strong) dispatch_queue_t queue;
@end

@implementation ExampleClass
//......
- (dispatch_queue_t)queue {
    if (_queue != nil) {
        _queue = dispatch_queue_create("SERIAL_QUEUE", DISPATCH_QUEUE_SERIAL);
    }
    return _queue;
}
//......
@end
</code>```

Then, operation FMDB in the queue, that will keep all operation on a thread:

```<code>//For list
dispatch_async(self.queue, ^{
    //NSArray *list = [yourObjectForFMDB list];
    dispatch_async(dispatch_get_main_queue(), ^{
        //do UI operation with list
    });
});

//For deleting
dispatch_async(self.queue, ^{
    //[yourObjectForFMDB deleteMessageModelByUid:@"1"];
});
</code>```

Theory：dispatch_async will create a new thread to do the task, and a SERIAL QUEUE makes sure there is only one thread created.

The ExampleClass here could be a singleton for global usage.

Body:
yep,i try to operation database in multi-thread with fmdb.
i create a timer to work to query database with 1.5s interval in child thread.
in the same time , it may operation the database in main-thread with delete,add,edit operation.
i find the delete add edit operation may fail if the query is operating.it say the database is locked.
i dont know how fmdb work in multi-thread,this is my code:

-(NSArray *)list{

NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
NSMutableArray *list = [NSMutableArray array];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    FMResultSet *set = [db executeQuery:@"SELECT * FROM t_messagesCache ORDER BY triggerTime ASC;"];

    while (set.next) {

        MXNIMMessageModel *message = [MXNIMMessageModel new];
        message.msgType = [set intForColumn:@"msgType"];
        message.uid = [set stringForColumn:@"uid"];
        message.msg = [set stringForColumn:@"msg"];
        message.nickname = [set stringForColumn:@"nickname"]; ;
        message.name = [set stringForColumn:@"name"];
        message.url = [set stringForColumn:@"url"];
        message.ext = [set stringForColumn:@"ext"];
        message.dur = [set intForColumn:@"dur"];
        message.w = [set intForColumn:@"w"];
        message.h = [set intForColumn:@"h"];
        message.size = [set intForColumn:@"size"];
        message.lastInterval = [set intForColumn:@"lastInterval"];
        message.md5 = [set stringForColumn:@"md5"];
        message.sort = [set intForColumn:@"sort"];
        message.triggerTime = [set stringForColumn:@"triggerTime"];
        message.teamId = [set stringForColumn:@"teamId"];

        [list addObject:message];

    }
    [db close];

}];
return list;

}

- (BOOL)deleteMessageModelByUid:(NSString *)uid

{

__block BOOL result;
NSString *path = [[PathHelper cachePath] stringByAppendingString:@"/MessagesCache.db"];
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
[queue inDatabase:^(FMDatabase *db) {
    [db open];
    result = [db executeUpdateWithFormat:@"DELETE FROM t_messagesCache WHERE uid = %@",uid];
    [db close];
}];

return result;

}

Body:
You can use GCD SERIAL QUEUE to keep all FBMD operations on a thread.

First, define a global serial queue:

@interface ExampleClass
@property(nonatomic,strong) dispatch_queue_t queue;
@end

@implementation ExampleClass
//......
- (dispatch_queue_t)queue {
    if (_queue != nil) {
        _queue = dispatch_queue_create("SERIAL_QUEUE", DISPATCH_QUEUE_SERIAL);
    }
    return _queue;
}
//......
@end

Then, operation FMDB in the queue, that will keep all operation on a thread:

//For list
dispatch_async(self.queue, ^{
    //NSArray *list = [yourObjectForFMDB list];
    dispatch_async(dispatch_get_main_queue(), ^{
        //do UI operation with list
    });
});

//For deleting
dispatch_async(self.queue, ^{
    //[yourObjectForFMDB deleteMessageModelByUid:@"1"];
});

Theory：dispatch_async will create a new thread to do the task, and a SERIAL QUEUE makes sure there is only one thread created.

The ExampleClass here could be a singleton for global usage.


问:
Is installing PHP on Cygwin just like it being on a real Linux server?
I currently use XAMPP on Windows 7 for my dev server which is a LAMP stack.

I recently installed cygwin and have been messing around with it.  I am just curious, with cygwin since it is like unix/linux does that mean that you can install apache and php just as if you were installing it on a Linux server?  I know you can install them on cygwin as I saw them in a package list but I'm not sure if this is the same as if I was installing it on a real production linux server?

From what I read cygwin mimics unix/linux on windows.

答:
The old question (and old answers) are still functional these days. However, I thought it'd be worth to add that, right now (June 2017), this became much simpler under Cygwin. Don't know if it has to do with Apache or PHP 7 changing something, but anyway I didn't have to follow lots of tutorials for my initial configuration.

Now it's really just a matter of running Cygwin setup, and selecting packages httpd, php, httpd-mod_php7, php-mysqli and mysql-server (in fact, some additional dependent packages will also be selected by Cygwin - and it will ask you for your confirmation, as you might already know).

When you next go to Cygwin console, you just need to apachectl start, and there it is readily available on port 80. If you need it as an all-time available server, configuring server is still the same with cygserver-config.

No apt-cyg needed, or importing packages from Cygwin Ports - although it's also great and still works beautifully. It just became a bit simpler.


答:
to start the i values from 1 instead of 0, use a starting value of 1 instead of 0

to start the j values from 0 instead of 20, do the add after the output instead of before -- or instead of using a separate variable j just compute it from i

don't open the file 502 times; once is enough

to convert j to decimal with leading zeros the simplest way by far is to use formatted output with the Iw.m specifier, and formatted output is also a somewhat easier way of doing the rest of what you want

Program:

```<code>program SO44379759
  implicit none
  integer :: i
  open(300,file='in')
  ! j=0
  do i=1,501
    ! j=j+20
    write(300,'(a,i0,a,i14.14,a)') "filein(",i,")='box_01_step_",(i-1)*20,".pdb'"
  end do
  close(300)
end program
</code>```

Output:

```<code>filein(1)='box_01_step_00000000000000.pdb'
filein(2)='box_01_step_00000000000020.pdb'
filein(3)='box_01_step_00000000000040.pdb'
filein(4)='box_01_step_00000000000060.pdb'
filein(5)='box_01_step_00000000000080.pdb'
filein(6)='box_01_step_00000000000100.pdb'
filein(7)='box_01_step_00000000000120.pdb'
filein(8)='box_01_step_00000000000140.pdb'
filein(9)='box_01_step_00000000000160.pdb'
filein(10)='box_01_step_00000000000180.pdb'
filein(11)='box_01_step_00000000000200.pdb'
filein(12)='box_01_step_00000000000220.pdb'
filein(13)='box_01_step_00000000000240.pdb'
filein(14)='box_01_step_00000000000260.pdb'
filein(15)='box_01_step_00000000000280.pdb'
filein(16)='box_01_step_00000000000300.pdb'
filein(17)='box_01_step_00000000000320.pdb'
filein(18)='box_01_step_00000000000340.pdb'
filein(19)='box_01_step_00000000000360.pdb'
filein(20)='box_01_step_00000000000380.pdb'
</code>```

Title: Counting in sentence

Body:
I'm trying to write a code to get the following format

filein(i)='box_01_step_000000000000j.pdb'

the output should be like:

filein(1)='box_01_step_00000000000000.pdb'
filein(2)='box_01_step_00000000000020.pdb'
filein(3)='box_01_step_00000000000040.pdb'
filein(4)='box_01_step_00000000000060.pdb'
filein(5)='box_01_step_00000000000080.pdb'
filein(6)='box_01_step_00000000000100.pdb'
filein(7)='box_01_step_00000000000120.pdb'
filein(8)='box_01_step_00000000000140.pdb'
filein(9)='box_01_step_00000000000160.pdb'
filein(10)='box_01_step_00000000000180.pdb'
filein(11)='box_01_step_00000000000200.pdb'

My code is

program main
implicit none
 integer :: i,n,j
 character(4):: filein,box,step,pdb
 do i = 0, 501
    open (300,file='in')
 end do
 j=0
 do i = 0, 501
  j=j+20
  WRITE(300,*) "'filein'",'"("',(i),'")"',"'='","'box_01_step_'","'000000000000'",j,"'.pdb'"
 enddo
 close (300)
end program

I got

 'filein'"("           0 ")"'=''box_01_step_''000000000000'          20 '.pdb'
 'filein'"("           1 ")"'=''box_01_step_''000000000000'          40 '.pdb'
 'filein'"("           2 ")"'=''box_01_step_''000000000000'          60 '.pdb'
 'filein'"("           3 ")"'=''box_01_step_''000000000000'          80 '.pdb'

How I can make it

filein(1)='box_01_step_00000000000000.pdb'
filein(2)='box_01_step_00000000000020.pdb'
filein(3)='box_01_step_00000000000040.pdb'

Body:
to start the i values from 1 instead of 0, use a starting value of 1 instead of 0

to start the j values from 0 instead of 20, do the add after the output instead of before -- or instead of using a separate variable j just compute it from i

don't open the file 502 times; once is enough

to convert j to decimal with leading zeros the simplest way by far is to use formatted output with the Iw.m specifier, and formatted output is also a somewhat easier way of doing the rest of what you want

Program:

program SO44379759
  implicit none
  integer :: i
  open(300,file='in')
  ! j=0
  do i=1,501
    ! j=j+20
    write(300,'(a,i0,a,i14.14,a)') "filein(",i,")='box_01_step_",(i-1)*20,".pdb'"
  end do
  close(300)
end program

Output:

filein(1)='box_01_step_00000000000000.pdb'
filein(2)='box_01_step_00000000000020.pdb'
filein(3)='box_01_step_00000000000040.pdb'
filein(4)='box_01_step_00000000000060.pdb'
filein(5)='box_01_step_00000000000080.pdb'
filein(6)='box_01_step_00000000000100.pdb'
filein(7)='box_01_step_00000000000120.pdb'
filein(8)='box_01_step_00000000000140.pdb'
filein(9)='box_01_step_00000000000160.pdb'
filein(10)='box_01_step_00000000000180.pdb'
filein(11)='box_01_step_00000000000200.pdb'
filein(12)='box_01_step_00000000000220.pdb'
filein(13)='box_01_step_00000000000240.pdb'
filein(14)='box_01_step_00000000000260.pdb'
filein(15)='box_01_step_00000000000280.pdb'
filein(16)='box_01_step_00000000000300.pdb'
filein(17)='box_01_step_00000000000320.pdb'
filein(18)='box_01_step_00000000000340.pdb'
filein(19)='box_01_step_00000000000360.pdb'
filein(20)='box_01_step_00000000000380.pdb'


问:
Use a clojure macro to automatically create getters and setters inside a reify call
I am trying to implement a huge Java interface with numerous (~50) getter and setter methods (some with irregular names). I thought it would be nice to use a macro to reduce the amount of code. So instead of

```<code>(def data (atom {:x nil}))
(reify HugeInterface
  (getX [this] (:x @data))
  (setX [this v] (swap! data assoc :x v)))
</code>```

I want to be able to write

```<code>(def data (atom {:x nil}))
(reify HugeInterface
  (set-and-get getX setX :x))
</code>```

Is this set-and-get macro (or something similar) possible? I haven't been able to make it work.

答: The point is reify being a macro itself which is expanded before your own set-and-get macro - so the set-and-get approach doesn't work. So, instead of an inner macro inside reify, you need a macro on the "outside" that generates the reify, too.</p>

Body:
I am trying to implement a huge Java interface with numerous (~50) getter and setter methods (some with irregular names). I thought it would be nice to use a macro to reduce the amount of code. So instead of

(def data (atom {:x nil}))
(reify HugeInterface
  (getX [this] (:x @data))
  (setX [this v] (swap! data assoc :x v)))

I want to be able to write

(def data (atom {:x nil}))
(reify HugeInterface
  (set-and-get getX setX :x))

Is this set-and-get macro (or something similar) possible? I haven't been able to make it work.


问:
Polymorphic JSON unmarshalling of embedded structs
Here is an example (see also https://play.golang.org/p/or7z4Xc8tN):

```<code>package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    X string
    Y int
}

type B struct {
    A
    Y string
}

func main() {
    data := []byte(`{"X": "me", "Y": "hi"}`)
    b := &B{}
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)

    b = &B{}
    data = []byte(`{"X": "me", "Y": 123}`)
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)
}
</code>```

Which outputs:

```<code>&{{me 0} hi}
{me 0}
&{{me 0} }
{me 0}
</code>```

Is there a way to polymorphically unmarshal the field Y to either an int or a string? Or even unmarshal into A.Y at all since B.Y is defined?

I know some might suggest unmarshalling with something like json.Unmarshall(data, &b.A), but I don't know if I can fit that into my current design.

答:
As pointed by Adrian, Go does not support polymorphism through struct embedding. interface{} is the only way to hold any type of golang variable. However, in your case you can implement custom Unmarshaler to decode the JSON stream to a struct utilizing json.Number or interface{}.  Below is implementation using json.Number. For more generic interface{} version, you can implement it as suggested by Adrian.

```<code>func (b *B) UnmarshalJSON(js []byte) error {
    //First: decode stream to anonymous struct
    v := struct {
        X string
        Y json.Number
    }{}

    err := json.Unmarshal(js, &v)
    if err != nil {
        return err
    }

    //Depends on the v.Y value, choose the holder variable
    //If it's convertible to number, assign to A.Y
    //otherwise, assign it to b.Y
    b.X = v.X
    if fv, err := v.Y.Float64(); err == nil {
        b.A.Y = int(fv)
    } else {
        b.Y = v.Y.String()
    }

    return nil
}
</code>```

Working example can be found in The Go Playground.

Body:
Here is an example (see also https://play.golang.org/p/or7z4Xc8tN):

package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    X string
    Y int
}

type B struct {
    A
    Y string
}

func main() {
    data := []byte(`{"X": "me", "Y": "hi"}`)
    b := &B{}
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)

    b = &B{}
    data = []byte(`{"X": "me", "Y": 123}`)
    json.Unmarshal(data, b)
    fmt.Println(b)
    fmt.Println(b.A)
}

Which outputs:

&{{me 0} hi}
{me 0}
&{{me 0} }
{me 0}

Is there a way to polymorphically unmarshal the field Y to either an int or a string? Or even unmarshal into A.Y at all since B.Y is defined?

I know some might suggest unmarshalling with something like json.Unmarshall(data, &b.A), but I don't know if I can fit that into my current design.

Body:
As pointed by Adrian, Go does not support polymorphism through struct embedding. interface{} is the only way to hold any type of golang variable. However, in your case you can implement custom Unmarshaler to decode the JSON stream to a struct utilizing json.Number or interface{}.  Below is implementation using json.Number. For more generic interface{} version, you can implement it as suggested by Adrian.

func (b *B) UnmarshalJSON(js []byte) error {
    //First: decode stream to anonymous struct
    v := struct {
        X string
        Y json.Number
    }{}

    err := json.Unmarshal(js, &v)
    if err != nil {
        return err
    }

    //Depends on the v.Y value, choose the holder variable
    //If it's convertible to number, assign to A.Y
    //otherwise, assign it to b.Y
    b.X = v.X
    if fv, err := v.Y.Float64(); err == nil {
        b.A.Y = int(fv)
    } else {
        b.Y = v.Y.String()
    }

    return nil
}

Working example can be found in The Go Playground.


问:
Converting DateTimes between timezones
This is thoroughly confusing me. I have tried in multiple ways to convert a datetime string of 2017-06-04 00:00:00 (America/New_York) to the Europe/London timezone, which should be I believe with current daylight savings 6am?

The whole concept of the dates and conversion is baffling me, I simply seem to misunderstand, or not get the simple principles, this picture demonstrates the current code i have and the results im getting.

I simply want to be able to give a function, a datetime string and what timezone it belongs too and give it a timezone I want it in and get a string back of the adjusted datetime, but I am getting stuff which is 4 minutes out etc..

```<code>from datetime import datetime
import pytz
import arrow

#Calc Timezone Offsets

def adjust_timezone(datetime_string, input_tz, output_tz, formatter="%Y-%m-
%d %H:%M:%S"):
    print datetime_string
    # Now we make datetime naive datetime
    date_to_convert = datetime.strptime(datetime_string, formatter)
    a = arrow.get(datetime_string, 'YYYY-M-D HH:mm:ss').replace(tzinfo=pytz.utc)
    print a.to(output_tz).format('YYYY-M-D HH:mm:ss')

    # Make it tz aware
    date_to_convert = date_to_convert.replace(tzinfo=pytz.timezone(input_tz))
    print date_to_convert
    date_to_convert = date_to_convert.astimezone(pytz.timezone(input_tz))
    print date_to_convert

    # Convert it
    output_datetime = date_to_convert.astimezone(pytz.timezone(output_tz))
    print output_datetime

    # Make tz unaware again
    output_datetime = output_datetime.replace(tzinfo=None)

    return str(output_datetime)

print adjust_timezone('2017-06-04 00:00:00', "America/New_York", "Europe/London")
</code>```

The above when run return the following results:

```<code>2017-06-04 00:00:00
2017-6-4 01:00:00
2017-06-04 00:00:00-04:56
2017-06-04 00:00:00-04:56
2017-06-04 05:56:00+01:00
2017-06-04 05:56:00
</code>```

答:
Although arrow is a fine library, we don't really need it here.  Instead we will use datetime and pytz for this.  The key elements are pytz.timezone().localize() and datetime.datetime.astimezone()

Code:

```<code>def adjust_timezone(datetime_string, input_tz, output_tz,
                    formatter="%Y-%m-%d %H:%M:%S"):
    # Now we make datetime naive datetime
    naive = dt.datetime.strptime(datetime_string, formatter)

    # this time stamp is from the input_tz
    with_input_tz = pytz.timezone(input_tz).localize(naive)

    # now express the timestamp as output_tz
    with_output_tz = with_input_tz.astimezone(pytz.timezone(output_tz))
    return with_output_tz
</code>```

Test Code:

```<code>import datetime as dt
import pytz

print(adjust_timezone(
    '2017-06-04 00:00:00', "America/New_York", "Europe/London"))
</code>```

Results:

```<code>2017-06-04 05:00:00+01:00
</code>```

Title: Converting DateTimes between timezones

Body:
This is thoroughly confusing me. I have tried in multiple ways to convert a datetime string of 2017-06-04 00:00:00 (America/New_York) to the Europe/London timezone, which should be I believe with current daylight savings 6am?

The whole concept of the dates and conversion is baffling me, I simply seem to misunderstand, or not get the simple principles, this picture demonstrates the current code i have and the results im getting.

I simply want to be able to give a function, a datetime string and what timezone it belongs too and give it a timezone I want it in and get a string back of the adjusted datetime, but I am getting stuff which is 4 minutes out etc..

from datetime import datetime
import pytz
import arrow

#Calc Timezone Offsets

def adjust_timezone(datetime_string, input_tz, output_tz, formatter="%Y-%m-
%d %H:%M:%S"):
    print datetime_string
    # Now we make datetime naive datetime
    date_to_convert = datetime.strptime(datetime_string, formatter)
    a = arrow.get(datetime_string, 'YYYY-M-D HH:mm:ss').replace(tzinfo=pytz.utc)
    print a.to(output_tz).format('YYYY-M-D HH:mm:ss')

    # Make it tz aware
    date_to_convert = date_to_convert.replace(tzinfo=pytz.timezone(input_tz))
    print date_to_convert
    date_to_convert = date_to_convert.astimezone(pytz.timezone(input_tz))
    print date_to_convert

    # Convert it
    output_datetime = date_to_convert.astimezone(pytz.timezone(output_tz))
    print output_datetime

    # Make tz unaware again
    output_datetime = output_datetime.replace(tzinfo=None)

    return str(output_datetime)

print adjust_timezone('2017-06-04 00:00:00', "America/New_York", "Europe/London")

The above when run return the following results:

2017-06-04 00:00:00
2017-6-4 01:00:00
2017-06-04 00:00:00-04:56
2017-06-04 00:00:00-04:56
2017-06-04 05:56:00+01:00
2017-06-04 05:56:00

Body:
Although arrow is a fine library, we don't really need it here.  Instead we will use datetime and pytz for this.  The key elements are pytz.timezone().localize() and datetime.datetime.astimezone()

Code:

def adjust_timezone(datetime_string, input_tz, output_tz,
                    formatter="%Y-%m-%d %H:%M:%S"):
    # Now we make datetime naive datetime
    naive = dt.datetime.strptime(datetime_string, formatter)

    # this time stamp is from the input_tz
    with_input_tz = pytz.timezone(input_tz).localize(naive)

    # now express the timestamp as output_tz
    with_output_tz = with_input_tz.astimezone(pytz.timezone(output_tz))
    return with_output_tz

Test Code:

import datetime as dt
import pytz

print(adjust_timezone(
    '2017-06-04 00:00:00', "America/New_York", "Europe/London"))

Results:

2017-06-04 05:00:00+01:00


问:
androidplot 1.4.3 redraw run-time analysis with JNI getY (idx) access
i did evaluate the run-time performance of a 6 XYSeries plot setup (500 X axis samples) on a nexus 7 2013 with simple synthesized sine waves in the getY (idx) functs and compared it to a JNI getY (idx) based setup where the JNI C++ code simply fetched the data from a buffer within the JNI capsule

here is a simplified setup for the synthesized sine wave generation (example shows one XYSeries)

```<code>public static int  DatCnt = 0 ;
       static long DatSav ;

@Override
public double GetY (int idx) // being called by super.getY (idx), which implements XYSeries
{
  long t0 = 0 ;

  if (DatCnt >    0) { DatCnt-- ; t0 = System.nanoTime () ; }
  if (DatCnt == 499)   DatSav   = t0 ;

  double dat = Sin (idx) * 45 + 50 ;

//if (DatCnt >    0 &&
//    DatCnt <   10) {
//  Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %d", (System.nanoTime () - t0) / 1000, DatCnt)) ;
//}
  if (DatCnt ==   1) {                                                                   ActPlotNew0.Tsum += t0 - DatSav ;
    Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %6d", (t0 - DatSav) / 1000, ActPlotNew0.Tsum / 1000)) ;
  }
  return dat ;
//return Sin (idx) * 45 + 50 ;
}
</code>```

and this is the android monitor output

```<code>06-04 16:14:40.707 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1493 y_523
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_23
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 233989457389
06-04 16:14:40.861 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  33874  33874
06-04 16:14:40.901 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  26428  60302
06-04 16:14:40.938 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24627  84930
06-04 16:14:40.974 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  25299 110229
06-04 16:14:41.010 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  24047 134277
06-04 16:14:41.046 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  25299 159576
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_517
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 272247
06-04 16:14:41.129 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  24322  24322
06-04 16:14:41.165 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  24536  48858
06-04 16:14:41.200 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24688  73547
06-04 16:14:41.236 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  24414  97961
06-04 16:14:41.271 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23895 121856
06-04 16:14:41.305 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  23834 145690
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_37
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 256622
06-04 16:14:41.387 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  23834  23834
06-04 16:14:41.429 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  30395  54229
06-04 16:14:41.473 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  28411  82641
06-04 16:14:41.507 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  23406 106048
06-04 16:14:41.542 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23803 129852
06-04 16:14:41.576 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  24108 153961
</code>```

a vertical scroll will start the loop with the DatUpd () functs being called periodically

```<code>public static long Tstart, Tsum ;

public synchronized void DataUpd ()
{

  LogI (String.format ("sum %d", (System.nanoTime () - Tstart) / 1000)) ;

  DataY_0.DatCnt = 500 ;
  DataY_1.DatCnt = 500 ;
  DataY_2.DatCnt = 500 ;
  DataY_3.DatCnt = 500 ;
  DataY_4.DatCnt = 500 ;
  DataY_5.DatCnt = 500 ;

  Tstart = System.nanoTime () ;
  Tsum   = 0 ;

  Plot.redraw () ;
}
</code>```

the "dat3 25299 110229" shows the exex times for each series (dat0 - dat5), whereas the 1st number is the individual time accumulation from the x-data 0 to 500, and the 2nd is a running time tally ... 25299 us for the dat3 series and 110299 us for dat0 to dat3 and so on ... an average data fetch time per ZYSeries is about 25 ms

the total sum of 272247 us is the time from the 1st DatUpd () call to the next one in the scroll operation ... i didn't have a hook into when the plot redraw process was complete

the total getY (idx) data fetch time for all 6 XYSeries is 159576 us and the total redraw cycle time 272247 us ... 272247 - 159576 = 112671 us

of course i do not have any idea of the percentage of the remaining time (after the fetch time) of 112671 us, which is androidplot time and which is scroll gesture processing

and now to the C++ JNI setup timing

```<code>06-04 17:09:39.783 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1620 y_497
06-04 17:09:39.881 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_16
06-04 17:09:39.882 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 25543273
06-04 17:09:39.947 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36865  36865
06-04 17:09:39.995 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36956  73822
06-04 17:09:40.032 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36224 110046
06-04 17:09:40.085 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  42205 152252
06-04 17:09:40.138 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  41778 194030
06-04 17:09:40.202 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  53955 247985
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_724
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 344085
06-04 17:09:40.293 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36956  36956
06-04 17:09:40.341 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36651  73608
06-04 17:09:40.377 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36315 109924
06-04 17:09:40.429 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  40954 150878
06-04 17:09:40.481 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  40802 191680
06-04 17:09:40.534 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41015 232696
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_4
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 329620
06-04 17:09:40.619 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36712  36712
06-04 17:09:40.666 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36499  73211
06-04 17:09:40.702 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36163 109375
06-04 17:09:40.779 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  63323 172698
06-04 17:09:40.836 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  42266 214965
06-04 17:09:40.888 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41259 256225
</code>```

comparison :

accumulated fetch time is 247985 us

the sine synthesized data fetches take an average 25 ms / series whereas the C++ JNI data fetches take about 40 ms ... 15 ms longer, an increase of 60 % over the sine wave synthesis example

the percentage of the getY (idx) synthesized sine wave generation time portion is unknown and so is what else is happening inside androidplot from one getY (idx) to the next one

25 ms / 500 x-samples is 50 us, 15 ms / 500 x-samples = 30 us   ... assuming that the sine calculation can't take the majority of the 50 us i would say that a single getY (idx) call processing, not counting the data fetch takes maybe 40 to 45 us ...

the C++ JNI data fetch time of 30 us is not lightning fast, but something i have to live with ... 30 us * 500 * 6 = 90 ms for the whole data fetch only portion ... i could do this 10 times / sec if the redraw wouldn't take any time

i use the FastLineAndPointRenderer.Formatter setup

```<code>public static FastLineAndPointRenderer.Formatter LineFormat (int color, int width, int dash, int spc)
{
  Paint paint = new Paint () ;
  paint.setColor (color) ;
  paint.setStyle (Paint.Style.STROKE) ;
  paint.setAntiAlias (false) ;
  paint.setStrokeWidth (PixelUtils.dpToPix (width)) ;
  paint.setPathEffect (new DashPathEffect (
                       new float [] { PixelUtils.dpToPix (dash), PixelUtils.dpToPix (spc) }, 0)) ;

  FastLineAndPointRenderer.Formatter line = new FastLineAndPointRenderer.Formatter (paint.getColor (), null, null) ;
  line.setLinePaint     (paint) ;
  line.setVertexPaint       (null) ;
  line.setPointLabelFormatter (null) ;

  return line ;
}
</code>```

please, can anyone shine a bit more light onto my setup and comment this paper

is there a way to speed it up and still sick with 500 x-points ... that's what's being used in QT on the desktop setup and it's zippy zippy fast

what can be improved and what additional info should i provide

i hope i do not have made too many typos ;)

答:
somehow i overlooked the size () function in the XYSeries providing the true x-data count of the plots ... was pretty late after 12 hours of coding ;)

below : synthesized sine wave getY (idx) timing data

```<code>dat0   2349   2349
dat1   2258   4608
dat2   2716   7324
dat3   2624   9948
dat4   2258  12207
dat5   2471  14678
sum 69396
</code>```

it takes now 69 ms for 50 x-samples and 6 plots of them, with 14 ms for all the getY (idx) fetches

below : C++ JNI getY (idx) data fetch timing data

```<code>rdif   3936   3936
rpm    4150   8087
tdif   3784  11871
ext0   4058  15930
ext1   4089  20019
raw2   4150  24169
sum 74432
</code>```

it takes now 74 ms for 50 x-samples and 6 plots of them with 24 ms for all the getY (idx) fetches

all the above so far has been done using the FastLineAndPointRenderer.Formatter which doesn't seem to care if the
setInterpolationParams is being used ... would make sense since we want to do it fast

```<code>FastLineAndPointRenderer.Formatter line = new FastLineAndPointRenderer.Formatter (paint.getColor (), null, null) ;
line.setLinePaint       (paint) ;
line.setVertexPaint     (null) ;
line.setPointLabelFormatter (null) ;
line.setInterpolationParams (new CatmullRomInterpolator.Params (10, CatmullRomInterpolator.Type.Centripetal)) ;
</code>```

the LineAndPointFormatter alone without the setInterpolationParams produces the same timing as the FastLineAndPointRenderer

one wonders about the differences between the LineAndPointFormatter and the FastLineAndPointRenderer.Formatter since this setup provides the same timing

```<code>LineAndPointFormatter line = new LineAndPointFormatter (paint.getColor (), null, null, null) ;
line.setLinePaint       (paint) ;
line.setVertexPaint     (null) ;
line.setPointLabelFormatter (null) ;
</code>```

but now, when you add the

```<code>line.setInterpolationParams (new CatmullRomInterpolator.Params (10, CatmullRomInterpolator.Type.Centripetal)) ;
</code>```

to the regular LineAndPointFormatter the interpolation sets in and the following timing is the result

```<code>dat0   2838   2838
dat1   3112   5950
dat2   2716   8666
dat3   3021  11688
dat4   2136  13824
dat5   2258  16082
sum 277618
</code>```

the getY (idx) timing seems the same, but the overall cycle time changed from 69 ms to 277 ms which makes sense since the interpolation of 50 x 6 points will take some time

i'm so far happy with my results and will use 50 instead of 500 x-data samples ... the JNI C++ code will either just return one value and skip 4 or average 5 of them together

maybe my humble anroidplot eval might help others with their androidplot design

Body:
i did evaluate the run-time performance of a 6 XYSeries plot setup (500 X axis samples) on a nexus 7 2013 with simple synthesized sine waves in the getY (idx) functs and compared it to a JNI getY (idx) based setup where the JNI C++ code simply fetched the data from a buffer within the JNI capsule

here is a simplified setup for the synthesized sine wave generation (example shows one XYSeries)

public static int  DatCnt = 0 ;
       static long DatSav ;

@Override
public double GetY (int idx) // being called by super.getY (idx), which implements XYSeries
{
  long t0 = 0 ;

  if (DatCnt >    0) { DatCnt-- ; t0 = System.nanoTime () ; }
  if (DatCnt == 499)   DatSav   = t0 ;

  double dat = Sin (idx) * 45 + 50 ;

//if (DatCnt >    0 &&
//    DatCnt <   10) {
//  Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %d", (System.nanoTime () - t0) / 1000, DatCnt)) ;
//}
  if (DatCnt ==   1) {                                                                   ActPlotNew0.Tsum += t0 - DatSav ;
    Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %6d", (t0 - DatSav) / 1000, ActPlotNew0.Tsum / 1000)) ;
  }
  return dat ;
//return Sin (idx) * 45 + 50 ;
}

and this is the android monitor output

06-04 16:14:40.707 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1493 y_523
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_23
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 233989457389
06-04 16:14:40.861 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  33874  33874
06-04 16:14:40.901 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  26428  60302
06-04 16:14:40.938 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24627  84930
06-04 16:14:40.974 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  25299 110229
06-04 16:14:41.010 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  24047 134277
06-04 16:14:41.046 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  25299 159576
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_517
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 272247
06-04 16:14:41.129 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  24322  24322
06-04 16:14:41.165 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  24536  48858
06-04 16:14:41.200 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24688  73547
06-04 16:14:41.236 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  24414  97961
06-04 16:14:41.271 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23895 121856
06-04 16:14:41.305 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  23834 145690
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_37
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 256622
06-04 16:14:41.387 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  23834  23834
06-04 16:14:41.429 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  30395  54229
06-04 16:14:41.473 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  28411  82641
06-04 16:14:41.507 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  23406 106048
06-04 16:14:41.542 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23803 129852
06-04 16:14:41.576 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  24108 153961

a vertical scroll will start the loop with the DatUpd () functs being called periodically

public static long Tstart, Tsum ;

public synchronized void DataUpd ()
{

  LogI (String.format ("sum %d", (System.nanoTime () - Tstart) / 1000)) ;

  DataY_0.DatCnt = 500 ;
  DataY_1.DatCnt = 500 ;
  DataY_2.DatCnt = 500 ;
  DataY_3.DatCnt = 500 ;
  DataY_4.DatCnt = 500 ;
  DataY_5.DatCnt = 500 ;

  Tstart = System.nanoTime () ;
  Tsum   = 0 ;

  Plot.redraw () ;
}

the "dat3 25299 110229" shows the exex times for each series (dat0 - dat5), whereas the 1st number is the individual time accumulation from the x-data 0 to 500, and the 2nd is a running time tally ... 25299 us for the dat3 series and 110299 us for dat0 to dat3 and so on ... an average data fetch time per ZYSeries is about 25 ms

the total sum of 272247 us is the time from the 1st DatUpd () call to the next one in the scroll operation ... i didn't have a hook into when the plot redraw process was complete

the total getY (idx) data fetch time for all 6 XYSeries is 159576 us and the total redraw cycle time 272247 us ... 272247 - 159576 = 112671 us

of course i do not have any idea of the percentage of the remaining time (after the fetch time) of 112671 us, which is androidplot time and which is scroll gesture processing

and now to the C++ JNI setup timing

06-04 17:09:39.783 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1620 y_497
06-04 17:09:39.881 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_16
06-04 17:09:39.882 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 25543273
06-04 17:09:39.947 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36865  36865
06-04 17:09:39.995 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36956  73822
06-04 17:09:40.032 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36224 110046
06-04 17:09:40.085 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  42205 152252
06-04 17:09:40.138 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  41778 194030
06-04 17:09:40.202 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  53955 247985
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_724
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 344085
06-04 17:09:40.293 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36956  36956
06-04 17:09:40.341 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36651  73608
06-04 17:09:40.377 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36315 109924
06-04 17:09:40.429 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  40954 150878
06-04 17:09:40.481 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  40802 191680
06-04 17:09:40.534 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41015 232696
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_4
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 329620
06-04 17:09:40.619 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36712  36712
06-04 17:09:40.666 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36499  73211
06-04 17:09:40.702 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36163 109375
06-04 17:09:40.779 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  63323 172698
06-04 17:09:40.836 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  42266 214965
06-04 17:09:40.888 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41259 256225

comparison :

accumulated fetch time is 247985 us

the sine synthesized data fetches take an average 25 ms / series whereas the C++ JNI data fetches take about 40 ms ... 15 ms longer, an increase of 60 % over the sine wave synthesis example

the percentage of the getY (idx) synthesized sine wave generation time portion is unknown and so is what else is happening inside androidplot from one getY (idx) to the next one

25 ms / 500 x-samples is 50 us, 15 ms / 500 x-samples = 30 us   ... assuming that the sine calculation can't take the majority of the 50 us i would say that a single getY (idx) call processing, not counting the data fetch takes maybe 40 to 45 us ...

the C++ JNI data fetch time of 30 us is not lightning fast, but something i have to live with ... 30 us * 500 * 6 = 90 ms for the whole data fetch only portion ... i could do this 10 times / sec if the redraw wouldn't take any time

i use the FastLineAndPointRenderer.Formatter setup

public static FastLineAndPointRenderer.Formatter LineFormat (int color, int width, int dash, int spc)
{
  Paint paint = new Paint () ;
  paint.setColor (color) ;
  paint.setStyle (Paint.Style.STROKE) ;
  paint.setAntiAlias (false) ;
  paint.setStrokeWidth (PixelUtils.dpToPix (width)) ;
  paint.setPathEffect (new DashPathEffect (
                       new float [] { PixelUtils.dpToPix (dash), PixelUtils.dpToPix (spc) }, 0)) ;

  FastLineAndPointRenderer.Formatter line = new FastLineAndPointRenderer.Formatter (paint.getColor (), null, null) ;
  line.setLinePaint     (paint) ;
  line.setVertexPaint       (null) ;
  line.setPointLabelFormatter (null) ;

  return line ;
}

please, can anyone shine a bit more light onto my setup and comment this paper

is there a way to speed it up and still sick with 500 x-points ... that's what's being used in QT on the desktop setup and it's zippy zippy fast

what can be improved and what additional info should i provide

i hope i do not have made too many typos ;)

Body:
somehow i overlooked the size () function in the XYSeries providing the true x-data count of the plots ... was pretty late after 12 hours of coding ;)

below : synthesized sine wave getY (idx) timing data

dat0   2349   2349
dat1   2258   4608
dat2   2716   7324
dat3   2624   9948
dat4   2258  12207
dat5   2471  14678
sum 69396

it takes now 69 ms for 50 x-samples and 6 plots of them, with 14 ms for all the getY (idx) fetches

below : C++ JNI getY (idx) data fetch timing data

rdif   3936   3936
rpm    4150   8087
tdif   3784  11871
ext0   4058  15930
ext1   4089  20019
raw2   4150  24169
sum 74432

it takes now 74 ms for 50 x-samples and 6 plots of them with 24 ms for all the getY (idx) fetches

all the above so far has been done using the FastLineAndPointRenderer.Formatter which doesn't seem to care if the
setInterpolationParams is being used ... would make sense since we want to do it fast

FastLineAndPointRenderer.Formatter line = new FastLineAndPointRenderer.Formatter (paint.getColor (), null, null) ;
line.setLinePaint       (paint) ;
line.setVertexPaint     (null) ;
line.setPointLabelFormatter (null) ;
line.setInterpolationParams (new CatmullRomInterpolator.Params (10, CatmullRomInterpolator.Type.Centripetal)) ;

the LineAndPointFormatter alone without the setInterpolationParams produces the same timing as the FastLineAndPointRenderer

one wonders about the differences between the LineAndPointFormatter and the FastLineAndPointRenderer.Formatter since this setup provides the same timing

LineAndPointFormatter line = new LineAndPointFormatter (paint.getColor (), null, null, null) ;
line.setLinePaint       (paint) ;
line.setVertexPaint     (null) ;
line.setPointLabelFormatter (null) ;

but now, when you add the

line.setInterpolationParams (new CatmullRomInterpolator.Params (10, CatmullRomInterpolator.Type.Centripetal)) ;

to the regular LineAndPointFormatter the interpolation sets in and the following timing is the result

dat0   2838   2838
dat1   3112   5950
dat2   2716   8666
dat3   3021  11688
dat4   2136  13824
dat5   2258  16082
sum 277618

the getY (idx) timing seems the same, but the overall cycle time changed from 69 ms to 277 ms which makes sense since the interpolation of 50 x 6 points will take some time

i'm so far happy with my results and will use 50 instead of 500 x-data samples ... the JNI C++ code will either just return one value and skip 4 or average 5 of them together

maybe my humble anroidplot eval might help others with their androidplot design


问:
Output Node.js logs to filesystem
I have a Splunk forwarder managing logs in my production servers, so I really just need to get the output of my node app into a file that Splunk is watching. What is the downside of simply doing the following in production:

```<code>node server.js &> output.log
</code>```

As oppose to handling the log output inside the node process with some sort of logging module...

答:
There's no problem with redirecting your output to a log file.  In a lot of ways, this is preferable.

Having your application write logs directly is more useful when your application is complicated and needs a lot of log configuration, possibly writing to several log files.  What I do is use Winston for logging.  Normally the only log transport enabled is the console, and I can redirect that to a file if I want.  But, I also have in my app config a way to specify other transports and config.  I use that for writing directly to Logstash and such.

Title: Output Node.js logs to filesystem

Body:
I have a Splunk forwarder managing logs in my production servers, so I really just need to get the output of my node app into a file that Splunk is watching. What is the downside of simply doing the following in production:

node server.js &> output.log

As oppose to handling the log output inside the node process with some sort of logging module...


问:
Alternative for System.out.print in Android
Could someone tell me what is the alternative for System.out.print in Android?

答:
```<code>System.out.print
System.output.print
System.out.echo
</code>```


问:
How can I configure Angular Router to still update browser URL in case of error
When in development with Angular (v4) using Angular Cli, I would love to have the following behavior:

I load load a certain route and an error occurs

The Browser URL is changed/updated before the error is reported

I fix the error in the source file and via Angular CLI my browser is refreshed with the intended URL

Currently when I load my targeted route and an error occurs, the browser URL seems to jump to the root URL.

Back in the AngularJS 1.x + UI Router days, this was the default behavior. I like the old behavior as I don't have to do any navigation as long as I develop/fix one particular page.

Is there a way to configure Angular v4 that way?

答:
in your error handler route to a desired component

Either

route

```<code>{
  component: FallbackComponent,
  path: "fallback"
}
</code>```

logic

```<code>try{
// some logic
}
catch{
 this.router.navigate(['/fallback'])
}
</code>```

or

depending on how you've implemented to the logic you can pass in a bogus route and have a wildcard route and handle the error in any way and have a fall back route

```<code>{
  component: FallBackComponent,
  path: "**" // this catches bogus routes and redirects (put at the end)
}
</code>```

or

implement a routeguard

Body:
in your error handler route to a desired component

Either

route

{
  component: FallbackComponent,
  path: "fallback"
}

logic

try{
// some logic
}
catch{
 this.router.navigate(['/fallback'])
}

or

depending on how you've implemented to the logic you can pass in a bogus route and have a wildcard route and handle the error in any way and have a fall back route

{
  component: FallBackComponent,
  path: "**" // this catches bogus routes and redirects (put at the end)
}

or

implement a routeguard


问:
UITextField text change event
How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly. Since until it returns YES, the textField texts are not available to other observer methods.

e.g. in my code calculateAndUpdateTextFields did not get the updated text, the user has typed.

Is their any way to get something like textChanged Java event handler.

```<code>- (BOOL)textField:(UITextField *)textField
            shouldChangeCharactersInRange:(NSRange)range
            replacementString:(NSString *)string
{
    if (textField.tag == kTextFieldTagSubtotal
        || textField.tag == kTextFieldTagSubtotalDecimal
        || textField.tag == kTextFieldTagShipping
        || textField.tag == kTextFieldTagShippingDecimal)
    {
        [self calculateAndUpdateTextFields];

    }

    return YES;
}
</code>```

答:
Swift 3 Version:

```<code>class SomeClass: UIViewController, UITextFieldDelegate {

   @IBOutlet weak var aTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        aTextField.delegate = self
        aTextField.addTarget(self, action: #selector(SignUpVC.textFieldDidChange), for: UIControlEvents.editingChanged)
    }

   func textFieldDidChange(_ textField: UITextField) {

       //TEXT FIELD CHANGED..SECRET STUFF

   }

}
</code>```

Don't forget to set the delegate.

Title: UITextField text change event

Body:
How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly. Since until it returns YES, the textField texts are not available to other observer methods.

e.g. in my code calculateAndUpdateTextFields did not get the updated text, the user has typed.

Is their any way to get something like textChanged Java event handler.

- (BOOL)textField:(UITextField *)textField
            shouldChangeCharactersInRange:(NSRange)range
            replacementString:(NSString *)string
{
    if (textField.tag == kTextFieldTagSubtotal
        || textField.tag == kTextFieldTagSubtotalDecimal
        || textField.tag == kTextFieldTagShipping
        || textField.tag == kTextFieldTagShippingDecimal)
    {
        [self calculateAndUpdateTextFields];

    }

    return YES;
}

Body:
Swift 3 Version:

class SomeClass: UIViewController, UITextFieldDelegate {

   @IBOutlet weak var aTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        aTextField.delegate = self
        aTextField.addTarget(self, action: #selector(SignUpVC.textFieldDidChange), for: UIControlEvents.editingChanged)
    }

   func textFieldDidChange(_ textField: UITextField) {

       //TEXT FIELD CHANGED..SECRET STUFF

   }

}

Don't forget to set the delegate.


问:
Angular 2 - How to use prerender.io along with lazy loading
Since Angular Universal isn't going to be in the CLI for quite a while I must use prerender.io to allow SEO to work properly. However, after some tests it appears that it doesn't work all that great because it doesn't appear to wait for lazy loaded modules so the SEO still fails.

On their site at this location, they say this:

Is your page only partially rendered?

Our Prerender server tries its best to determine when the page is done
  loading by counting the number of requests in flight. Once the number
  of requests in flight reaches zero, we wait a short period of time and
  then save the HTML. If this is saving the page too early, you can use
  our window.prerenderReady flag to notify the server that your page is
  ready to be saved.

Put this in your HTML:

```<code><script> window.prerenderReady = false; </script>
</code>```

When we see window.prerenderReady set to false, we'll wait until it's
  set to true to save the HTML. Execute this when your page will be
  ready (usually after ajax calls):

```<code>window.prerenderReady = true;
</code>```

Here's where I don't understand how to go about it. Since Angular removes script tags from the template (not sure if this is just CLI behavior or Angular itself), I can't set the initial script tag. Nor can I figure out how I would update the window property prerenderReady inside a template script tag from my component class, since I can't just use window.prerenderReady = true and expect it to work since the script has to be added to the template.

Has anyone managed to figure this one out or have any ideas on how I could achieve this?

答:
REMOVE: server.use(prerender.removeScriptTags());

prerender.io can be set to leave in scripts so they can run.

My Meteor-Angular2 setup gave me the same grief.  My header and footer modules would render, but not my router-outlet output.  I placed:

on my main index.html (containing the main  <app></app> tag), and placed:

window.prerenderReady = true;

at the end of my last callback. Then I commented out:
 //server.use(prerender.removeScriptTags());
 in the server.js of my prerender server - and it finally rendered correctly.

Body:
Since Angular Universal isn't going to be in the CLI for quite a while I must use prerender.io to allow SEO to work properly. However, after some tests it appears that it doesn't work all that great because it doesn't appear to wait for lazy loaded modules so the SEO still fails.

On their site at this location, they say this:

Is your page only partially rendered?

Our Prerender server tries its best to determine when the page is done
  loading by counting the number of requests in flight. Once the number
  of requests in flight reaches zero, we wait a short period of time and
  then save the HTML. If this is saving the page too early, you can use
  our window.prerenderReady flag to notify the server that your page is
  ready to be saved.

Put this in your HTML:

When we see window.prerenderReady set to false, we'll wait until it's
  set to true to save the HTML. Execute this when your page will be
  ready (usually after ajax calls):

window.prerenderReady = true;

Here's where I don't understand how to go about it. Since Angular removes script tags from the template (not sure if this is just CLI behavior or Angular itself), I can't set the initial script tag. Nor can I figure out how I would update the window property prerenderReady inside a template script tag from my component class, since I can't just use window.prerenderReady = true and expect it to work since the script has to be added to the template.

Has anyone managed to figure this one out or have any ideas on how I could achieve this?

Body:
REMOVE: server.use(prerender.removeScriptTags());

prerender.io can be set to leave in scripts so they can run.

My Meteor-Angular2 setup gave me the same grief.  My header and footer modules would render, but not my router-outlet output.  I placed:

<script> window.prerenderReady = false; </script>

on my main index.html (containing the main  <app></app> tag), and placed:

window.prerenderReady = true;

at the end of my last callback. Then I commented out:
 //server.use(prerender.removeScriptTags());
 in the server.js of my prerender server - and it finally rendered correctly.


问:
How can i listen incoming subscription request in smack openfire android
I am creating an android chat application using a smack open fire. The problem that I am facing is I know how to send and accept subscription requests but how can I know if I have received any subscription request.
I have used Stanza listener but the listener is only listening to incoming chat messages, not subscription requests.
Below is my code

```<code>StanzaFilter filter=new StanzaTypeFilter(Message.class);
        PacketCollector collector=connection.createPacketCollector(filter);
        connection.addAsyncStanzaListener(new StanzaListener() {
            @Override
            public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
                Log.wtf("MA","Stanz listner");
            }
        },filter);
</code>```

I am a beginner in smack, please help me how can I listen for incoming subscription request. Thanks in advance.

答:
A subscription request is not a Message. It is a Presence instead.

So, you probably should try:

StanzaFilter filter = new StanzaTypeFilter(Presence.class);

Reference: RFC 3921 - Section 6 - Managing Subscriptions

Body:
I am creating an android chat application using a smack open fire. The problem that I am facing is I know how to send and accept subscription requests but how can I know if I have received any subscription request.
I have used Stanza listener but the listener is only listening to incoming chat messages, not subscription requests.
Below is my code

StanzaFilter filter=new StanzaTypeFilter(Message.class);
        PacketCollector collector=connection.createPacketCollector(filter);
        connection.addAsyncStanzaListener(new StanzaListener() {
            @Override
            public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
                Log.wtf("MA","Stanz listner");
            }
        },filter);

I am a beginner in smack, please help me how can I listen for incoming subscription request. Thanks in advance.


问:
Exception when trying to create/use an inner transaction
My application (WCF service) uses LINQ data contexts and recently we've decided to wrap everything in a transaction. Seems to work pretty well; each call into the service has its own transaction so if an exception is thrown then everything is rolled back and no changes are committed to the database.

However we have a notion of a "supervisor code", which can be generated and used once-only. We wish that the supervisor code will be marked as being used even if an error should occur later in the operation. To me, this suggests that I should use an inner transaction?

So inside my SetToUsed method, I put in a new transaction like so:

```<code>    public void SetToUsed(string code)
    {
        // security codes explicitly need their own transaction so that they will still be marked as having been used even if the outer transaction were to be rolled back due to error
        using (var securityCodeTransaction = new TransactionScope(
                TransactionScopeOption.RequiresNew,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadUncommitted
                },
                EnterpriseServicesInteropOption.Automatic))
        {
            var returnedItems = m_safetyCodeRepository.FindAll(sc => sc.safetyCode == code &&
                                                                     sc.safetyCodeTypeId == (long)GetCodeType() &&
                                                                     sc.isUsed == false);
            foreach (var item in returnedItems)
            {
                item.isUsed = true;
                m_safetyCodeRepository.SaveChanges(item);
            }

            securityCodeTransaction.Complete();
        }
    }
</code>```

However, this causes an exception: System.InvalidOperationException: Connection currently has transaction enlisted.  Finish current transaction and retry.

The exception is thrown on the FindAll line, which is a thin wrapper for

```<code>dataContext.GetTable<tbSftSafetyCodes>().Where(exp).ToList()
</code>```

Am I missing something, or going about this in entirely the wrong way?

Edit: I realised that I did not actually need a Transaction for the Supervisor Code changes per se.

So I changed the TransactionScopeOption to be TransactionScopeOption.Suppress instead. I would still like to know why having the inner transaction using TransactionScopeOption.RequiresNew didn't work though!

答:
```<code>TransactionScopeOption.RequiresNew
</code>```

attempts to start an entirely new transaction which is independent of the one it sits within, is this what you intend? The Requires option will enlist the new transaction into the currently active one.

However, if yopu always want the code to be marked as used - do you need to have it in a transaction at all? Could you not just mark it as used amd commit that change just before you start your transaction-wrapped operation?

Body:
My application (WCF service) uses LINQ data contexts and recently we've decided to wrap everything in a transaction. Seems to work pretty well; each call into the service has its own transaction so if an exception is thrown then everything is rolled back and no changes are committed to the database.

However we have a notion of a "supervisor code", which can be generated and used once-only. We wish that the supervisor code will be marked as being used even if an error should occur later in the operation. To me, this suggests that I should use an inner transaction?

So inside my SetToUsed method, I put in a new transaction like so:

    public void SetToUsed(string code)
    {
        // security codes explicitly need their own transaction so that they will still be marked as having been used even if the outer transaction were to be rolled back due to error
        using (var securityCodeTransaction = new TransactionScope(
                TransactionScopeOption.RequiresNew,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadUncommitted
                },
                EnterpriseServicesInteropOption.Automatic))
        {
            var returnedItems = m_safetyCodeRepository.FindAll(sc => sc.safetyCode == code &&
                                                                     sc.safetyCodeTypeId == (long)GetCodeType() &&
                                                                     sc.isUsed == false);
            foreach (var item in returnedItems)
            {
                item.isUsed = true;
                m_safetyCodeRepository.SaveChanges(item);
            }

            securityCodeTransaction.Complete();
        }
    }

However, this causes an exception: System.InvalidOperationException: Connection currently has transaction enlisted.  Finish current transaction and retry.

The exception is thrown on the FindAll line, which is a thin wrapper for

dataContext.GetTable<tbSftSafetyCodes>().Where(exp).ToList()

Am I missing something, or going about this in entirely the wrong way?

Edit: I realised that I did not actually need a Transaction for the Supervisor Code changes per se.

So I changed the TransactionScopeOption to be TransactionScopeOption.Suppress instead. I would still like to know why having the inner transaction using TransactionScopeOption.RequiresNew didn't work though!

Body:
TransactionScopeOption.RequiresNew

attempts to start an entirely new transaction which is independent of the one it sits within, is this what you intend? The Requires option will enlist the new transaction into the currently active one.

However, if yopu always want the code to be marked as used - do you need to have it in a transaction at all? Could you not just mark it as used amd commit that change just before you start your transaction-wrapped operation?


问:
Auto post facebook in different groups
Is it possible facebook has an ability to auto post a data of an item on my website.  Let's say everyday it will post a product automatically in different pages/groups on facebook.  Or, alternatively, I could use a button to post the product to different pages/groups in facebook. Is the facebook graph api capable with that?

I built my website using php.

答: For this, you can use any facebook auto post tool which has scheduled post feature. I can suggest you one from here -Liveurlifehere Tools.</p>

Title: Auto post facebook in different groups