问:
condition to use GLSurfaceView on android
I use GLSurfaceView but occur NullpointerException

I want showing camera preview to use GLSurfaceview

I must use GLSurfaceView

recently , occur nullpointerException code

MainActivity.class

```<code>public class CameraMainActivity extends FragmentActivity {

   private GLSurfaceView glview;

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       .
       .
       .
       glview = (GLSurfaceView) findViewById(R.id.framelayoout_network);
       VideoRendererGui.setView(glview, null) ;
   }
</code>```

(VideoRendererGui is webRtclibrary

VideoRendererGui.class

```<code>public class VideoRendererGui implements Renderer {
     private static VideoRendererGui instance = null;
     private static Runnable eglContextReady = null;

     public static void setView(GLSurfaceView surface, Runnable eglContextReadyCallback) {
    instance = new VideoRendererGui(surface);
    eglContextReady = eglContextReadyCallback;
}
</code>```

and activity_main.xml

```<code>  <android.opengl.GLSurfaceView
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:id="@+id/framelayout_network">
    </android.opengl.GLSurfaceView>
</code>```

logcat

```<code>java.lang.NullPointerException
      at android.opengl.GLSurfaceView.surfaceCreated(GLSurfaceView.java:523)
      at android.view.SurfaceView.updateWindow(SurfaceView.java:572)
      at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:232)
      at android.view.View.dispatchWindowVisibilityChanged(View.java:8004)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1233)
      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
      at android.view.Choreographer.doCallbacks(Choreographer.java:574)
      at android.view.Choreographer.doFrame(Choreographer.java:544)
      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
      at android.os.Handler.handleCallback(Handler.java:733)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:136)
      at android.app.ActivityThread.main(ActivityThread.java:5001)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
      at dalvik.system.NativeStart.main(Native Method)
</code>```

I don't know why occur NullpointerException

perhaps, use GLSurfaceViewneed condition?

please advice for me

thanks.

答:
```<code>VideoRendererGui.setView(glview, null) ;
</code>```

should be change to,

```<code>VideoRendererGui.setView(glview, new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "log something what you want...");
        }) ;
</code>```

Body:
I use GLSurfaceView but occur NullpointerException

I want showing camera preview to use GLSurfaceview

I must use GLSurfaceView

recently , occur nullpointerException code

MainActivity.class

public class CameraMainActivity extends FragmentActivity {

   private GLSurfaceView glview;

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       .
       .
       .
       glview = (GLSurfaceView) findViewById(R.id.framelayoout_network);
       VideoRendererGui.setView(glview, null) ;
   }

(VideoRendererGui is webRtclibrary

VideoRendererGui.class

public class VideoRendererGui implements Renderer {
     private static VideoRendererGui instance = null;
     private static Runnable eglContextReady = null;

     public static void setView(GLSurfaceView surface, Runnable eglContextReadyCallback) {
    instance = new VideoRendererGui(surface);
    eglContextReady = eglContextReadyCallback;
}

and activity_main.xml

  <android.opengl.GLSurfaceView
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:id="@+id/framelayout_network">
    </android.opengl.GLSurfaceView>

logcat

java.lang.NullPointerException
      at android.opengl.GLSurfaceView.surfaceCreated(GLSurfaceView.java:523)
      at android.view.SurfaceView.updateWindow(SurfaceView.java:572)
      at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:232)
      at android.view.View.dispatchWindowVisibilityChanged(View.java:8004)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1077)
      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1233)
      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
      at android.view.Choreographer.doCallbacks(Choreographer.java:574)
      at android.view.Choreographer.doFrame(Choreographer.java:544)
      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
      at android.os.Handler.handleCallback(Handler.java:733)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:136)
      at android.app.ActivityThread.main(ActivityThread.java:5001)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
      at dalvik.system.NativeStart.main(Native Method)

I don't know why occur NullpointerException

perhaps, use GLSurfaceViewneed condition?

please advice for me

thanks.

Body:
VideoRendererGui.setView(glview, null) ;

should be change to,

VideoRendererGui.setView(glview, new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "log something what you want...");
        }) ;


来源: stackexchange

问:
How point application to database.php which resides in a non-public folder?
Now that my app is built I am researching how to secure it. If I place database.php file in a folder outside of the public folder how can I point to it from inside the app? Simply using the include structure is not sufficient since this only goes to the top of the public folder.</p>

```<code>include '../database.php';
</code>```

答:
you can use './' to specify the current path of the file you're In
then use many '../' of it to move between folders and get what file you want to include </p>

ContentLicense: CC BY-SA 3.0

Body:
Now that my app is built I am researching how to secure it. If I place database.php file in a folder outside of the public folder how can I point to it from inside the app? Simply using the include structure is not sufficient since this only goes to the top of the public folder.

include '../database.php';


问:
How to get the current python interpreter path
I am wondering how to get the current python interpreter path,because of the script is packed to binary file. sys.executable doesn't work

答:
When running a PyInstaller executable ("one-file bundle" in official terms), a temporarily created file acts as the launcher for the Python engine as explained in How the One-File Program Works, so sys.executable returning it makes perfect sense.

If you're interested in the compound file instead, it's in argv[0], as it was written on the command line (i.e. may be either a relative or absolute path or contain symlinks). So, the bundle is at os.path.realpath(sys.argv[0]).

You won't get a path to the system's resident Python here because it's not involved in any way.


问:
HTML to PDF - page break with HtmlRenderer
I try to convert HTML to PDF using HtmlRenderer. This is part of code:

```<code>private byte[] CreateHtmlContent()
{
    string htmlContent = File.ReadAllText(@"htmlExample.txt");

    using (MemoryStream ms = new MemoryStream())
    {
        PdfDocument pdfDocument = new PdfDocument();
        PdfDocument pdf = PdfGenerator.GeneratePdf(htmlContent, PdfSharp.PageSize.A4, 60);
        pdf.Save(ms);
        res = ms.ToArray();
    }
    return res;
}
</code>```

Everything works fine except page break. On some pages I have result like on this image

Is it possible to fix this? HTML content is simple HTML that contains only headings and paragraphs and no other tags. I had no problem with iTextSharp but on this project I have to use PDFSharp and MigraDoc.

答:
This is a little late, but I ran into the same issue. The problem is the margin set on the GeneratePdf call.  Remove it and it's fine.</p>

```<code>    PdfDocument pdf = PdfGenerator.GeneratePdf(htmlContent, PdfSharp.PageSize.A4);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to convert HTML to PDF using HtmlRenderer. This is part of code:

private byte[] CreateHtmlContent()
{
    string htmlContent = File.ReadAllText(@"htmlExample.txt");

    using (MemoryStream ms = new MemoryStream())
    {
        PdfDocument pdfDocument = new PdfDocument();
        PdfDocument pdf = PdfGenerator.GeneratePdf(htmlContent, PdfSharp.PageSize.A4, 60);
        pdf.Save(ms);
        res = ms.ToArray();
    }
    return res;
}

Everything works fine except page break. On some pages I have result like on this image

Is it possible to fix this? HTML content is simple HTML that contains only headings and paragraphs and no other tags. I had no problem with iTextSharp but on this project I have to use PDFSharp and MigraDoc.

Body:
This is a little late, but I ran into the same issue. The problem is the margin set on the GeneratePdf call.  Remove it and it's fine.

    PdfDocument pdf = PdfGenerator.GeneratePdf(htmlContent, PdfSharp.PageSize.A4);


问:
Calling a shell command from Applescript with quotes
This seems like it should be simple, but I'm pulling out my remaining hair trying to get it to work. In a shell script I want to run some Applescript code that defines a string, then pass that string (containing a single quote) to a shell command that calls PHP's addslashes function, to return a string with that single quote escaped properly.

Here's the code I have so far - it's returning a syntax error.

```<code>STRING=$(osascript -- - <<'EOF'
set s to "It's me"
return "['test'=>'" & (do shell script "php -r 'echo addslashes(\"" & s & "\");") & "']"
EOF)
echo -e $STRING
</code>```

It's supposed to return this:

```<code>['test'=>'It\'s me']
</code>```

答:
First, when asking a question like this, please include what's happening, not just what you're trying to do. When I try this, I get:

```<code>42:99: execution error: sh: -c: line 0: unexpected EOF while looking for matchin
sh: -c: line 1: syntax error: unexpected end of file (2)
</code>```

(which is actually two error messages, with one partly overwriting the other.) Is that what you're getting?

If it is, the problem is that the inner shell command you're creating has quoting issues. Take a look at the AppleScript snippet that tries to run a shell command:

```<code>do shell script "php -r 'echo addslashes(\"" & s & "\");"
</code>```

Since s is set to It's me, this runs the shell command:

```<code>php -r 'echo addslashes("It's me");
</code>```

Which has the problem that the apostrophe in It's me is acting as a close-quote for the string that starts 'echo .... After that, the double-quote in me"); is seen as opening a new quoted string, which doesn't get closed before the end of the "file", causing the unexpected EOF problem.

The underlying problem is that you're trying to pass a string from AppleScript to shell to php... but each of those has its own rules for parsing strings (with different ideas about how quoting and escaping work). Worse, it looks like you're doing this so you can get an escaped string (following which set of escaping rules?) to pass to something else... This way lies madness.

I'm not sure what the real goal is here, but there has to be a better way; something that doesn't involve a game of telephone with players that all speak different languages. If not, you're pretty much doomed.

BTW, there are a few other dubious shell-scripting practices in the script:

Don't use all-caps variable named in shell scripts. There are a bunch of all-caps variables that have special meanings, and if you accidentally use one of those for something else, weird results can happen.

Put double-quotes around all variable references in scripts, to avoid them getting split into multiple "words" and/or expanded as shell wildcards. For example, if the variable string was set to "['test'=>'It\'s-me']", and you happened to have files named "t" and "m" in the current directory, echo -e $string will print "m t" because those are the files that match the [] pattern.

Don't use echo with options and/or to print strings that might contain escapes, since different versions treat these things differently. Some versions, for example, will print the "-e" as part of the output string. Use printf instead. The first argument to printf is a format string that tells it how to format all of the rest of the arguments. To emulate echo -e "$string" in a more reliable form, use printf '%b\n' "$string".

Body:
This seems like it should be simple, but I'm pulling out my remaining hair trying to get it to work. In a shell script I want to run some Applescript code that defines a string, then pass that string (containing a single quote) to a shell command that calls PHP's addslashes function, to return a string with that single quote escaped properly.

Here's the code I have so far - it's returning a syntax error.

STRING=$(osascript -- - <<'EOF'
set s to "It's me"
return "['test'=>'" & (do shell script "php -r 'echo addslashes(\"" & s & "\");") & "']"
EOF)
echo -e $STRING

It's supposed to return this:

['test'=>'It\'s me']

Body:
First, when asking a question like this, please include what's happening, not just what you're trying to do. When I try this, I get:

42:99: execution error: sh: -c: line 0: unexpected EOF while looking for matchin
sh: -c: line 1: syntax error: unexpected end of file (2)

(which is actually two error messages, with one partly overwriting the other.) Is that what you're getting?

If it is, the problem is that the inner shell command you're creating has quoting issues. Take a look at the AppleScript snippet that tries to run a shell command:

do shell script "php -r 'echo addslashes(\"" & s & "\");"

Since s is set to It's me, this runs the shell command:

php -r 'echo addslashes("It's me");

Which has the problem that the apostrophe in It's me is acting as a close-quote for the string that starts 'echo .... After that, the double-quote in me"); is seen as opening a new quoted string, which doesn't get closed before the end of the "file", causing the unexpected EOF problem.

The underlying problem is that you're trying to pass a string from AppleScript to shell to php... but each of those has its own rules for parsing strings (with different ideas about how quoting and escaping work). Worse, it looks like you're doing this so you can get an escaped string (following which set of escaping rules?) to pass to something else... This way lies madness.

I'm not sure what the real goal is here, but there has to be a better way; something that doesn't involve a game of telephone with players that all speak different languages. If not, you're pretty much doomed.

BTW, there are a few other dubious shell-scripting practices in the script:

Don't use all-caps variable named in shell scripts. There are a bunch of all-caps variables that have special meanings, and if you accidentally use one of those for something else, weird results can happen.

Put double-quotes around all variable references in scripts, to avoid them getting split into multiple "words" and/or expanded as shell wildcards. For example, if the variable string was set to "['test'=>'It\'s-me']", and you happened to have files named "t" and "m" in the current directory, echo -e $string will print "m t" because those are the files that match the [] pattern.

Don't use echo with options and/or to print strings that might contain escapes, since different versions treat these things differently. Some versions, for example, will print the "-e" as part of the output string. Use printf instead. The first argument to printf is a format string that tells it how to format all of the rest of the arguments. To emulate echo -e "$string" in a more reliable form, use printf '%b\n' "$string".


问:
How can I access my webapp from my pc by Android emulator?
Well I'm trying to access my webapp from my android emulator device an exception is throwing: java.net.SocketException: socket failed: EACCES (Permission denied)

In browser all right:

Browser access from http://192.168.25.7:8080

But When I try to access it from my app:

App code and thrown exception

How should I make it work?

Note: I'm using Tomcat 9, vraptor to webapp and eclipse to android programming.

答: use: http://10.0.2.2:8080 instead to access your pc's localhost from the emulator</p>


问:
convert GMT time to EST
My sql server is located in GMT and I need to get the EST equivalent tz.

Somehow the EST is wrong.

```<code>select now(),convert_tz(now(),'GMT','EST'),convert_tz(now(),'GMT','EST') - interval 10 minute
</code>```

The EST time should be 20:30 and not 19:30

Here is my results -

答:
As @ceejayoz mentioned, the timezones of locations change depending on daylight savings observation. In addition, it's more proper to call it UTC rather than GMT, as when you call it GMT, it connotes that your servers are tune to some local time, say, London time, and that your server's time will switch to some other time, say BST, when daylight savings is observed.

Assuming, as I presume you are trying to communicate, that your servers are set to UTC time, never observing daylight savings, and that you want to translate it to the time observed by most Eastern US cities, a solution would be

```<code>SELECT NOW(),
  CONVERT_TZ(NOW(), 'UTC', 'America/New_York'),
  CONVERT_TZ(NOW(), 'UTC', 'America/New_York') - INTERVAL 10 MINUTE;
</code>```

Title: convert GMT time to EST

Body:
My sql server is located in GMT and I need to get the EST equivalent tz.

Somehow the EST is wrong.

select now(),convert_tz(now(),'GMT','EST'),convert_tz(now(),'GMT','EST') - interval 10 minute

The EST time should be 20:30 and not 19:30

Here is my results -

Body:
As @ceejayoz mentioned, the timezones of locations change depending on daylight savings observation. In addition, it's more proper to call it UTC rather than GMT, as when you call it GMT, it connotes that your servers are tune to some local time, say, London time, and that your server's time will switch to some other time, say BST, when daylight savings is observed.

Assuming, as I presume you are trying to communicate, that your servers are set to UTC time, never observing daylight savings, and that you want to translate it to the time observed by most Eastern US cities, a solution would be

SELECT NOW(),
  CONVERT_TZ(NOW(), 'UTC', 'America/New_York'),
  CONVERT_TZ(NOW(), 'UTC', 'America/New_York') - INTERVAL 10 MINUTE;


问:
Sparse Efficiency Warning while changing the column
```<code>def tdm_modify(feature_names,tdm):
    non_useful_words=['kill','stampede','trigger','cause','death','hospital'\
        ,'minister','said','told','say','injury','victim','report']
    indexes=[feature_names.index(word) for word in non_useful_words]
    for index in indexes:
        tdm[:,index]=0
    return tdm
</code>```

I want to manually set zero weights for some terms in tdm matrix. Using the above code I get the warning. I don't seem to understand why? Is there a better way to do this?

```<code>C:\Anaconda\lib\site-packages\scipy\sparse\compressed.py:730: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
  SparseEfficiencyWarning)
</code>```

答:
I ran into this warning message as well working on a machine learning problem.  The exact application was constructing a document term matrix from a corpus of text.  I agree with the accepted answer.  I will add one empirical observation:

My exact task was to build a 25000 x 90000 matrix of uint8.
My desired output was a sparse matrix compressed row format, i.e. csr_matrix.

The fastest way to do this by far, at the cost of using quite a bit more memory in the interim, was to initialize a dense matrix using np.zeros(), build it up, then do csr_matrix(dense_matrix) once at the end.

The second fastest way was to build up a lil_matrix, then convert it to csr_matrix with the .tocsr() method.  This is recommended in the accepted answer.  (Thank you hpaulj).

The slowest way was to assemble the csr_matrix element by element.

So to sum up, if you have enough working memory to build a dense matrix, and only want to end up with a sparse matrix later on for downstream efficiency, it might be faster to build up the matrix in dense format and then covert it once at the end.  If you need to work in sparse format the whole time because of memory limitations, building up the matrix as a lil_matrix and then converting it (as in the accepted answer) is faster than building up a csr_matrix from the start.

Body:
def tdm_modify(feature_names,tdm):
    non_useful_words=['kill','stampede','trigger','cause','death','hospital'\
        ,'minister','said','told','say','injury','victim','report']
    indexes=[feature_names.index(word) for word in non_useful_words]
    for index in indexes:
        tdm[:,index]=0
    return tdm

I want to manually set zero weights for some terms in tdm matrix. Using the above code I get the warning. I don't seem to understand why? Is there a better way to do this?

C:\Anaconda\lib\site-packages\scipy\sparse\compressed.py:730: SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.
  SparseEfficiencyWarning)


问:
MySql foreign key constraint issue
I am trying to develop a university database and am stuck with few tables throwing a constraint error. I have tried various workarounds:
1. Checking my eninge status. It's INNODB across all tables.
2. On Update On Delete parameters(although I am not sure if I am doing that correctly).
3. Checking the NULL reference and the data types. Foreign keys referred to have the same data types as the primary key in the table which is making the reference.
    This is my query:

```<code>CREATE TABLE Faculty (
FacNo         CHAR(11)      NOT NULL,
FacFirstName  VARCHAR(30)   NOT NULL,
 FacLastName   VARCHAR(30)   NOT NULL,
FacCity       VARCHAR(30)   NOT NULL,
FacState      CHAR(2)       NOT NULL,
FacDept       CHAR(6)       NULL,
FacRank       CHAR(4)       NULL,
FacSalary     DECIMAL(10,2) NULL,
FacSupervisor CHAR(11)      NOT NULL,
FacHireDate   DATETIME      NULL,
FacZipCode    CHAR(10)      NOT NULL,
CONSTRAINT FacultyPK PRIMARY KEY (FacNo),
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty
ON DELETE NO ACTION
ON UPDATE NO ACTION )engine = innodb;
</code>```

This is the OFFERING table making the reference:

```<code>CREATE TABLE Offering (
OfferNo       INTEGER       NOT NULL,
CourseNo      CHAR(6)       NOT NULL,
OffTerm       CHAR(6)       NOT NULL,
OffYear       INTEGER       NOT NULL,
OffLocation   VARCHAR(30)   NULL,
OffTime       VARCHAR(10)   NULL,
FacNo         CHAR(11)      NOT NULL,
OffDays       CHAR(4)       NULL,
CONSTRAINT OfferingPK PRIMARY KEY (OfferNo),
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course,
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty  )ENGINE =     INNODB;
</code>```

答:
Your foreign key references are lacking columns:

```<code>CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty(Facno)

CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course(CourseNo),

CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty(FacNo)
</code>```

Here is a SQL Fiddle.  It doesn't have the CourseNo foreign key, because that isn't defined in the question.

Title: MySql foreign key constraint issue

Body:
I am trying to develop a university database and am stuck with few tables throwing a constraint error. I have tried various workarounds:
1. Checking my eninge status. It's INNODB across all tables.
2. On Update On Delete parameters(although I am not sure if I am doing that correctly).
3. Checking the NULL reference and the data types. Foreign keys referred to have the same data types as the primary key in the table which is making the reference.
    This is my query:

CREATE TABLE Faculty (
FacNo         CHAR(11)      NOT NULL,
FacFirstName  VARCHAR(30)   NOT NULL,
 FacLastName   VARCHAR(30)   NOT NULL,
FacCity       VARCHAR(30)   NOT NULL,
FacState      CHAR(2)       NOT NULL,
FacDept       CHAR(6)       NULL,
FacRank       CHAR(4)       NULL,
FacSalary     DECIMAL(10,2) NULL,
FacSupervisor CHAR(11)      NOT NULL,
FacHireDate   DATETIME      NULL,
FacZipCode    CHAR(10)      NOT NULL,
CONSTRAINT FacultyPK PRIMARY KEY (FacNo),
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty
ON DELETE NO ACTION
ON UPDATE NO ACTION )engine = innodb;

This is the OFFERING table making the reference:

CREATE TABLE Offering (
OfferNo       INTEGER       NOT NULL,
CourseNo      CHAR(6)       NOT NULL,
OffTerm       CHAR(6)       NOT NULL,
OffYear       INTEGER       NOT NULL,
OffLocation   VARCHAR(30)   NULL,
OffTime       VARCHAR(10)   NULL,
FacNo         CHAR(11)      NOT NULL,
OffDays       CHAR(4)       NULL,
CONSTRAINT OfferingPK PRIMARY KEY (OfferNo),
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course,
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty  )ENGINE =     INNODB;

Body:
Your foreign key references are lacking columns:

CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty(Facno)

CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course(CourseNo),

CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty(FacNo)

Here is a SQL Fiddle.  It doesn't have the CourseNo foreign key, because that isn't defined in the question.


问:
Checking if a graph is at-least-one-way-connected
A directed graph is called 'at-least-one-way-connected' if, for every two nodes u and v in the graph, there's either a path from u to v or a path from v to u (or both).

Is there an algorithm of time complexity O(m + n) for solving this problem?

答:
To build up to the overall solution, let's begin by with a much simpler version of this problem. Suppose that you knew that the input graph was a directed acyclic graph (DAG). How might you solve the problem in this case? Well, if the DAG had two different source nodes, then it couldn't be at-least-one-way-connected (ALOWC), since there wouldn't be a path from one of those source nodes to the other. If the DAG does have a single source node, then there's a path from that node to every other node in the DAG. That means that the overall graph is ALOWC if every other pair of nodes in the graph are ALOWC, which we can determine by removing that source node and recursively looking at the graph we have left. In other words, our algorithm would look something like this:

```<code>while (the graph has more than one node) {
    if (the graph has more than one source node) return false;
    else find and remove a source node;
}
</code>```

One way to implement this algorithm efficiently is to begin by finding a node of indegree 0. From there, we can remove it from the graph and decrement the indegree of each of its successors. We can then see, of those remaining successors, which have indegree 0 and proceed from there. Here's some pseudocode:

```<code>/* Compute indegrees. */
for (each node u) {
    u.indegree = 0;
}
for (each edge (u, v) in the graph) {
    v.indegree++;
}

/* Find a node with indegree 0. */
Node source = null;
for (each node u in the graph) {
    if (u.indegree == 0) {
        if (source != null) return false; // Two sources
        source = u;
    }
}

/* Repeatedly remove the source node, update indegrees, and find the
 * next node to process.
 */
while (there is more than one node) {
    /* Simulate removing the source node by decrementing the indegree
     * of each of its children.
     */
    Node next = null;
    for (each edge (source, v)) {
        v.indegree--;
        if (v.indegree == 0) {
            if (next != null) return false; // Two sources discovered
            next = v;
        }
    }

    source = next;
}
return true;
</code>```

This algorithm runs in time O(m + n): it takes time O(n) to set the counts to 0, time O(m) to initialize them to the proper values, and time O(m + n) for the loop, since each node is set as the source at most once and each edge is visited at most once.

So now we have an algorithm that solves this problem for DAGs, but what about general graphs? The good news is that the more general version of this problem can be converted into the problem on DAGs by looking at the strongly connected components of the graph and graph's condensation. (If you haven't seen these concepts before, I think your best bet would be to search around for a good explanation of them, since I don't think I can give a complete explanation here).

The key insight is the following: a graph G is ALOWC if and only if its condensation is also ALOWC. To see why this is, first suppose that the condensation is ALOWC, and then pick any two nodes u and v in G. If u and v are strongly connected, then there's a path from u to v, and so they're ALOWC. On the other hand, if u and v are not strongly connected, then since the condensation is ALOWC, there's either a path from the SCC containing u to the SCC containing v or vice-versa in the condensation, and that path gives a path from u to v (or vice-versa) in the original graph G.

On the other hand, if G is ALOWC, then if we form its condensation, the resulting DAG must be ALOWC, since given any two SCCs C1 and C2 in the DAG, if we pick some node u in C1 and some node v in C2 from G, then there's a path either from u to v or v to u, and therefore in the condensation there's a path from C1 to C2 or vice-versa.

So this gives a very clean O(m + n)-time algorithm for this problem:

Compute the condensation of the graph G using a standard linear-time algorithm like Tarjan's algorithm or Kosaraju's algorithm.

Use the above algorithm for DAGs to check whether the condensation is ALOWC, and return that answer.

Each step in this algorithm takes time O(m + n), so the overall runtime is O(m + n) as well.

Hope this helps!

Body:
To build up to the overall solution, let's begin by with a much simpler version of this problem. Suppose that you knew that the input graph was a directed acyclic graph (DAG). How might you solve the problem in this case? Well, if the DAG had two different source nodes, then it couldn't be at-least-one-way-connected (ALOWC), since there wouldn't be a path from one of those source nodes to the other. If the DAG does have a single source node, then there's a path from that node to every other node in the DAG. That means that the overall graph is ALOWC if every other pair of nodes in the graph are ALOWC, which we can determine by removing that source node and recursively looking at the graph we have left. In other words, our algorithm would look something like this:

while (the graph has more than one node) {
    if (the graph has more than one source node) return false;
    else find and remove a source node;
}

One way to implement this algorithm efficiently is to begin by finding a node of indegree 0. From there, we can remove it from the graph and decrement the indegree of each of its successors. We can then see, of those remaining successors, which have indegree 0 and proceed from there. Here's some pseudocode:

/* Compute indegrees. */
for (each node u) {
    u.indegree = 0;
}
for (each edge (u, v) in the graph) {
    v.indegree++;
}

/* Find a node with indegree 0. */
Node source = null;
for (each node u in the graph) {
    if (u.indegree == 0) {
        if (source != null) return false; // Two sources
        source = u;
    }
}

/* Repeatedly remove the source node, update indegrees, and find the
 * next node to process.
 */
while (there is more than one node) {
    /* Simulate removing the source node by decrementing the indegree
     * of each of its children.
     */
    Node next = null;
    for (each edge (source, v)) {
        v.indegree--;
        if (v.indegree == 0) {
            if (next != null) return false; // Two sources discovered
            next = v;
        }
    }

    source = next;
}
return true;

This algorithm runs in time O(m + n): it takes time O(n) to set the counts to 0, time O(m) to initialize them to the proper values, and time O(m + n) for the loop, since each node is set as the source at most once and each edge is visited at most once.

So now we have an algorithm that solves this problem for DAGs, but what about general graphs? The good news is that the more general version of this problem can be converted into the problem on DAGs by looking at the strongly connected components of the graph and graph's condensation. (If you haven't seen these concepts before, I think your best bet would be to search around for a good explanation of them, since I don't think I can give a complete explanation here).

The key insight is the following: a graph G is ALOWC if and only if its condensation is also ALOWC. To see why this is, first suppose that the condensation is ALOWC, and then pick any two nodes u and v in G. If u and v are strongly connected, then there's a path from u to v, and so they're ALOWC. On the other hand, if u and v are not strongly connected, then since the condensation is ALOWC, there's either a path from the SCC containing u to the SCC containing v or vice-versa in the condensation, and that path gives a path from u to v (or vice-versa) in the original graph G.

On the other hand, if G is ALOWC, then if we form its condensation, the resulting DAG must be ALOWC, since given any two SCCs C1 and C2 in the DAG, if we pick some node u in C1 and some node v in C2 from G, then there's a path either from u to v or v to u, and therefore in the condensation there's a path from C1 to C2 or vice-versa.

So this gives a very clean O(m + n)-time algorithm for this problem:

Compute the condensation of the graph G using a standard linear-time algorithm like Tarjan's algorithm or Kosaraju's algorithm.

Use the above algorithm for DAGs to check whether the condensation is ALOWC, and return that answer.

Each step in this algorithm takes time O(m + n), so the overall runtime is O(m + n) as well.

Hope this helps!


问:
Making HTTP requests to other services from CouchDB?
Is it possible to make HTTP requests to other web services from CouchDB?</p>

答: CouchDB uses SpiderMonkey as JavaScript engine. If it is possible to make http requests from SpiderMonkey - maybe you can make it from CouchDB.</p>

ContentLicense: CC BY-SA 2.5


问:
UWPCommunityToolkit Master/Detail view how do I get selected item?
I'm trying to use Master/Detail from UWPCommunityToolkit, how can I can the details for the selected item? I load the items with a set of anonymous objects:

```<code>listOfReplayFiles = await ReplayDirectoryManager.GetAllReplaysFromReplayDirectoryAsync();
        foreach (var item in listOfReplayFiles)
        {
            SavedReplays.Add(new { ReplayName = item.Name, ReplayDateCreated = item.DateCreated });
        }
</code>```

This is what my xaml looks like

```<code>        <uwpkit:MasterDetailsView
        RelativePanel.Below="pageHeader"
        ItemsSource="{Binding SavedReplays}">

        <uwpkit:MasterDetailsView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Style="{ThemeResource TitleTextBlockStyle}" Text="{Binding ReplayName}" />

                    <TextBlock Style="{ThemeResource CaptionTextBlockStyle}">
                        <Run Text="Date Created: " />
                        <Run Text="{Binding ReplayDateCreated}" />
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </uwpkit:MasterDetailsView.ItemTemplate>

        <!--<uwpkit:MasterDetailsView.DetailsTemplate>
            <DataTemplate>

            </DataTemplate>
        </uwpkit:MasterDetailsView.DetailsTemplate>-->

    </uwpkit:MasterDetailsView>
</code>```

I tried adding SelectedItem to xaml with a backing property, but my setter is not triggered when I select items.

答:
UWPCommunityToolkit Master/Detail view how do I get selected item?

The MasterDetailsView Control presents items in a master/details pattern. It shows a collection of items within the "master panel" and the details for that item within the "details panel".

So that the details panel will show the current selected item. What you just need is to bind your details of this item to the DetailsTemplate. For example, show the same content within details panel as master panel has may as follows:

```<code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <uwpkit:MasterDetailsView
    RelativePanel.Below="pageHeader"
    ItemsSource="{Binding}">
        <uwpkit:MasterDetailsView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Style="{ThemeResource TitleTextBlockStyle}" Text="{Binding ReplayName}" />
                    <TextBlock Style="{ThemeResource CaptionTextBlockStyle}">
                    <Run Text="Date Created: " />
                    <Run Text="{Binding ReplayDateCreated}" />
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </uwpkit:MasterDetailsView.ItemTemplate>
        <uwpkit:MasterDetailsView.DetailsTemplate>
        <DataTemplate>
                <StackPanel>
                    <TextBlock Style="{ThemeResource TitleTextBlockStyle}" Text="{Binding ReplayName}" />
                    <TextBlock Style="{ThemeResource CaptionTextBlockStyle}">
                    <Run Text="Date Created: " />
                    <Run Text="{Binding ReplayDateCreated}" />
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
    </uwpkit:MasterDetailsView.DetailsTemplate>
    </uwpkit:MasterDetailsView>
</Grid>
</code>```

More dertails please reference the MasterDetailsView sample.

Body:
I'm trying to use Master/Detail from UWPCommunityToolkit, how can I can the details for the selected item? I load the items with a set of anonymous objects:

listOfReplayFiles = await ReplayDirectoryManager.GetAllReplaysFromReplayDirectoryAsync();
        foreach (var item in listOfReplayFiles)
        {
            SavedReplays.Add(new { ReplayName = item.Name, ReplayDateCreated = item.DateCreated });
        }

This is what my xaml looks like

        <uwpkit:MasterDetailsView
        RelativePanel.Below="pageHeader"
        ItemsSource="{Binding SavedReplays}">

        <uwpkit:MasterDetailsView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Style="{ThemeResource TitleTextBlockStyle}" Text="{Binding ReplayName}" />

                    <TextBlock Style="{ThemeResource CaptionTextBlockStyle}">
                        <Run Text="Date Created: " />
                        <Run Text="{Binding ReplayDateCreated}" />
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </uwpkit:MasterDetailsView.ItemTemplate>

    </uwpkit:MasterDetailsView>

I tried adding SelectedItem to xaml with a backing property, but my setter is not triggered when I select items.

Body:
UWPCommunityToolkit Master/Detail view how do I get selected item?

The MasterDetailsView Control presents items in a master/details pattern. It shows a collection of items within the "master panel" and the details for that item within the "details panel".

So that the details panel will show the current selected item. What you just need is to bind your details of this item to the DetailsTemplate. For example, show the same content within details panel as master panel has may as follows:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <uwpkit:MasterDetailsView
    RelativePanel.Below="pageHeader"
    ItemsSource="{Binding}">
        <uwpkit:MasterDetailsView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Style="{ThemeResource TitleTextBlockStyle}" Text="{Binding ReplayName}" />
                    <TextBlock Style="{ThemeResource CaptionTextBlockStyle}">
                    <Run Text="Date Created: " />
                    <Run Text="{Binding ReplayDateCreated}" />
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </uwpkit:MasterDetailsView.ItemTemplate>
        <uwpkit:MasterDetailsView.DetailsTemplate>
        <DataTemplate>
                <StackPanel>
                    <TextBlock Style="{ThemeResource TitleTextBlockStyle}" Text="{Binding ReplayName}" />
                    <TextBlock Style="{ThemeResource CaptionTextBlockStyle}">
                    <Run Text="Date Created: " />
                    <Run Text="{Binding ReplayDateCreated}" />
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
    </uwpkit:MasterDetailsView.DetailsTemplate>
    </uwpkit:MasterDetailsView>
</Grid>

More dertails please reference the MasterDetailsView sample.


问:
PIC18F2520 mplab x xc8 EEPROM
```<code>Platform MPLAB X
CPU PIC18F2520
Compiler XC8 v1.38
</code>```

We are moving a project from an old (htc) compiler to the MPLAB X
platform but cannot access the EEPROM.

The old compiler supported the eeprom_read and eeprom_write but XC8
does not, well, there are defines defining them but they are "empty".
(xc.h includes htc.h which include pic18.h)
In pic.h the line

```<code>#if _EEPROMSIZE > 0 && defined(_PLIB)
</code>```

Is not triggered but instead the corresponding #else
It seems that neither _EEPROMSIZE nor _PLIB is defined.

Why is it so that the older (eeprom_read and eeprom_write)
is not supported in xc8 ?

What should we do to be able to access the EEPROM?

We tried to see what Microchip Code Configure would have done,
but the CPU PIC18F2520 is not supported by MCC.

```<code>The chip do have 256 byte eeprom according to
</code>```

http://ww1.microchip.com/downloads/en/DeviceDoc/39631E.pdf

Regards

答:
using MCC
select Memory module and it will create memory.c with all the functions needed</p>

Title: PIC18F2520 mplab x xc8 EEPROM

Body:
Platform MPLAB X
CPU PIC18F2520
Compiler XC8 v1.38

We are moving a project from an old (htc) compiler to the MPLAB X
platform but cannot access the EEPROM.

The old compiler supported the eeprom_read and eeprom_write but XC8
does not, well, there are defines defining them but they are "empty".
(xc.h includes htc.h which include pic18.h)
In pic.h the line

#if _EEPROMSIZE > 0 && defined(_PLIB)

Is not triggered but instead the corresponding #else
It seems that neither _EEPROMSIZE nor _PLIB is defined.

Why is it so that the older (eeprom_read and eeprom_write)
is not supported in xc8 ?

What should we do to be able to access the EEPROM?

We tried to see what Microchip Code Configure would have done,
but the CPU PIC18F2520 is not supported by MCC.

The chip do have 256 byte eeprom according to

http://ww1.microchip.com/downloads/en/DeviceDoc/39631E.pdf

Regards


问:
Runtime error when deploying to Azure because of one dll file
I build the app using Visual Studio and already publish it to Azure Services.
However, when trying to run it, I got the following error:

Could not load file or assembly 'RandomColorGenerator.Forms' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I looked into the bin folder in my local project and I can see the dll file just right.
Any suggestions?

答:
According to your description, your MVC project could work on your development environment, but when deployed to Azure Web App, you got the above error. Per my understanding, you could follow the possible approaches below to troubleshoot this issue:

Use KUDU which is an analysis tool for Azure Web Apps, click on the "Debug console > CMD", then check your deployed web content under D:\home\site\wwwroot\. Make sure the missing dll has been deployed to Azure Web App successfully.

You could try to create a new web app for deploying your MVC project, in order to isolate this issue.

Additionally, you could try to empty your deployed web content via KUDU or redeploy your project by select "Delete all existing files prior to publish" under the "Setting > File Publish Options" of VS publish wizard.

UPDATE:

Based on your comment, you are using Azure Cloud Services. You could enable Remote Desktop and re-publish your application, then remote to your cloud services for troubleshooting this issue. Here is a similar issue, you could refer to it.

An attempt was made to load a program with an incorrect format.

As I known, the above message means that there be a 32-bit or 64-bit
 platform conflict. For more details, you could refer to this similar issue.


问:
Python Nuke - How to use variable result from another function
I have some trouble with the return of a function. I want to create a Nuke script that asks the user a directory and automatically set the path to this directory in a Write Node with the current date, hour, etc. This part was pretty easy (this is the DateWrite() function in the provided code)

Now, I want to open this directory after the render is finished. So I have to use Callbacks and call a function that opens the given directory.

This is where I get some trouble : since the directory is set in the first function, I tried to get the value of this function with a return.

It works, but it forces me to use the first function twice (this part is the openDirectoryAfterRender() function)

```<code>#Modules import
import nuke
import subprocess

# Create DateWrite function
def DateWrite():

    # Create Variables
    selectedNodes = nuke.selectedNodes() # Get Selection of all selected nodes

    if len(selectedNodes) == 1:
        filePath = nuke.getFilename('Set Output Directory') # Asks the user to set an OutPut directory for the Write Node

        writeNode = nuke.createNode("Write") # Create a Write Node
        writeNode['file'].setValue(filePath + "[file rootname [file tail [value root.name]]]_[date %y][date %m][date %d]_[date %H][date %M].png") # Set the Write Node with TCL
        writeNode['afterRender'].setValue('openDirectoryAfterRender()') # Add a callback which will call the function openDirectoryAfterRender()

    else:
        nuke.message("No node selected or more than one node are selected.\nPlease select only one node.")
    return filePath

# Create openDirectoryAfterRender
def openDirectoryAfterRender():
    directoryToOpen = DateWrite() # Get the returned directory from DateWrite() -but also execute DateWrite another time-
    directoryToOpen = directoryToOpen.replace('/','\\') # Replace the slashes with backslashes

    subprocess.Popen('explorer %s' % directoryToOpen) # Open the chosen directory
</code>```

I am pretty new to Python and code in general, so this is probably a noob question.
I tried a lot of different solutions, this one is the closest I can get to from what I want.

Thanks a lot !

答:
I think you bit confused about the callback. You should call DataWrite from another function or outside itself. Here is a updated version of your code and tested in nuke and it works</p>

```<code>import nuke
import subprocess

# Create DateWrite function
def DateWrite():

    # Create Variables
    selectedNodes = nuke.selectedNodes() # Get Selection of all selected nodes

    if len(selectedNodes) == 1:
        filePath = nuke.getFilename('Set Output Directory') # Asks the user to set an OutPut directory for the Write Node

        writeNode = nuke.createNode("Write") # Create a Write Node
        writeNode['file'].setValue(filePath + "[file rootname [file tail [value root.name]]]_[date %y][date %m][date %d]_[date %H][date %M].png") # Set the Write Node with TCL
        writeNode['afterRender'].setValue('openDirectoryAfterRender(%s)' % filePath) # Add a callback which will call the function openDirectoryAfterRender()

    else:
        nuke.message("No node selected or more than one node are selected.\nPlease select only one node.")

# Create openDirectoryAfterRender
def openDirectoryAfterRender(directoryToOpen):
    directoryToOpen = directoryToOpen.replace('/','\\') # Replace the slashes with backslashes

    subprocess.Popen('explorer %s' % directoryToOpen) # Open the chosen directory

directoryToOpen = DateWrite() # Get the returned directory from DateWrite() -but also execute DateWrite another time-
</code>```

Body:
I have some trouble with the return of a function. I want to create a Nuke script that asks the user a directory and automatically set the path to this directory in a Write Node with the current date, hour, etc. This part was pretty easy (this is the DateWrite() function in the provided code)

Now, I want to open this directory after the render is finished. So I have to use Callbacks and call a function that opens the given directory.

This is where I get some trouble : since the directory is set in the first function, I tried to get the value of this function with a return.

It works, but it forces me to use the first function twice (this part is the openDirectoryAfterRender() function)

#Modules import
import nuke
import subprocess

# Create DateWrite function
def DateWrite():

    # Create Variables
    selectedNodes = nuke.selectedNodes() # Get Selection of all selected nodes

    if len(selectedNodes) == 1:
        filePath = nuke.getFilename('Set Output Directory') # Asks the user to set an OutPut directory for the Write Node

        writeNode = nuke.createNode("Write") # Create a Write Node
        writeNode['file'].setValue(filePath + "[file rootname [file tail [value root.name]]]_[date %y][date %m][date %d]_[date %H][date %M].png") # Set the Write Node with TCL
        writeNode['afterRender'].setValue('openDirectoryAfterRender()') # Add a callback which will call the function openDirectoryAfterRender()

    else:
        nuke.message("No node selected or more than one node are selected.\nPlease select only one node.")
    return filePath

# Create openDirectoryAfterRender
def openDirectoryAfterRender():
    directoryToOpen = DateWrite() # Get the returned directory from DateWrite() -but also execute DateWrite another time-
    directoryToOpen = directoryToOpen.replace('/','\\') # Replace the slashes with backslashes

    subprocess.Popen('explorer %s' % directoryToOpen) # Open the chosen directory

I am pretty new to Python and code in general, so this is probably a noob question.
I tried a lot of different solutions, this one is the closest I can get to from what I want.

Thanks a lot !

Body:
I think you bit confused about the callback. You should call DataWrite from another function or outside itself. Here is a updated version of your code and tested in nuke and it works

import nuke
import subprocess

# Create DateWrite function
def DateWrite():

    # Create Variables
    selectedNodes = nuke.selectedNodes() # Get Selection of all selected nodes

    if len(selectedNodes) == 1:
        filePath = nuke.getFilename('Set Output Directory') # Asks the user to set an OutPut directory for the Write Node

        writeNode = nuke.createNode("Write") # Create a Write Node
        writeNode['file'].setValue(filePath + "[file rootname [file tail [value root.name]]]_[date %y][date %m][date %d]_[date %H][date %M].png") # Set the Write Node with TCL
        writeNode['afterRender'].setValue('openDirectoryAfterRender(%s)' % filePath) # Add a callback which will call the function openDirectoryAfterRender()

    else:
        nuke.message("No node selected or more than one node are selected.\nPlease select only one node.")

# Create openDirectoryAfterRender
def openDirectoryAfterRender(directoryToOpen):
    directoryToOpen = directoryToOpen.replace('/','\\') # Replace the slashes with backslashes

    subprocess.Popen('explorer %s' % directoryToOpen) # Open the chosen directory

directoryToOpen = DateWrite() # Get the returned directory from DateWrite() -but also execute DateWrite another time-


问:
Python: How to write a CSV file?
I would like to write a CSV that outputs the following:

```<code>John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

total age 35
</code>```

And so far have:

```<code>import csv

students_file = open(‘./students_file’, ‘w’)
file_writer = csv.DictWriter(students_file)

…

file_writer.writeheader(name_title) #John
file_writer.writeheader(‘Titles’:’Values’)
file_writer.writerow(color_title:color_val) #In first column: color, in second column: black
file_writer.writerow(age_title:age_val) #In first column: age, in second column: 15
file_writer.writerow('total age': total_val) #In first column: 'total age', in second column: total_val
</code>```

But seems like it just writes on new rows rather than putting corresponding values next to each other.

What is the proper way of creating the example above?

答:
I don't think you got the concept of .csv right. The c stands for comma (or any other delimiter). I guess it means Comma,Separated,Values.

Think of it as an excel sheet or a relational database table (eg. MySQL).

Mostly the document starts with a line of col names, then the values follow. You are not in need to write eg. age twice.

Example structure of a .csv

```<code>firstname,lastname,age,favorite_meal
Jim,Joker,33,"fried hamster"
Bert,Uber,19,"salad, vegan"
</code>```

Often text is enclosed in " to, so that itself can contain commas and dont't disturb your .csv structure.

Title: Python: How to write a CSV file?

Body:
I would like to write a CSV that outputs the following:

John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

total age 35

And so far have:

import csv

students_file = open(‘./students_file’, ‘w’)
file_writer = csv.DictWriter(students_file)

…

file_writer.writeheader(name_title) #John
file_writer.writeheader(‘Titles’:’Values’)
file_writer.writerow(color_title:color_val) #In first column: color, in second column: black
file_writer.writerow(age_title:age_val) #In first column: age, in second column: 15
file_writer.writerow('total age': total_val) #In first column: 'total age', in second column: total_val

But seems like it just writes on new rows rather than putting corresponding values next to each other.

What is the proper way of creating the example above?

Body:
I don't think you got the concept of .csv right. The c stands for comma (or any other delimiter). I guess it means Comma,Separated,Values.

Think of it as an excel sheet or a relational database table (eg. MySQL).

Mostly the document starts with a line of col names, then the values follow. You are not in need to write eg. age twice.

Example structure of a .csv

firstname,lastname,age,favorite_meal
Jim,Joker,33,"fried hamster"
Bert,Uber,19,"salad, vegan"

Often text is enclosed in " to, so that itself can contain commas and dont't disturb your .csv structure.


问:
How do i efficiently feed a 2d python list to a c++ extension module
I am writing a python 3.5 module in c++ and I want to feed a 2d list from python to c++ - preferably to a std::vector. The working code is below, however I was hoping that I could avoid copying the data and instead point a 2d array to the address &input_value. Is there a better way to do this? </p>

```<code>PyObject* CheckTerminal(PyObject* self, PyObject* args)
{
  PyObject *input_value;
  std::vector<std::vector<bool>> cArray;

  if (!PyArg_ParseTuple(args, "O", &input_value))
  {
    std::cout << "\nerror\n";
    goto error;
  }

  int count = (int)PyList_Size(input_value);
  PyObject *ptemp,*vals;

  for (int i = 0; i < count; i++)
  {
    cArray.push_back(std::vector<bool>());
    ptemp = PyList_GetItem(input_value, i);
    int count2 = (int)PyList_Size(ptemp);
    for (int j = 0; j < count2; ++j)
    {

        vals = PyList_GetItem(ptemp, j);
        int v = PyLong_AsLong(vals);

        if (v == 1)
        {
            cArray[i].push_back(true);
        }
        else if (v == 0)
        {
            cArray[i].push_back(false);
        }

    }

  }

  return PyBool_FromLong(g.CheckTerminal(&cArray));

error:
  return 0;
}
</code>```

<p>After importing this module I call it from python with; </p>

```<code>p=[[1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0]]
print(nInARow.CheckTerminal(p))
</code>```

答:
I solved this by using PyObject's instead of converting to C++ array. Accessing the data inside the pyobject is done by PyList_GetItem or PyList_GetSlice </p>

```<code>// Checks if given boardState is terminal.
PyObject* NInARowGame::CheckTerminal(PyObject* input_value)
{

    //this is just  check, should be the same number of planes.
    PyObject *p1 = PyList_GetItem(input_value, 0);
    PyObject *p2 = PyList_GetItem(input_value, 1);
    Py_INCREF(p1);
    Py_INCREF(p2);

    int count = (int)PyList_Size(input_value);

    auto nK = this->winsK.size();

    for (int i = 0; i<nK; ++i)
    {//for each winning kernel do the following
     //int ksizeY = k[0].size();

        if (compareK(p1, &this->winsK[i]))
        {
            winner = 1;
            return Py_True;

        }
        if (compareK(p2, &this->winsK[i]))
        {
            winner = 2;
            return Py_True;
        }

    }
    PyObject *m = this->GetMoves();
    int counter = (int)PyList_Size(m);

    if (counter==0)
    {
        winner = 3;
        return Py_True;

    }
    Py_DECREF(p1);
    Py_DECREF(p2);
    return Py_False;
}
</code>```

Body:
I am writing a python 3.5 module in c++ and I want to feed a 2d list from python to c++ - preferably to a std::vector. The working code is below, however I was hoping that I could avoid copying the data and instead point a 2d array to the address &input_value. Is there a better way to do this?

PyObject* CheckTerminal(PyObject* self, PyObject* args)
{
  PyObject *input_value;
  std::vector<std::vector<bool>> cArray;

  if (!PyArg_ParseTuple(args, "O", &input_value))
  {
    std::cout << "\nerror\n";
    goto error;
  }

  int count = (int)PyList_Size(input_value);
  PyObject *ptemp,*vals;

  for (int i = 0; i < count; i++)
  {
    cArray.push_back(std::vector<bool>());
    ptemp = PyList_GetItem(input_value, i);
    int count2 = (int)PyList_Size(ptemp);
    for (int j = 0; j < count2; ++j)
    {

        vals = PyList_GetItem(ptemp, j);
        int v = PyLong_AsLong(vals);

        if (v == 1)
        {
            cArray[i].push_back(true);
        }
        else if (v == 0)
        {
            cArray[i].push_back(false);
        }

    }

  }

  return PyBool_FromLong(g.CheckTerminal(&cArray));

error:
  return 0;
}

After importing this module I call it from python with;

p=[[1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0]]
print(nInARow.CheckTerminal(p))

Body:
I solved this by using PyObject's instead of converting to C++ array. Accessing the data inside the pyobject is done by PyList_GetItem or PyList_GetSlice

// Checks if given boardState is terminal.
PyObject* NInARowGame::CheckTerminal(PyObject* input_value)
{

    //this is just  check, should be the same number of planes.
    PyObject *p1 = PyList_GetItem(input_value, 0);
    PyObject *p2 = PyList_GetItem(input_value, 1);
    Py_INCREF(p1);
    Py_INCREF(p2);

    int count = (int)PyList_Size(input_value);

    auto nK = this->winsK.size();

    for (int i = 0; i<nK; ++i)
    {//for each winning kernel do the following
     //int ksizeY = k[0].size();

        if (compareK(p1, &this->winsK[i]))
        {
            winner = 1;
            return Py_True;

        }
        if (compareK(p2, &this->winsK[i]))
        {
            winner = 2;
            return Py_True;
        }

    }
    PyObject *m = this->GetMoves();
    int counter = (int)PyList_Size(m);

    if (counter==0)
    {
        winner = 3;
        return Py_True;

    }
    Py_DECREF(p1);
    Py_DECREF(p2);
    return Py_False;
}


问:
jQuery: How to get first value and last value on input text
I have no idea how to get last value on input text. I already get the first value, when input type is empty did not get value. Here's my code:

HTML

```<code><input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
</code>```

JS/jQuery

```<code>$(document).ready(function(){
    var $set = $('.date');
    var len = $set.length;
    $set.each(function(index, element) {
        if (index === 0) {
            alert (this.value);
        }
    });
});
</code>```

答:
I have no idea how to get last value on input text. I already get the
  first value, when input type is empty did not get value.

this should work.

var result =  $("input[value!='']");
console.log(result.first().val());
console.log(result.last().val());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/></code>```

Also, just as a side tip, don't use multiple id attributes that have the same value because that's invalid HTML. Rather, if you want to access multiple elements use the class attribute which you've already done.

Body:
I have no idea how to get last value on input text. I already get the first value, when input type is empty did not get value. Here's my code:

HTML

<input type="text" name="date[]" class="date" id="date" value="6/17">

<input type="text" name="date[]" class="date" id="date" value="6/18">

<input type="text" name="date[]" class="date" id="date" value="6/18">

<input type="text" name="date[]" class="date" id="date" value="6/19">

<input type="text" name="date[]" class="date" id="date" value="6/19">

<input type="text" name="date[]" class="date" id="date" value="">

<input type="text" name="date[]" class="date" id="date" value="">

JS/jQuery

$(document).ready(function(){
    var $set = $('.date');
    var len = $set.length;
    $set.each(function(index, element) {
        if (index === 0) {
            alert (this.value);
        }
    });
});

Body:
I have no idea how to get last value on input text. I already get the
  first value, when input type is empty did not get value.

this should work.

var result =  $("input[value!='']");
console.log(result.first().val());
console.log(result.last().val());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="date[]" class="date" id="date" value="6/17"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/18"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value="6/19"><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>
<input type="text" name="date[]" class="date" id="date" value=""><br/>

Also, just as a side tip, don't use multiple id attributes that have the same value because that's invalid HTML. Rather, if you want to access multiple elements use the class attribute which you've already done.


问:
Add methods to a model using entity framework
With entity framework, is it possible to add methods to an object class ?
For example, i have a CLIENT mapping and i would like to create a "getAgeFromBirhDate" method.</p>

答:
```<code>public static class ModelExtended
{
    public static void SaveModelToXML(this Model1Container model, string xmlfilePath)
    {
        ///some code
    }
}
</code>```


问:
Taking Date input in the form of "yyyy/mm/dd, hh:mm" from user and validate the date in C++?
I'm pretty new in C++ and trying to figure out how to solve this problem, so any help is absolutely appreciated. I need to take Date input from user in the form of  "yyyy/mm/dd, hh:mm" in an istarem& function and validate its parts.
So far, I have tried everything that I've learned and my best solution with minimum error is the following code. There is also a predefined tester client code which I can't modify. There are many steps in the client code in which every validation gets tested. for example:

one input is "2000/1/50" and I get the DAY_ERROR which is true.
another input is "2000/1/1, 25:10" and I get the HOUR_ERROR which is true as well. Everything goes fine until the last part (checking minute). When the input is "2000/1/1, 23:60" I get the HOUR_ERROR again instead of MIN_ERROR.
I'm not sure if it's because of the whitespace after "," or not. However, if that's the case I don't know how to fix it.

```<code>std::istream& Date::read(std::istream& is = std::cin) {
    int year;
    int mon;
    int day;
    int hour;
    int min;
    bool valid;
    ((((is >> year).ignore(100, '/') >> mon).ignore(100, '/') >> day).ignore(100, ',') >> hour).ignore(100, ':') >> min;

        bool val_year = sizeof(year) == 4 && year >= MIN_YEAR && year <= MAX_YEAR;
        bool val_mon = mon >= 1 && mon <= 12;
        bool val_day = day >= 1 && day <= mday();
        bool val_hour = sizeof(hour) == 2 && hour >= 0 && hour <= 23;
        bool val_min = sizeof(min) == 2 && min >= 0 && min <= 59;
        valid = val_year && val_mon && val_day && val_hour && val_min;
        if (valid) {
            errCode(NO_ERROR);
            Date D2(year, mon, day, hour, min);
        }
        else {
            if (!val_year)
                errCode(YEAR_ERROR);
            else if (!val_mon)
                errCode(MON_ERROR);
            else if (!val_day)
                errCode(DAY_ERROR);
            else if (!val_hour)
                errCode(HOUR_ERROR);
            else if (!val_min)
                errCode(MIN_ERROR);
            else
                errCode(NO_ERROR);
            }
        }
        return is;
    }
</code>```

答:
Here's one suggestion:

```<code>/*
 * EXAMPLE INPUT: 2/22/17, 20:15
 * EXAMPLE OUTPUT: input: 02/22/17, 20:15
 */
#include <stdio.h>

int main()
{
  int year, month, day, hour, min;
  char buff[80];

  fgets (buff, sizeof(buff), stdin);
  int n = sscanf(buff, "%d/%d/%d, %d:%d", &year, &month, &day, &hour, &min);
  if (n != 5) {
    printf ("Error parsing input: expected 5 values, got %d...\n", n);
    return 1;
  }
  printf ("input: %02d/%02d/%d, %02d:%02d\n", year, month, day, hour, min);

  return 0;
}
</code>```

As far as validating the date: your code looks fine.

Or you might want to consider reading your date/time values into a struct tm_date (instead of year, month, day, etc.), then using strftime to validate.

Here is an example:

taking date as dd/mm/yy in c language

Body:
I'm pretty new in C++ and trying to figure out how to solve this problem, so any help is absolutely appreciated. I need to take Date input from user in the form of  "yyyy/mm/dd, hh:mm" in an istarem& function and validate its parts.
So far, I have tried everything that I've learned and my best solution with minimum error is the following code. There is also a predefined tester client code which I can't modify. There are many steps in the client code in which every validation gets tested. for example:

one input is "2000/1/50" and I get the DAY_ERROR which is true.
another input is "2000/1/1, 25:10" and I get the HOUR_ERROR which is true as well. Everything goes fine until the last part (checking minute). When the input is "2000/1/1, 23:60" I get the HOUR_ERROR again instead of MIN_ERROR.
I'm not sure if it's because of the whitespace after "," or not. However, if that's the case I don't know how to fix it.

std::istream& Date::read(std::istream& is = std::cin) {
    int year;
    int mon;
    int day;
    int hour;
    int min;
    bool valid;
    ((((is >> year).ignore(100, '/') >> mon).ignore(100, '/') >> day).ignore(100, ',') >> hour).ignore(100, ':') >> min;

        bool val_year = sizeof(year) == 4 && year >= MIN_YEAR && year <= MAX_YEAR;
        bool val_mon = mon >= 1 && mon <= 12;
        bool val_day = day >= 1 && day <= mday();
        bool val_hour = sizeof(hour) == 2 && hour >= 0 && hour <= 23;
        bool val_min = sizeof(min) == 2 && min >= 0 && min <= 59;
        valid = val_year && val_mon && val_day && val_hour && val_min;
        if (valid) {
            errCode(NO_ERROR);
            Date D2(year, mon, day, hour, min);
        }
        else {
            if (!val_year)
                errCode(YEAR_ERROR);
            else if (!val_mon)
                errCode(MON_ERROR);
            else if (!val_day)
                errCode(DAY_ERROR);
            else if (!val_hour)
                errCode(HOUR_ERROR);
            else if (!val_min)
                errCode(MIN_ERROR);
            else
                errCode(NO_ERROR);
            }
        }
        return is;
    }

Body:
Here's one suggestion:

/*
 * EXAMPLE INPUT: 2/22/17, 20:15
 * EXAMPLE OUTPUT: input: 02/22/17, 20:15
 */
#include <stdio.h>

int main()
{
  int year, month, day, hour, min;
  char buff[80];

  fgets (buff, sizeof(buff), stdin);
  int n = sscanf(buff, "%d/%d/%d, %d:%d", &year, &month, &day, &hour, &min);
  if (n != 5) {
    printf ("Error parsing input: expected 5 values, got %d...\n", n);
    return 1;
  }
  printf ("input: %02d/%02d/%d, %02d:%02d\n", year, month, day, hour, min);

  return 0;
}

As far as validating the date: your code looks fine.

Or you might want to consider reading your date/time values into a struct tm_date (instead of year, month, day, etc.), then using strftime to validate.

Here is an example:

taking date as dd/mm/yy in c language


问:
Receiving data only if sent python socket
I am writing a messenger application in python and I have a problem. The problem is quite simple: I want the program to only receive data from the other computer if it was sent, otherwise, my program would wait for a data transfer infinitely. How would I write that piece of code? I imagine it'd be something like this:</p>

```<code>    try:
        data = s.recv(1024).decode()
    except:
        data == None
</code>```

答:
See the select module.  A socket can be monitored for readability with a timeout, so other process can proceed.

Example server:

```<code>import socket
import select

with socket.socket() as server:
    server.bind(('',5000))
    server.listen(3)
    to_read = [server]  # add server to list of readable sockets.
    clients = {}
    while True:
        # check for a connection to the server or data ready from clients.
        # readers will be empty on timeout.
        readers,_,_ = select.select(to_read,[],[],0.5)
        for reader in readers:
            if reader is server:
                client,address = reader.accept()
                print('connected',address)
                clients[client] = address # store address of client in dict
                to_read.append(client) # add client to list of readable sockets
            else:
                # Simplified, really need a message protocol here.
                # For example, could receive a partial UTF-8 encoded sequence.
                data = reader.recv(1024)
                if not data: # No data indicates disconnect
                    print('disconnected',clients[reader])
                    to_read.remove(reader) # remove from monitoring
                    del clients[reader] # remove from dict as well
                else:
                    print(clients[reader],data.decode())
        print('.',flush=True,end='')
</code>```

A simple client, assuming your IP address is 1.2.3.4.

```<code>import socket
s = socket.socket()
s.connect(('1.2.3.4',5000))
s.sendall('hello'.encode())
s.close()
</code>```

Body:
I am writing a messenger application in python and I have a problem. The problem is quite simple: I want the program to only receive data from the other computer if it was sent, otherwise, my program would wait for a data transfer infinitely. How would I write that piece of code? I imagine it'd be something like this:

    try:
        data = s.recv(1024).decode()
    except:
        data == None

Body:
See the select module.  A socket can be monitored for readability with a timeout, so other process can proceed.

Example server:

import socket
import select

with socket.socket() as server:
    server.bind(('',5000))
    server.listen(3)
    to_read = [server]  # add server to list of readable sockets.
    clients = {}
    while True:
        # check for a connection to the server or data ready from clients.
        # readers will be empty on timeout.
        readers,_,_ = select.select(to_read,[],[],0.5)
        for reader in readers:
            if reader is server:
                client,address = reader.accept()
                print('connected',address)
                clients[client] = address # store address of client in dict
                to_read.append(client) # add client to list of readable sockets
            else:
                # Simplified, really need a message protocol here.
                # For example, could receive a partial UTF-8 encoded sequence.
                data = reader.recv(1024)
                if not data: # No data indicates disconnect
                    print('disconnected',clients[reader])
                    to_read.remove(reader) # remove from monitoring
                    del clients[reader] # remove from dict as well
                else:
                    print(clients[reader],data.decode())
        print('.',flush=True,end='')

A simple client, assuming your IP address is 1.2.3.4.

import socket
s = socket.socket()
s.connect(('1.2.3.4',5000))
s.sendall('hello'.encode())
s.close()


问:
Android Virtual Device (AVD) -- which CPU/ABI should I select?
When creating an AVD, there are three options to select for CPU/ABI:

ARM

Mips

Intel Atom

What are the differences and which should I choose?  Is there one that covers most devices?

答:
There are three main CPU architectures used in today's Android phones. ARM is perhaps the most common, as it's optimized for battery consumption. ARM64 is an evolution of the original ARM architecture that supports 64-bit processing for more powerful computing, and it's quickly becoming the standard in newer devices.

From: https://android.gadgethacks.com/how-to/android-basics-see-what-kind-processor-you-have-arm-arm64-x86-0168051/


问:
Finding the maximum depth of a binary tree
```<code>public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public int maxDepth(TreeNode root) {
        TreeNode focusNode = root;
        TreeNode focusNode2 = root;
        int count = 0;
        int count1 = 0;
        boolean a = true;
        while (a) {
           if (focusNode != null) {
               count++;
               focusNode = focusNode.left;
           }
           if (focusNode2 != null) {
               count++;
               focusNode2 = focusNode2.right;
           } else {
               a = false;
           }
        }
        return Math.max(count,count1);
    }
}
</code>```

<p>I am confused why this code I wrote cannot give expected output. And I am also confused with the definition of maximum depth. Is finding maximum depth just considering all the nodes that line up on the left or line up on the right? </p>

答:
You're not traversing the whole tree. You're running down the far left and far right paths only.

Typically, recursion is your friend with binary trees, because every node can be treated simply and in isolation.

Define a depth() method for the node class, that makes use of these facts:

the depth of a null child is zero

the depth of a non-null child is found by calling its depth() method (ie recursively)

the depth of this node is the max of its children's depths, plus 1 (so it counts itself)

Implement that and call depth() on the root node to find the max depth of the tree. The recursive nature of the corresponding implementation will traverse the whole tree.

Body:
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public int maxDepth(TreeNode root) {
        TreeNode focusNode = root;
        TreeNode focusNode2 = root;
        int count = 0;
        int count1 = 0;
        boolean a = true;
        while (a) {
           if (focusNode != null) {
               count++;
               focusNode = focusNode.left;
           }
           if (focusNode2 != null) {
               count++;
               focusNode2 = focusNode2.right;
           } else {
               a = false;
           }
        }
        return Math.max(count,count1);
    }
}

I am confused why this code I wrote cannot give expected output. And I am also confused with the definition of maximum depth. Is finding maximum depth just considering all the nodes that line up on the left or line up on the right?


问:
How to make 2 different joins in one query (3 tables) on mysql
Let's say I have 3 tables and I want to join them like this:

```<code>table 1 join table 2 and table 2 join table 3
</code>```

I'm trying the following code but I'm  getting an error of syntax.

SELECT * from table1 join table2 and table2 join table3
on  table1.id=table2.idA  and table2.idB=table3.id

答:
Study up a bit on SQL.  The syntax looks like:

```<code>select *
from table1 join
     table2
     on table1.id = table2.idA join
     table3
     on table2.idB = table3.id;
</code>```

This is very basic JOIN syntax and should be covered in any tutorial, documentation, book, paper or whatever that you are using to learn SQL.

Body:
Let's say I have 3 tables and I want to join them like this:

table 1 join table 2 and table 2 join table 3

I'm trying the following code but I'm  getting an error of syntax.

SELECT * from table1 join table2 and table2 join table3
on  table1.id=table2.idA  and table2.idB=table3.id

Body:
Study up a bit on SQL.  The syntax looks like:

select *
from table1 join
     table2
     on table1.id = table2.idA join
     table3
     on table2.idB = table3.id;

This is very basic JOIN syntax and should be covered in any tutorial, documentation, book, paper or whatever that you are using to learn SQL.


问:
MYSQL Using a replace function to replace a part of a statement with a variable
I'm trying to figure out how to change DueDays by increasing 15 days for terms whose current DueDays is larger than 30 (I figured out that part). Then I need to change the details value to the same value as the Duedays is changed. For example, if DueDays of a term is changed from 30 to 45, then 'Net due 30 days' should change to 'Net due 45 days'.

```<code>ID  Details                DueDays
1   Net due 10 days          10
2   Net due 20 days          20
3   Net due 30 days          30
4   Net due 60 days          60
5   Net due 90 days          90
</code>```

So far this is what I came up with:

```<code>Update Terms
SET DueDays = DueDays + 15 AND SET Replace ( Details, '' ,
WHERE DueDays > 30;
</code>```

Thank you in advance

答:
This should work as well</p>

```<code> Update terms
 Set Duedays = Duedays + 15,
 Details=replace(details,Duedays,Duedays+15)
 Where duedays > 90;
</code>```

Body:
I'm trying to figure out how to change DueDays by increasing 15 days for terms whose current DueDays is larger than 30 (I figured out that part). Then I need to change the details value to the same value as the Duedays is changed. For example, if DueDays of a term is changed from 30 to 45, then 'Net due 30 days' should change to 'Net due 45 days'.

ID  Details                DueDays
1   Net due 10 days          10
2   Net due 20 days          20
3   Net due 30 days          30
4   Net due 60 days          60
5   Net due 90 days          90

So far this is what I came up with:

Update Terms
SET DueDays = DueDays + 15 AND SET Replace ( Details, '' ,
WHERE DueDays > 30;

Thank you in advance

Body:
This should work as well

 Update terms
 Set Duedays = Duedays + 15,
 Details=replace(details,Duedays,Duedays+15)
 Where duedays > 90;


问:
Get position of string from "right to left"
it's me again.

This time I need help for find the position of a string, but from right to left.

Ex:

The new car is: > SUV Ford (user file: 1191.jpg), OK ;)

Failure was in battery: >> Pickup Chevrolet (user file: 23.jpg), BAD :'(

The new car is: > SUV Kia (user file: 8.jpg), OK ;)

The new car is: > SUV Toyota (user file: 27411058.jpg), OK ;)

Failure was in battery: >>> SUV Dodge (user file: 9409.jpg), BAD, Priority

So, I'd like get the position of 'NUMBER.jpg', but from right to left:

Index #: 8 --> right to left

Index #: 10 --> right to left

Index #: 8 --> right to left

Index #: 8 --> right to left

Index #: 16 --> right to left

How can I do it in python 2.7?

@dot.Py Where are you? I need your support.

答:
In the meantime you don't get other "pythonic" answers, here's a total "hack":

```<code>import re
print re.search("gpj", line[::-1]).start() # "gpj" as it reads in reverse
</code>```

or, the pseudocode G5W mentioned may be something like this:

```<code>import re
match = "jpg"
pos = re.search(match, line).start()
print len(line) - pos - len(match)
</code>```

either way, should get:

```<code>8
10
8
8
16
</code>```

Body:
In the meantime you don't get other "pythonic" answers, here's a total "hack":

import re
print re.search("gpj", line[::-1]).start() # "gpj" as it reads in reverse

or, the pseudocode G5W mentioned may be something like this:

import re
match = "jpg"
pos = re.search(match, line).start()
print len(line) - pos - len(match)

either way, should get:

8
10
8
8
16


问:
Pushing objects into Object Array - Typescript
Having trouble with some code here. Building an application but stumbling over how to work with array objects. I provided the code above NgInit{}. And provided the TS error I am getting in Xcode.

Full component

```<code>import { Component, OnInit } from '@angular/core';
import { Ticker } from '../TickerType';
import { ConversionService } from '../Conversion.service';
import {Observable} from 'rxjs/Rx';
import {resultsType} from './resultsTypeInterface';
@Component({
  selector: 'app-contents',
  templateUrl: './contents.component.html',
  styleUrls: ['./contents.component.scss']
})
export class ContentsComponent implements OnInit{

//Will hold the data from the JSON file

  // Variables for front end
 cryptoSelected : boolean = false;
 regSelected : boolean = false;
 step2AOptions : any[] = [
      {name: "make a selection..."},
      {name: "Bitcoin"},
      {name: "DASH"},
      {name: "Etherium"}
    ]; // step2AOptions
 step2BOptions : any[] = [
      {name: "make a selection..."},
      {name: "CAD"},
      {name: "USD"}
    ]; // step2BOptions
 step2Selection: string;
 holdings: number = 10;

coins: any[] = ["BTC_ETH", "BTC_DASH"];
ticker: Ticker[];
coinResults: resultsType[] =[];
currencyExchange:any[] = [];

  constructor( private conversionService: ConversionService ) {

  }
</code>```

Error

```<code>Argument of type '{ name: string; amount: any; }[]' is not assignable to parameter of type 'resultsType'.
  Property 'name' is missing in type '{ name: string; amount: any; }[]'.
</code>```

This is happening in the code below. What I am trying to do is push this objects into an Object Array so I can access properties of like.

```<code>console.log(coinsResults[0].name);
</code>```

Code

```<code>ngOnInit(){
  this.conversionService.getFullTicker().subscribe((res) => {this.ticker = res;

  for(var j = 0; j<= this.coins.length-1; j++)
  {
    var currencyName: string = this.coins[j];
    if(this.ticker[currencyName])
    {
      var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
      this.coinResults.push(temp)
    }
  }//end the for loop
  }); //end the subscribe function
 this.conversionService.getFullCurrencyExchange().subscribe( (res) => {this.currencyExchange = res["rates"]
  });
  console.log(this.coinResults);
}// End OnInit
</code>```

答:
you can't pass an array to Array.push(array) since Array.push signature defined as reset parameters push(...items: T[]), use Array.push(item) instead.

```<code>var temp = {name: currencyName, amount: this.ticker[currencyName].last};
this.coinResults.push(temp);
</code>```

OR using spread operator:...

```<code>var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ];
this.coinResults.push(...temp);
</code>```

Body:
Having trouble with some code here. Building an application but stumbling over how to work with array objects. I provided the code above NgInit{}. And provided the TS error I am getting in Xcode.

Full component

import { Component, OnInit } from '@angular/core';
import { Ticker } from '../TickerType';
import { ConversionService } from '../Conversion.service';
import {Observable} from 'rxjs/Rx';
import {resultsType} from './resultsTypeInterface';
@Component({
  selector: 'app-contents',
  templateUrl: './contents.component.html',
  styleUrls: ['./contents.component.scss']
})
export class ContentsComponent implements OnInit{

//Will hold the data from the JSON file

  // Variables for front end
 cryptoSelected : boolean = false;
 regSelected : boolean = false;
 step2AOptions : any[] = [
      {name: "make a selection..."},
      {name: "Bitcoin"},
      {name: "DASH"},
      {name: "Etherium"}
    ]; // step2AOptions
 step2BOptions : any[] = [
      {name: "make a selection..."},
      {name: "CAD"},
      {name: "USD"}
    ]; // step2BOptions
 step2Selection: string;
 holdings: number = 10;

coins: any[] = ["BTC_ETH", "BTC_DASH"];
ticker: Ticker[];
coinResults: resultsType[] =[];
currencyExchange:any[] = [];

  constructor( private conversionService: ConversionService ) {

  }

Error

Argument of type '{ name: string; amount: any; }[]' is not assignable to parameter of type 'resultsType'.
  Property 'name' is missing in type '{ name: string; amount: any; }[]'.

This is happening in the code below. What I am trying to do is push this objects into an Object Array so I can access properties of like.

console.log(coinsResults[0].name);

Code

ngOnInit(){
  this.conversionService.getFullTicker().subscribe((res) => {this.ticker = res;

  for(var j = 0; j<= this.coins.length-1; j++)
  {
    var currencyName: string = this.coins[j];
    if(this.ticker[currencyName])
    {
      var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
      this.coinResults.push(temp)
    }
  }//end the for loop
  }); //end the subscribe function
 this.conversionService.getFullCurrencyExchange().subscribe( (res) => {this.currencyExchange = res["rates"]
  });
  console.log(this.coinResults);
}// End OnInit

Body:
you can't pass an array to Array.push(array) since Array.push signature defined as reset parameters push(...items: T[]), use Array.push(item) instead.

var temp = {name: currencyName, amount: this.ticker[currencyName].last};
this.coinResults.push(temp);

OR using spread operator:...

var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ];
this.coinResults.push(...temp);


问:
lightweight framework for automatic IIS deployment
Some background:

I'm a Java server developer and works mostly for Linux server

I use python as major scripting language for all trivial tasks, as well as deployment

Now I'm going to move to a project using C# on Windows.

What's feature I like for fabric:

fabric is lightweight, and easy for small team to learn

python can do a lot of things than some deployment framework. For example, we manage hundreds of machines via a internal management portal, a lot of specified configurations and functionalities. We implemented the portal using Java and some fancy web framework. I use python to access the rest API from the server and retrieve server address/port and other information for deployment. The most convenient way to get it done is using a real programming language.

with fabric, I can run any command on remote server. With this I can easily have workarounds for some unusual cases.

again, python is really good to do customization work for servers, e.g. build an init.d script from template.

What I have checked for windows:

Windows Deployment Kit

Ansible

Chef

(The list above may cost me too much to learn to get the right choice. I didn't dig into them.)

I also think about installing a ssh server software on windows. But I'm looking for a Windows way for Windows deployment.

The question is:
Is there an easy to learn and lightweight script framework for windows server deployment? my goal is to automatic everything for deployment to multiple IIS instances, and also, handle some daily/weekly ops tasks.

答:
My Final solution that works pretty well:

install cygwin on windows server

install sshd as service

use python fabric to handle deployment

run commands on server using fabric

sync files using rsync

steps of uploading files

upload a random password file to server

start rsync daemon on remote server

upload file with modification check and compression using rsync

stop rsync daemon on remote server

server provision


问:
Trying to create script that uses two arguments to find number of occurences within string
I am trying to write a bash script where it takes two inputs from the user, uses the first as a three letter codon string, and uses the second as a pathname of a file containing a valid DNA string (which I have made and called dnafile.txt in my directory, and already stored a DNA string in). The script is supposed to output the number of occurrences of the codon given as argument 1 in the file given as argument 2. What do I do?</p>

答:
You can use grep's -o flag to only output matches, then count them using wc -l as such:

```<code>grep -o $1 $2 | wc -l
</code>```

For example,

```<code>$ cat dnafile.txt
aacgtttgtaaccagaac
$ grep -o 'aac' dnafile.txt | wc -l
3
</code>```

Body:
You can use grep's -o flag to only output matches, then count them using wc -l as such:

grep -o $1 $2 | wc -l

For example,

$ cat dnafile.txt
aacgtttgtaaccagaac
$ grep -o 'aac' dnafile.txt | wc -l
3