答:
Here's one way, which gets the MAX date per day and then uses it in the INNER query to get the other fields:

```<code>SELECT *
FROM test
WHERE `datetime` IN (
  SELECT MAX(`datetime`)
  FROM test
  GROUP BY DATE(`datetime`)
 );
</code>```

Here's the SQL Fiddle.

Title: MySQL select last row each day

Body:
Trying to select last row each day.

This is my (simplified, more records in actual table) table:

+-----+-----------------------+------+
| id  |       datetime        | temp |
+-----+-----------------------+------+
|  9  | 2017-06-05 23:55:00   | 9.5  |
|  8  | 2017-06-05 23:50:00   | 9.6  |
|  7  | 2017-06-05 23:45:00   | 9.3  |
|  6  | 2017-06-04 23:55:00   | 9.4  |
|  5  | 2017-06-04 23:50:00   | 9.2  |
|  4  | 2017-06-05 23:45:00   | 9.1  |
|  3  | 2017-06-03 23:55:00   | 9.8  |
|  2  | 2017-06-03 23:50:00   | 9.7  |
|  1  | 2017-06-03 23:45:00   | 9.6  |
+-----+-----------------------+------+

I want to select row with id = 9, id = 6 and id = 3.

I have tried this query:

SELECT MAX(datetime) Stamp
     , temp
  FROM weatherdata
 GROUP
    BY YEAR(DateTime)
     , MONTH(DateTime)
     , DAY(DateTime)
 order
    by datetime desc
 limit 10;

But datetime and temp does not match.

Kind Regards

Body:
Here's one way, which gets the MAX date per day and then uses it in the INNER query to get the other fields:

SELECT *
FROM test
WHERE `datetime` IN (
  SELECT MAX(`datetime`)
  FROM test
  GROUP BY DATE(`datetime`)
 );

Here's the SQL Fiddle.


来源: stackexchange

问:
Creating multiple daemons in C Linux and communicating between them
I am working on Linux Ubuntu to create daemon processes. I have referred the following tutorial to learn about the basic implementation of a daemon code using fork and setid:

http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html

I have an application where I have to create multiple daemon processes and communicate between them.

For example:
 I have 3 source files and I would like to make them as 3 different daemon processes. And I have functions defined in these source files, which I would like to call from main() or from other source files.

How exactly should I create multiple daemon processes i.e each individual source file acts as a separate daemon process ?
(I might be wrong here but I was planning to create threads to the functions of these files function, where this function will have its own PID and then I do fork and setid and the rest process to create a daemon here, which might create individual multiple daemons ? )

How should I manage communication between these daemon processes ?
For example: If I want to call some function from source file, and if that source file is a daemon process, then how should I call a function from that daemon process ?

I am searching the internet about multiple daemon processes and their intercommunication, but it would be very great if someone can help me.

Thank you.

答:
If you are target linux, I will recommend you to let the demon feature be handle by the init system (systemd for example).

To communicate between your programs, you can use a named pipe https://linux.die.net/man/4/fifo.

ContentLicense: CC BY-SA 3.0


问:
Unity : How to deal with many colliders or triggers at once?
In unity, We can deal with collisions and positions with trigger. However, I couldn't find any of information about dealing plural conditions of triggers or collider.

For example, if there is two balls connected with one cylinder, how should I have to control the state of Cylinder Which affected by two different balls.

If ball A is black and ball B is white, than the connected cylinder
is gray.

If both A & B is black, cylinder is black.

If both A & B is
white, cylinder is white.

答:
You can solve the problem with a simple script like this:

```<code>using UnityEngine;

public class TriggerScript : MonoBehaviour {

    public GameObject sphereA, sphereB;
    MeshRenderer meshA, meshB, meshC;
    Color colorA, colorB;

    void Awake() {
        meshA = sphereA.GetComponent<MeshRenderer>();
        meshB = sphereB.GetComponent<MeshRenderer>();
        meshC = GetComponent<MeshRenderer>();
        colorA = meshA.material.color;
        colorB = meshB.material.color;
    }

    void OnTriggerStay(Collider other) {
        // Check which sphere is "other"
        if (other.gameObject == sphereA) {
            colorA = meshA.material.color;
        }
        if (other.gameObject == sphereB) {
            colorB = meshB.material.color;
        }

        // Check which are the spheres' colors and change cylinder color accordingly
        if (colorA == Color.black && colorB == Color.white ||
            colorA == Color.white && colorB == Color.black) {
            meshC.material.color = Color.gray;
        }
        else if (colorA == Color.black && colorB == Color.black) {
            meshC.material.color = Color.black;
        }
        else if (colorA == Color.white && colorB == Color.white) {
            meshC.material.color = Color.white;
        }
    }
}
</code>```

Attach the script to the cylinder game object, give the spheres' references via Inspector and that's all. You can change OnTriggerStay to OnTriggerEnter based on what you want to accomplish ofc.
Remember that the spheres can have only the Collider component, but the cylinder must have a Rigidbody component too.

Body:
You can solve the problem with a simple script like this:

using UnityEngine;

public class TriggerScript : MonoBehaviour {

    public GameObject sphereA, sphereB;
    MeshRenderer meshA, meshB, meshC;
    Color colorA, colorB;

    void Awake() {
        meshA = sphereA.GetComponent<MeshRenderer>();
        meshB = sphereB.GetComponent<MeshRenderer>();
        meshC = GetComponent<MeshRenderer>();
        colorA = meshA.material.color;
        colorB = meshB.material.color;
    }

    void OnTriggerStay(Collider other) {
        // Check which sphere is "other"
        if (other.gameObject == sphereA) {
            colorA = meshA.material.color;
        }
        if (other.gameObject == sphereB) {
            colorB = meshB.material.color;
        }

        // Check which are the spheres' colors and change cylinder color accordingly
        if (colorA == Color.black && colorB == Color.white ||
            colorA == Color.white && colorB == Color.black) {
            meshC.material.color = Color.gray;
        }
        else if (colorA == Color.black && colorB == Color.black) {
            meshC.material.color = Color.black;
        }
        else if (colorA == Color.white && colorB == Color.white) {
            meshC.material.color = Color.white;
        }
    }
}

Attach the script to the cylinder game object, give the spheres' references via Inspector and that's all. You can change OnTriggerStay to OnTriggerEnter based on what you want to accomplish ofc.
Remember that the spheres can have only the Collider component, but the cylinder must have a Rigidbody component too.


答:
If your rows are always inserted and never updated, and if id is an autoincrementing primary key, then

```<code>SELECT w.*
  FROM weatherdata w
  JOIN (   SELECT MAX(id) id
             FROM weatherdata
            GROUP BY DATE(datetime)
       ) last ON w.id = last.id
</code>```

will get you what you want. Why? The inner query returns the largest (meaning most recent) id value for each date in weatherdata.  This can be very fast indeed, especially if you put an index on the datetime column.

But it's possible the conditions for this to work don't hold. If your datetime column sometimes gets updated to change the date, it's possible that larger id values don't always imply larger datetime values.

In that case you need something like this.

```<code>SELECT w.*
  FROM weatherdata w
  JOIN (   SELECT MAX(datetime) datetime
             FROM weatherdata
            GROUP BY DATE(datetime)
       ) last ON w.datetime = last.datetime
</code>```

Your query doesn't work because it misuses the nasty nonstandard extension to MySQL GROUP BY.  Read this: https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

It should, properly, use the ANY_VALUE() function to highlight the unpredictability of the results. It shoud read ....

```<code>SELECT MAX(datetime) Stamp, ANY_VALUE(temp) temp
</code>```

which means you aren't guaranteed the right row's temp value. Rather, it can return the temp value from any row in each day's grouping.

Title: MySQL select last row each day

Body:
If your rows are always inserted and never updated, and if id is an autoincrementing primary key, then

SELECT w.*
  FROM weatherdata w
  JOIN (   SELECT MAX(id) id
             FROM weatherdata
            GROUP BY DATE(datetime)
       ) last ON w.id = last.id

will get you what you want. Why? The inner query returns the largest (meaning most recent) id value for each date in weatherdata.  This can be very fast indeed, especially if you put an index on the datetime column.

But it's possible the conditions for this to work don't hold. If your datetime column sometimes gets updated to change the date, it's possible that larger id values don't always imply larger datetime values.

In that case you need something like this.

SELECT w.*
  FROM weatherdata w
  JOIN (   SELECT MAX(datetime) datetime
             FROM weatherdata
            GROUP BY DATE(datetime)
       ) last ON w.datetime = last.datetime

Your query doesn't work because it misuses the nasty nonstandard extension to MySQL GROUP BY.  Read this: https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

It should, properly, use the ANY_VALUE() function to highlight the unpredictability of the results. It shoud read ....

SELECT MAX(datetime) Stamp, ANY_VALUE(temp) temp

which means you aren't guaranteed the right row's temp value. Rather, it can return the temp value from any row in each day's grouping.


问:
Get author names from CrossRef (get text out of JSON)
I'm trying to get the author names of this paper by using the CrossRef API with curl.

```<code>curl -LH "Accept: application/citeproc+json" http://dx.doi.org/10.3389/fpls.2011.00050 | jq .author
</code>```

Of course I get a JSON as response, but rather need pure text for further bash processing:

```<code>[
  {
    "given": "Fabio",
    "family": "Facchinelli",
    "affiliation": []
  },
  {
    "given": "Andreas P. M.",
    "family": "Weber",
    "affiliation": []
  }
]
</code>```

I thought of using jq, but couldn't figure out, how to just get:

"Fabio Facchinelli, Andreas P. M. Weber"

Do you know a solution (must not be jq)?

答:
Here's one way to do that with jq:

```<code>... | jq '.author[] | .given + " " + .family' | jq -s 'join(", ")'
</code>```

Outputs:

```<code>"Fabio Facchinelli, Andreas P. M. Weber"
</code>```

Body:
I'm trying to get the author names of this paper by using the CrossRef API with curl.

curl -LH "Accept: application/citeproc+json" http://dx.doi.org/10.3389/fpls.2011.00050 | jq .author

Of course I get a JSON as response, but rather need pure text for further bash processing:

[
  {
    "given": "Fabio",
    "family": "Facchinelli",
    "affiliation": []
  },
  {
    "given": "Andreas P. M.",
    "family": "Weber",
    "affiliation": []
  }
]

I thought of using jq, but couldn't figure out, how to just get:

"Fabio Facchinelli, Andreas P. M. Weber"

Do you know a solution (must not be jq)?

Body:
Here's one way to do that with jq:

... | jq '.author[] | .given + " " + .family' | jq -s 'join(", ")'

Outputs:

"Fabio Facchinelli, Andreas P. M. Weber"


问:
Get next year from the current NSDate?
I have a calendar application in which I want to get the next year from the current date (NSDate).

How can I do this?

答:
You can make NSDateComponents do all the hard work of calculating leap years and leap seconds:

```<code>NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:1];
NSDate *nextYear = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
</code>```

Title: Get next year from the current NSDate?

Body:
You can make NSDateComponents do all the hard work of calculating leap years and leap seconds:

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:1];
NSDate *nextYear = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];

ContentLicense: CC BY-SA 2.5


问:
Unable to distribute app on Android Wear in Google Play Developer console
Im trying to submit my newly created Android Wear watch face through Google Play Developer Console. The problem is checkbox "Distribute your app on Android Wear" in pricing and distribution section is disabled. I cant understand why.

What I did:

1) Uploaded screenshot for Android Wear

2) Uploaded 2 APK files in closed Beta releases. Both files are signed with one key, have different version names.  First is phone apk with embedded wear apk (minSdkVersion 23), second - standalone wear apk (minSdkVersion 25) has meta-data            android:name="com.google.android.wearable.standalone" android:value="true" in manifest file.

Everythings seems fine and app is ready to publish in production, except the "Distribute your app on Android Wear" checkbox which remains disabled.
What Im missing?

答:
I stumbled upon the exact same issue.

I had <uses-feature android:name="android.hardware.type.watch" /> in my manifest

I had <meta-data
            android:name="com.google.android.wearable.standalone"
            android:value="true" /> in my manifest

minSdk was set to 25

But still the checkbox for Wear distribution was disabled.

For fun I tried editing the HTML with Chrome's inspection tools, and removed the "disabled" attribute from the checkbox. Sure enough, the setting stuck after enabling the checkbox, and now Wear distribution is enabled. Give it a try!


问:
Protractor Element text value sendKeys and attribute error
i've been trying to run this code in protractor but i keep getting this error also i can't find a way to get the anpr_box_input text value anyhow.

Value: ManagedPromise::871 {[[PromiseStatus]]: "pending"}
    failed - should have a valid license number plate when screen contains as ANPR request
  Suite failed: ANPR Screen Content

Chrome version: 58.0.3029.110 (64-bit)
Dependencies:
"protractor": "5.1.2",
"jasmine-core": "~2.4.1",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"@types/jasmine": "2.5.36"

describe('ANPR Screen Content', function () {

```<code>it('should have a valid license number plate when screen contains as ANPR request', function () {

    var base_keyboard_ok = browser.driver.findElement(by.id('base-keyboard-ok'));

    var anpr_box_input = browser.driver.findElement(by.className('anpr-box-input'));
    //anpr_box_input.clear().then(function() { anpr_box_input.sendKeys('999'); }); tryed it before, didn't work
    anpr_box_input.clear().then(function() { anpr_box_input.setAttribute("value", "459"); });

    base_keyboard_ok.click();

    /* didn't work
    anpr_box_input.getText().then(function(text) {
        console.log("AQUI: " + text);
    });
    */

    //console.log("Value: " + anpr_box_input.getAttribute('value')); didn't work

    //working on..
    anpr_box_input.getAttribute('value').then(function(text) {
        console.log("Value: " + text);
    });

    //so i'll need something like
    expect(anpr_box_input.text).toEqual("1234");
});
</code>```

});

答:
Based on the provided info and HTML you can't set the value of the element with

anpr_box_input.sendKeys('999'); because it is not an input, it's a
.

anpr_box_input.setAttribute("value", "459"); will also not work because setAttribute is not a valid Protractor command. You first need to know how the field works, my guess is that it's a
 element that reflects the value of an other field that contains the original value. You need to locate that field and do a:

sendKeys()

browser.driver.executeScript('argument[0].setAttribute("name", "value")', element(by.css('#selector').getWebElement())

on it.

I also have 1 remark on you code. Based on the code you provided it looks like you have an Angular page, but you are using "vanila" webdriver commands to locate the elements, why don't you use the Protractor syntax with element(by.css('')) and so on?

Body:
i've been trying to run this code in protractor but i keep getting this error also i can't find a way to get the anpr_box_input text value anyhow.

Value: ManagedPromise::871 {[[PromiseStatus]]: "pending"}
    failed - should have a valid license number plate when screen contains as ANPR request
  Suite failed: ANPR Screen Content

Chrome version: 58.0.3029.110 (64-bit)
Dependencies:
"protractor": "5.1.2",
"jasmine-core": "~2.4.1",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"@types/jasmine": "2.5.36"

describe('ANPR Screen Content', function () {

it('should have a valid license number plate when screen contains as ANPR request', function () {

    var base_keyboard_ok = browser.driver.findElement(by.id('base-keyboard-ok'));

    var anpr_box_input = browser.driver.findElement(by.className('anpr-box-input'));
    //anpr_box_input.clear().then(function() { anpr_box_input.sendKeys('999'); }); tryed it before, didn't work
    anpr_box_input.clear().then(function() { anpr_box_input.setAttribute("value", "459"); });

    base_keyboard_ok.click();

    /* didn't work
    anpr_box_input.getText().then(function(text) {
        console.log("AQUI: " + text);
    });
    */

    //console.log("Value: " + anpr_box_input.getAttribute('value')); didn't work

    //working on..
    anpr_box_input.getAttribute('value').then(function(text) {
        console.log("Value: " + text);
    });

    //so i'll need something like
    expect(anpr_box_input.text).toEqual("1234");
});

});

Body:
Based on the provided info and HTML you can't set the value of the element with

anpr_box_input.sendKeys('999'); because it is not an input, it's a <div>.

anpr_box_input.setAttribute("value", "459"); will also not work because setAttribute is not a valid Protractor command. You first need to know how the field works, my guess is that it's a <div> element that reflects the value of an other field that contains the original value. You need to locate that field and do a:

sendKeys()

browser.driver.executeScript('argument[0].setAttribute("name", "value")', element(by.css('#selector').getWebElement())

on it.

I also have 1 remark on you code. Based on the code you provided it looks like you have an Angular page, but you are using "vanila" webdriver commands to locate the elements, why don't you use the Protractor syntax with element(by.css('')) and so on?


问:
How can one Tcl thread cause an event in another?
I have a system with multiple I/O interfaces, and I'm collecting the output of all of them into a common log.  Two of the interfaces are through well-behaved channels that are opened as file-like objects, and can be managed on an event basis with "fileevent readable".  The other two are the problem.

These are to a vendor-supplied library, which someone else has already kindly wrapped into a Tcl package (snoopy, FWIW).  However, the only read access is a blocking call, and there's nothing in the package that would cause an event equivalent to a fileevent.

I've figured out how to spawn a separate thread to block on the read, pull the result, and put it into a message queue for the main thread.  But having the main thread block on reading the queue would seem to defeat the purpose, especially since there are two queues it would have to block on.  And I haven't been able to get the reader to generate an event that can trigger the main thread to read the queue.

I've looked on the tcl.tk wiki to no avail so far.  I've tried using the uevent library to generate an event on a message push, but the event goes to the writing thread instead of the reading thread, which really doesn't help.  It seems like there should be some solution related to a Thread condition variable, but so far I haven't been able to find an appropriate design pattern for that use of the library.

If all else fails I'll fall back to a Tk event, but I'm trying to keep Tk out of this as it's meant to be an automated system with no GUI, and any mention of Tk pushes tclsh into wish and pops up a GUI window.

I feel like I'm close, but just missing something.

答:
Firstly, the main thread needs to run the event loop in order to receive events. The idiomatic way to do this is to use vwait forever once you've finished setting up your program (I assume you're not going to write to that variable) but if you are running Tk you already have an event loop (GUIs need event loops).

There are two ways to do the messaging between threads.

Thread events

The thread::send command uses events to dispatch code to execute (the message) between threads. All you need to do is to tell the worker thread what the main thread's ID is so it knows where to send to. Note that you may well want to send the event asynchronously, like this:

```<code>thread::send -async $mainID [list eventReceiver "something happened" $payload]
</code>```

Pipelines

If you're using Tcl 8.6, you can use chan pipe to create an unnamed OS pipeline. You can then use normal fileevents, etc., to deliver information from thread to another that way.

```<code># In master
lassign [chan pipe] readSide writeSide
thread::transfer $worker $readSide
thread::send $worker [list variable pipe $readSide]
fconfigure $writeSide -blocking 0
fileevent $writeSide readable [list handleLine $writeSide]

# In worker
fconfigure $pipe -blocking 0 -buffering line
puts $pipe "got event: $payload"
</code>```

It's probably easier to use thread events in retrospect! (The main advantage of a pipe is that you can also put the worker in another process if necessary.)

Body:
Firstly, the main thread needs to run the event loop in order to receive events. The idiomatic way to do this is to use vwait forever once you've finished setting up your program (I assume you're not going to write to that variable) but if you are running Tk you already have an event loop (GUIs need event loops).

There are two ways to do the messaging between threads.

Thread events

The thread::send command uses events to dispatch code to execute (the message) between threads. All you need to do is to tell the worker thread what the main thread's ID is so it knows where to send to. Note that you may well want to send the event asynchronously, like this:

thread::send -async $mainID [list eventReceiver "something happened" $payload]

Pipelines

If you're using Tcl 8.6, you can use chan pipe to create an unnamed OS pipeline. You can then use normal fileevents, etc., to deliver information from thread to another that way.

# In master
lassign [chan pipe] readSide writeSide
thread::transfer $worker $readSide
thread::send $worker [list variable pipe $readSide]
fconfigure $writeSide -blocking 0
fileevent $writeSide readable [list handleLine $writeSide]

# In worker
fconfigure $pipe -blocking 0 -buffering line
puts $pipe "got event: $payload"

It's probably easier to use thread events in retrospect! (The main advantage of a pipe is that you can also put the worker in another process if necessary.)


问:
GitLab CI. Path in yml for different users
I'm trying to set up GitLab CI for .net project. Now I'm writing script in yml file. What I want to know: the path to the msbuild.exe and mstest.exe may be different for the different team members, how the same yml script may work for different users?

Or may be I'm understand how GitLab CI work in wrong way?

答:
The path to the mstest.exe and all other referenced executable and files is based on the machine that has the GitLab runner running.

What's on your machine or anyone else's doesn't matter; Only the build server matters, so write your gitlab .yml accordingly.

Sample .net yml file
```<code>    ##variables:
## increase indentation carefully, one space per cascade level.
## THIS IS YAML. NEVER USE TABS.
stages:
   - build
   - deploy

 #BUILD
# Builds all working branches
working:
  stage: build
  except:
   - master
  script:
   - echo "Build Stage"
   - echo "Restoring NuGet Packages..."
   - '"c:\nuget\nuget.exe" restore "SOLUTION PATH"'
   # - '"c:\nuget\nuget.exe" restore "ANOTHER ABSOLUTE PATH TO YOUR SOLUTION"'
   - ''
   - echo "Building Solutions..."
   - C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /consoleloggerparameters:ErrorsOnly /maxcpucount /nologo /property:Configuration=Release /verbosity:quiet "SOLUTION PATH"

# Builds all stable/master pushes
stable:
  stage: build
  only:
   - master
  script:
   - echo "Build Stage"
   - echo "Restoring NuGet Packages..."
   - '"c:\nuget\nuget.exe" restore "SOLUTION PATH"'
   # - '"c:\nuget\nuget.exe" restore "ANOTHER ABSOLUTE PATH TO YOUR SOLUTION"'
   - ''
   - echo "Building Solutions..."
   - C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /consoleloggerparameters:ErrorsOnly /maxcpucount /nologo /property:Configuration=Release /verbosity:quiet "SOLUTION PATH"

 #DEPLOY

  stage: deploy
  only:
    - dev
  script:
   - echo "Deploy Stage"
#SEND TO YOUR DEV SERVER

  ## deploy latest master to the correct servers
  stage: deploy

  script:
  - echo "Deploy Stage"
  only:
   - master
 #SEND TO YOUR PRODUCTION SERVER

  tags:
   - .NET
  #put tags here you put on your runners so you can hit the right runners when you push your code.

</code>```

Body:
The path to the mstest.exe and all other referenced executable and files is based on the machine that has the GitLab runner running.

What's on your machine or anyone else's doesn't matter; Only the build server matters, so write your gitlab .yml accordingly.

Sample .net yml file

    ##variables:
## increase indentation carefully, one space per cascade level.
## THIS IS YAML. NEVER USE TABS.
stages:
   - build
   - deploy

 #BUILD
# Builds all working branches
working:
  stage: build
  except:
   - master
  script:
   - echo "Build Stage"
   - echo "Restoring NuGet Packages..."
   - '"c:\nuget\nuget.exe" restore "SOLUTION PATH"'
   # - '"c:\nuget\nuget.exe" restore "ANOTHER ABSOLUTE PATH TO YOUR SOLUTION"'
   - ''
   - echo "Building Solutions..."
   - C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /consoleloggerparameters:ErrorsOnly /maxcpucount /nologo /property:Configuration=Release /verbosity:quiet "SOLUTION PATH"

# Builds all stable/master pushes
stable:
  stage: build
  only:
   - master
  script:
   - echo "Build Stage"
   - echo "Restoring NuGet Packages..."
   - '"c:\nuget\nuget.exe" restore "SOLUTION PATH"'
   # - '"c:\nuget\nuget.exe" restore "ANOTHER ABSOLUTE PATH TO YOUR SOLUTION"'
   - ''
   - echo "Building Solutions..."
   - C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /consoleloggerparameters:ErrorsOnly /maxcpucount /nologo /property:Configuration=Release /verbosity:quiet "SOLUTION PATH"

 #DEPLOY

  stage: deploy
  only:
    - dev
  script:
   - echo "Deploy Stage"
#SEND TO YOUR DEV SERVER

  ## deploy latest master to the correct servers
  stage: deploy

  script:
  - echo "Deploy Stage"
  only:
   - master
 #SEND TO YOUR PRODUCTION SERVER

  tags:
   - .NET
  #put tags here you put on your runners so you can hit the right runners when you push your code.


问:
How to merge two contents version with Quill.js?
I am synchronizing the content of the textarea with a server and I'd like to merge both in case of conflict to keep the differences without showing twice things that didn't changed.

Does anyone have a strategy of how we could do that?

答: This is not a trivial task. The two main approaches to do this is Operational Transform and Conflict Free Replicated Data Types. A couple libraries that do this is ShareJS and yjs.</p>


问:
Django handle photo upload
I have model whiuch has photo attachment.

```<code>class Forum_message(models.Model):
    text = models.TextField()
    photo = models.ImageField(upload_to= 'forum_attachments')
</code>```

I have my form(I prefer writing forms in pure html so I can have full access to modifying them)

```<code><form action="/forum_new" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="img_msg" type="file">
    <textarea name="new_msg"></textarea>
    <input type="submit" value="Submit"/>
</form>
</code>```

What do I write in my function
def forum_new(request): in views.py to handle file upload and save new forum message to database?

答:
I needed something like this:</p>

```<code>def forum_new(request):
    msg = Forum_message()
    msg.user = request.user
    if 'image' in request.FILES:
        msg.photo = request.FILES['image']

    msg.text = request.GET.get('text')
    msg.save()
</code>```

Title: Django handle photo upload

Body:
I have model whiuch has photo attachment.

class Forum_message(models.Model):
    text = models.TextField()
    photo = models.ImageField(upload_to= 'forum_attachments')

I have my form(I prefer writing forms in pure html so I can have full access to modifying them)

<form action="/forum_new" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="img_msg" type="file">
    <textarea name="new_msg"></textarea>
    <input type="submit" value="Submit"/>
</form>

What do I write in my function
def forum_new(request): in views.py to handle file upload and save new forum message to database?

Body:
I needed something like this:

def forum_new(request):
    msg = Forum_message()
    msg.user = request.user
    if 'image' in request.FILES:
        msg.photo = request.FILES['image']

    msg.text = request.GET.get('text')
    msg.save()


问:
Javascript - move all commas in a string to a new position
in a given string, I want to move all commas at the ends of words in a string to the end of the word before the word they are attached to.
ex: "sometime soon the, cat said let's, go!" would read: "sometime soon, the cat said, let's go!"
any suggestions?</p>

答:
Edit: Question was edited, this was an answer to a previous version of it. le_m's answer is a great answer, and I recommend using it.

-

Edit: I thought I'd add a little context regarding what I chose to do here.

Strings in Javascript are immutable, that means they can not be changed, but we can manage to create copies of them as we like. We can then, if we like, assign the new value and override the old variable of course.

As I don't necessarily think in "regex-way", I find it easiest to convert strings to arrays, using split(' '), and mapping over each word using functional map. To map, I pass an arrow function that is responsible for evaluating each word. Once I'm done working on my array, I join it back to a string.

```<code>let sentence = 'again, the cat said, let's go!'
let result = sentence.split(' ').map((word) => word[word.length -1] == ',' ? ','+word.substring(0,word.length -1) : word).join(' ')
</code>```

Body:
Edit: Question was edited, this was an answer to a previous version of it. le_m's answer is a great answer, and I recommend using it.

-

Edit: I thought I'd add a little context regarding what I chose to do here.

Strings in Javascript are immutable, that means they can not be changed, but we can manage to create copies of them as we like. We can then, if we like, assign the new value and override the old variable of course.

As I don't necessarily think in "regex-way", I find it easiest to convert strings to arrays, using split(' '), and mapping over each word using functional map. To map, I pass an arrow function that is responsible for evaluating each word. Once I'm done working on my array, I join it back to a string.

let sentence = 'again, the cat said, let's go!'
let result = sentence.split(' ').map((word) => word[word.length -1] == ',' ? ','+word.substring(0,word.length -1) : word).join(' ')


问:
Angular: Function not running after page load
I have a webpage that runs well, but on a certain route, it would not load certain functions. For example, this is code:

```<code>myApp.controller('people', ['$scope', function($scope) {

    $scope.$watch('$viewContentLoaded', function(){
        console.log('la 1');

        $scope.allPeople = function() {
            // This does not run when refreshed at https://www.website.com/people
            console.log('la 2');
        }
    })
]);
</code>```

This has the same behavior, la 1 works, not la 2:

```<code>myApp.controller('people', ['$scope', function($scope) {
    console.log('la 1');
    $scope.allPeople = function() {
        console.log('la 2');
    }
}]);
</code>```

These are routes:

```<code>myApp.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: '../../templates/all.html',
        controller: 'all'
    })
    .when('/people', {
        templateUrl: '../../templates/people.html',
        controller: 'people'
    })
});
</code>```

When I load https://www.website.com, and navigate to People tab, it loads list of people. But, when I load the page WHILE in the People tab, the page would load, but without the list: I see la 1 printed, not la 2.

How can I run the allPeople when refreshed from /people?

答:
The reason is that you only declared the function but never execute it.

```<code>myApp.controller('people', ['$scope', function($scope) {

     $scope.allPeople = function() {
          console.log('la 2');
     }

     $scope.$watch('$viewContentLoaded', function(){
         console.log('la 1');
         $scope.allPeople();
     });
]);
</code>```

Additionally don't declare it every time you route.
And don't forget to unregister the watch (thanks @NainishModi).

```<code>   myApp.controller('people', ['$scope', function($scope) {

     $scope.allPeople = $scope.allPeople || function() {
          console.log('la 2');
     }

     var deReg = $scope.$watch('$viewContentLoaded', function(){
         console.log('la 1');
         $scope.allPeople();
     })

      //deRegister watch
      $scope.$on('$destroy', deReg);
]);
</code>```

Body:
I have a webpage that runs well, but on a certain route, it would not load certain functions. For example, this is code:

myApp.controller('people', ['$scope', function($scope) {

    $scope.$watch('$viewContentLoaded', function(){
        console.log('la 1');

        $scope.allPeople = function() {
            // This does not run when refreshed at https://www.website.com/people
            console.log('la 2');
        }
    })
]);

This has the same behavior, la 1 works, not la 2:

myApp.controller('people', ['$scope', function($scope) {
    console.log('la 1');
    $scope.allPeople = function() {
        console.log('la 2');
    }
}]);

These are routes:

myApp.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: '../../templates/all.html',
        controller: 'all'
    })
    .when('/people', {
        templateUrl: '../../templates/people.html',
        controller: 'people'
    })
});

When I load https://www.website.com, and navigate to People tab, it loads list of people. But, when I load the page WHILE in the People tab, the page would load, but without the list: I see la 1 printed, not la 2.

How can I run the allPeople when refreshed from /people?

Body:
The reason is that you only declared the function but never execute it.

myApp.controller('people', ['$scope', function($scope) {

     $scope.allPeople = function() {
          console.log('la 2');
     }

     $scope.$watch('$viewContentLoaded', function(){
         console.log('la 1');
         $scope.allPeople();
     });
]);

Additionally don't declare it every time you route.
And don't forget to unregister the watch (thanks @NainishModi).

   myApp.controller('people', ['$scope', function($scope) {

     $scope.allPeople = $scope.allPeople || function() {
          console.log('la 2');
     }

     var deReg = $scope.$watch('$viewContentLoaded', function(){
         console.log('la 1');
         $scope.allPeople();
     })

      //deRegister watch
      $scope.$on('$destroy', deReg);
]);


问:
Remove padding in google chart?
I'm wondering why google charts add a blank padding when not specifying the top/right/left axises.

Select the image and you'll find a huge padding except the bottom which is already filled & that's why, how to remove that?

Specifically, Talking about the right and left paddings.

Thank you.

答:
Unfortunately, as said in Chart Margins documentation you can set only the minimum margin on each side of the chart.

Google adds some unnecessary margin (mostly on top) itself and there is no parameter which can stop this behavior.

Title: Remove padding in google chart?


问:
How to Get Sunday of any day
i have an issue with get day in android. in my activity i have a button, when i tap this button, my current day will Increased to 1 day and the last day is sunday.
If i tap the button, until the current day increases past the next week, the last day will be the next Sunday of the following week. My code works properly when I click the first time, when i tap my button again my current day is up to 7 days, I did the research but did not find the results as expected. Hope you can help.
Example like this:
Every time i press the button:

MONDAY 5/6/2017 - SUNDAY 11/6/2017

TUESDAY 6/6/2017 - SUNDAY 11/6/2017

WEDNESDAY 7/6/2017 - SUNDAY 11/6/2017

THURSDAY 8/6/2017 - SUNDAY 11/6/2017

FRIDAY 9/6/2017 - SUNDAY 11/6/2017

SATURDAY 10/6/2017 - SUNDAY 11/6/2017

SUNDAY 11/6/2017 - SUNDAY 11/6/2017

MONDAY 12/6/2017 - SUNDAY 18/6/2017

TUESDAY 13/6/2017 - SUNDAY 18/6/2017

........

this is my code:
Thank you in advance.

```<code>     btnChooseDay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                    mCalendar.add(Calendar.DAY_OF_WEEK, 1);
                    tvDayChoose.setText(getNameOfDay(mCalendar.get(Calendar.DAY_OF_WEEK)) + ", " + mSimpleDateFormat.format(mCalendar.getTime()));
                    mCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY );
                    tvDayChoose.append(" - " + mSimpleDateFormat.format(mCalendar.getTime()));
                }
            });
</code>```

答:
You are doing almost everything right. You setting and fetching date correctly, However , you are doing it on same date by this line (mCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY );. As a result, you are getting into loop.
Lets say today is june 5  ( monday), so when you first add 1, it becomes june 6(tuesday), so your sunday date is june 4 which you set back to your date. Now, you mCalendar is set to June 4, and when you click again,you add 1 and it becomes june 5 and your sunday becomes June 4 again, and you set that to your mCalendar again, which sets it back to june 4. This keeps repeating for ever. So your solution is to use new Calendar instance to get sunday , but keep adding 1 on the mCalendar.  You may find better way to create calendar instance,but make few changes like to keep things in proper state :

Add this two line after you add 1 on mCalendar ,

```<code>Calendar sundayCalendar=Calendar.getInstance();
    sundayCalendar.setTime(mCalendar.getTime());
</code>```

Then set Sunday date in this new Calendar instance and use it , instead of using mCalenar. Now your mCalendar keeps it state of increment and sundayCalendar returns your sunday date based on mCalendar which is incremented by 1 on every click.

```<code> sundayCalendar.set(Calendar.DAY_OF_WEEK, mCalendar.get(Calendar.SUNDAY));

 tvDayChoose.append(" - " + mSimpleDateFormat.format(sundayCalendar.getTime()));
</code>```

A simple class to show usage is as below :

```<code>public class DateSunday {

static Calendar mCalendar= Calendar.getInstance();

public static void main(String[] args){

    for(int i=0;i<10;i++){
        onClick();
    }
}

public static void onClick(){
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
    mCalendar.add(Calendar.DAY_OF_WEEK, 1);

    Calendar sundayCalendar=Calendar.getInstance();
    sundayCalendar.setTime(mCalendar.getTime());
    sundayCalendar.set(Calendar.DAY_OF_WEEK, mCalendar.get(Calendar.SUNDAY));

    System.out.println(" - " + mSimpleDateFormat.format(sundayCalendar.getTime()));

    }
}
</code>```

Title: How to Get Sunday of any day

Body:
i have an issue with get day in android. in my activity i have a button, when i tap this button, my current day will Increased to 1 day and the last day is sunday.
If i tap the button, until the current day increases past the next week, the last day will be the next Sunday of the following week. My code works properly when I click the first time, when i tap my button again my current day is up to 7 days, I did the research but did not find the results as expected. Hope you can help.
Example like this:
Every time i press the button:

MONDAY 5/6/2017 - SUNDAY 11/6/2017

TUESDAY 6/6/2017 - SUNDAY 11/6/2017

WEDNESDAY 7/6/2017 - SUNDAY 11/6/2017

THURSDAY 8/6/2017 - SUNDAY 11/6/2017

FRIDAY 9/6/2017 - SUNDAY 11/6/2017

SATURDAY 10/6/2017 - SUNDAY 11/6/2017

SUNDAY 11/6/2017 - SUNDAY 11/6/2017

MONDAY 12/6/2017 - SUNDAY 18/6/2017

TUESDAY 13/6/2017 - SUNDAY 18/6/2017

........

this is my code:
Thank you in advance.

     btnChooseDay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                    mCalendar.add(Calendar.DAY_OF_WEEK, 1);
                    tvDayChoose.setText(getNameOfDay(mCalendar.get(Calendar.DAY_OF_WEEK)) + ", " + mSimpleDateFormat.format(mCalendar.getTime()));
                    mCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY );
                    tvDayChoose.append(" - " + mSimpleDateFormat.format(mCalendar.getTime()));
                }
            });

Body:
You are doing almost everything right. You setting and fetching date correctly, However , you are doing it on same date by this line (mCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY );. As a result, you are getting into loop.
Lets say today is june 5  ( monday), so when you first add 1, it becomes june 6(tuesday), so your sunday date is june 4 which you set back to your date. Now, you mCalendar is set to June 4, and when you click again,you add 1 and it becomes june 5 and your sunday becomes June 4 again, and you set that to your mCalendar again, which sets it back to june 4. This keeps repeating for ever. So your solution is to use new Calendar instance to get sunday , but keep adding 1 on the mCalendar.  You may find better way to create calendar instance,but make few changes like to keep things in proper state :

Add this two line after you add 1 on mCalendar ,

Calendar sundayCalendar=Calendar.getInstance();
    sundayCalendar.setTime(mCalendar.getTime());

Then set Sunday date in this new Calendar instance and use it , instead of using mCalenar. Now your mCalendar keeps it state of increment and sundayCalendar returns your sunday date based on mCalendar which is incremented by 1 on every click.

 sundayCalendar.set(Calendar.DAY_OF_WEEK, mCalendar.get(Calendar.SUNDAY));

 tvDayChoose.append(" - " + mSimpleDateFormat.format(sundayCalendar.getTime()));

A simple class to show usage is as below :

public class DateSunday {

static Calendar mCalendar= Calendar.getInstance();

public static void main(String[] args){

    for(int i=0;i<10;i++){
        onClick();
    }
}

public static void onClick(){
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
    mCalendar.add(Calendar.DAY_OF_WEEK, 1);

    Calendar sundayCalendar=Calendar.getInstance();
    sundayCalendar.setTime(mCalendar.getTime());
    sundayCalendar.set(Calendar.DAY_OF_WEEK, mCalendar.get(Calendar.SUNDAY));

    System.out.println(" - " + mSimpleDateFormat.format(sundayCalendar.getTime()));

    }
}


问:
IBM MobileFirst 8 Invalid client signature
I am using MobileFirst 8 to run my web  application. After creating a JAVA authentication adapter and a challenge handler, my application works fine on windows however I am facing the error below on Ubuntu :

```<code>[/mfp/api/registration/v1/self] failure. state: 403, response: undefined
Authorization request failed with response: "Invalid client signature."
</code>```

I noticed that com.mfp.oauth.application.data and com.mfp.oauth.clientid are returned as null.

Any idea about this issue ?

答:
The root cause is that ibm web sdk has a minimum server version requirements.
you solved this by removing and installing the server again. There are two other appropriate fixes for this:

Recommended way: update your mfpf server by installing the latest fixpack from here.

OR,

downgrade your sdk by running:

```<code>npm install ibm-mfp-web-sdk@8.0.2016070716
</code>```

The above version fixed it for me but your MFPF server version might be different so you might need older packages. to see available versions:

```<code>npm show ibm-mfp-web-sdk@* version
</code>```

Body:
I am using MobileFirst 8 to run my web  application. After creating a JAVA authentication adapter and a challenge handler, my application works fine on windows however I am facing the error below on Ubuntu :

[/mfp/api/registration/v1/self] failure. state: 403, response: undefined
Authorization request failed with response: "Invalid client signature."

I noticed that com.mfp.oauth.application.data and com.mfp.oauth.clientid are returned as null.

Any idea about this issue ?

Body:
The root cause is that ibm web sdk has a minimum server version requirements.
you solved this by removing and installing the server again. There are two other appropriate fixes for this:

Recommended way: update your mfpf server by installing the latest fixpack from here.

OR,

downgrade your sdk by running:

npm install ibm-mfp-web-sdk@8.0.2016070716

The above version fixed it for me but your MFPF server version might be different so you might need older packages. to see available versions:

npm show ibm-mfp-web-sdk@* version


问:
Chef: Enabling Jenkins security causes plugin installation to fail
I am currently using Chef to deploy a Jenkins instance on a managed node. I am using the following public supermarket cookbook: https://supermarket.chef.io/cookbooks/jenkins .

I am using the following code in my recipe file to enable authentication:

```<code>jenkins_script 'activate global security' do
  command <<-EOH.gsub(/^ {4}/, '')
      import jenkins.model.*
      import hudson.security.*
      def instance = Jenkins.getInstance()

      def hudsonRealm = new HudsonPrivateSecurityRealm(false)
      hudsonRealm.createAccount("Administrator","Password")
      instance.setSecurityRealm(hudsonRealm)
      instance.save()

      def strategy = new GlobalMatrixAuthorizationStrategy()
        strategy.add(Jenkins.ADMINISTER, "Administrator")
        instance.setAuthorizationStrategy(strategy)

      instance.save()
  EOH
 end
</code>```

This works great to setup security on the instance the first time the recipe is run on the managed node. It creates an administrator user with administrator permissions on the Jenkins server. In addition to enabling security on the Jenkins instance, plugins are also installed using this recipe.

Once security has been enabled, installation of plugins which do not yet exist (but are specified to be installed), fail:

```<code>ERROR: anonymous is missing the Overall/Read permission
</code>```

I assume this is an error related to the newly created administrator account, and Chef attempting to install the plugins using the anonymous user as opposed to the administrator user. Is there anything that should be set in my recipe file in order to work around this permissions issue?

The goal here is that in the event a plugin is upgraded to an undesired version or uninstalled completely, running the recipe will reinstall / rollback any plugin changes. Currently this does not appear to be possible if I also have security enabled on the Jenkins instance.

EDIT It should also be noted that currently each time I need to repair plugins in this way, I have to disable security then run the entire recipe (plugin installation + security enable).

Thanks for any help!

答: The jenkins_plugin resource doesn't appear to expose any authentication options so you'll probably need to build your own resource. If you dive in to the code you'll see that the underlying executor layer in the cookbook does support auth (and a whole bunch of other stuff) so it might be easy to do in a copy-fork (and send us a patch) of just that resource.

Body:
I am currently using Chef to deploy a Jenkins instance on a managed node. I am using the following public supermarket cookbook: https://supermarket.chef.io/cookbooks/jenkins .

I am using the following code in my recipe file to enable authentication:

jenkins_script 'activate global security' do
  command <<-EOH.gsub(/^ {4}/, '')
      import jenkins.model.*
      import hudson.security.*
      def instance = Jenkins.getInstance()

      def hudsonRealm = new HudsonPrivateSecurityRealm(false)
      hudsonRealm.createAccount("Administrator","Password")
      instance.setSecurityRealm(hudsonRealm)
      instance.save()

      def strategy = new GlobalMatrixAuthorizationStrategy()
        strategy.add(Jenkins.ADMINISTER, "Administrator")
        instance.setAuthorizationStrategy(strategy)

      instance.save()
  EOH
 end

This works great to setup security on the instance the first time the recipe is run on the managed node. It creates an administrator user with administrator permissions on the Jenkins server. In addition to enabling security on the Jenkins instance, plugins are also installed using this recipe.

Once security has been enabled, installation of plugins which do not yet exist (but are specified to be installed), fail:

ERROR: anonymous is missing the Overall/Read permission

I assume this is an error related to the newly created administrator account, and Chef attempting to install the plugins using the anonymous user as opposed to the administrator user. Is there anything that should be set in my recipe file in order to work around this permissions issue?

The goal here is that in the event a plugin is upgraded to an undesired version or uninstalled completely, running the recipe will reinstall / rollback any plugin changes. Currently this does not appear to be possible if I also have security enabled on the Jenkins instance.

EDIT It should also be noted that currently each time I need to repair plugins in this way, I have to disable security then run the entire recipe (plugin installation + security enable).

Thanks for any help!


问:
Use computed columns more than once in same query
I have this recurring issue where I want to use a value I computed in a select query more than once. Here's an example

```<code>SELECT
  complicated_function(x) as foo,
  another_complicated_function(y) as bar,
  complicated_function(x)/another_complicated_function(y) as foo_bar_rate
FROM my_table;
</code>```

What's the simplest way to write this query? Ideally, I'd like to write

```<code>SELECT
  complicated_function(x) as foo
  another_complicated_function(y) as bar,
  foo/bar as foo_bar_rate
FROM my_table;
</code>```

This question isn't about the specific values being computing, it's about how to write this query in a simpler way that can be more easily maintained.

答:
Your answer using a CTE is generally good. A couple of suggestions, though:

```<code>SELECT *, foo / NULLIF(bar, 0) AS foo_bar_rate  -- defend against div0
FROM  (
   SELECT complicated_function(x)         AS foo
        , another_complicated_function(y) AS bar
   FROM   my_table
   --  OFFSET 0  -- see below
   ) sub;
</code>```

A CTE (though easier to read to some) is typically more expensive than a plain subquery in Postgres. If performance is relevant, only use CTEs where you actually need them. In this case, you don't.

Postgres might flatten the subquery in its query plan, and if cost settings and server config are good, that's typically also the best course of action. If you know better (you sure?) you can use the undocumented "query hint" OFFSET 0, which is logical noise, but forces separate execution of the subquery.

How can I prevent Postgres from inlining a subquery?

To keep the code short, you can use SELECT * in the outer SELECT. (Since you complained you'd have to add all columns to the main query.)

Use NULLIF(bar, 0) to defend against possible division by 0 exceptions - unless another_complicated_function(y) can never return 0.

Body:
I have this recurring issue where I want to use a value I computed in a select query more than once. Here's an example

SELECT
  complicated_function(x) as foo,
  another_complicated_function(y) as bar,
  complicated_function(x)/another_complicated_function(y) as foo_bar_rate
FROM my_table;

What's the simplest way to write this query? Ideally, I'd like to write

SELECT
  complicated_function(x) as foo
  another_complicated_function(y) as bar,
  foo/bar as foo_bar_rate
FROM my_table;

This question isn't about the specific values being computing, it's about how to write this query in a simpler way that can be more easily maintained.

Body:
Your answer using a CTE is generally good. A couple of suggestions, though:

SELECT *, foo / NULLIF(bar, 0) AS foo_bar_rate  -- defend against div0
FROM  (
   SELECT complicated_function(x)         AS foo
        , another_complicated_function(y) AS bar
   FROM   my_table
   --  OFFSET 0  -- see below
   ) sub;

A CTE (though easier to read to some) is typically more expensive than a plain subquery in Postgres. If performance is relevant, only use CTEs where you actually need them. In this case, you don't.

Postgres might flatten the subquery in its query plan, and if cost settings and server config are good, that's typically also the best course of action. If you know better (you sure?) you can use the undocumented "query hint" OFFSET 0, which is logical noise, but forces separate execution of the subquery.

How can I prevent Postgres from inlining a subquery?

To keep the code short, you can use SELECT * in the outer SELECT. (Since you complained you'd have to add all columns to the main query.)

Use NULLIF(bar, 0) to defend against possible division by 0 exceptions - unless another_complicated_function(y) can never return 0.


问:
SimonSays sequence is always incorrect, even if userChoice is matching
I'm trying to create a SimonSays-game but I'm having problems with the inputCheck()-function.

When a user presses a button, the variable userChoice equals whatever color the user pressed down. Then the inputCheck-function is called. The problem is that it always gives you an alert that you lost and ends the game, even if the user pressed the correct color. I added console.logs that log both user input and the current sequence step in the console.

Any help is appreciated. Thanks!

var gameRunning = false;
var userClick = "";
var correctSequence = true;
var sequence = [];
var sequenceCountDisplay = document.getElementById("sequenceCountDisplay");
var currentIndex = 0;

var startButton = document.getElementById("startButton");
startButton.addEventListener("click", startGame);

var buttonGreen = document.getElementById("buttonGreen");
buttonGreen.addEventListener("click", buttonPressGreen);
var buttonRed = document.getElementById("buttonRed");
buttonRed.addEventListener("click", buttonPressRed);
var buttonBlue = document.getElementById("buttonBlue");
buttonBlue.addEventListener("click", buttonPressBlue);
var buttonYellow = document.getElementById("buttonYellow");
buttonYellow.addEventListener("click", buttonPressYellow);

var greenSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3");
var redSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3");
var yellowSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3");
var blueSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3");

function buttonPressGreen(){
  greenSound.play();
  userClick = "green";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}
function buttonPressRed(){
  redSound.play();
  userClick = "red";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}
function buttonPressYellow(){
  yellowSound.play();
  userClick = "yellow";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}
function buttonPressBlue(){
  blueSound.play();
  userClick = "blue";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}

function generateSequenceStep() {
 var randomNumber = Math.floor(Math.random() * 4);

 switch(randomNumber){
  case 0: sequence.push("green");
   break;
  case 1: sequence.push("red");
   break;
  case 2: sequence.push("yellow");
   break;
  case 3: sequence.push("blue");
   break;
 }
}

function playBackSequence() {
 currentIndex = 0;
 setInterval(function(){
  if (sequence[currentIndex] == "green") {
   buttonGreen.style.opacity = "0.4";
   greenSound.play();
  }else if(sequence[currentIndex] == "red"){
   buttonRed.style.opacity = "0.4";
   redSound.play();
  }else if(sequence[currentIndex] == "yellow"){
   buttonYellow.style.opacity = "0.4";
   yellowSound.play();
  }else if(sequence[currentIndex] == "blue"){
   buttonBlue.style.opacity = "0.4";
   blueSound.play();
  }
  currentIndex++;
  setTimeout(function(){
   buttonGreen.style.opacity = "1";
   buttonRed.style.opacity = "1";
   buttonYellow.style.opacity = "1";
   buttonBlue.style.opacity = "1";
  }, 500);
 }, 1000);
 currentIndex = 0;
}

function inputCheck(){
 if (userClick == sequence[currentIndex]) {
  currentIndex++;
 }else{
  correctSequence = false;
 }

 if (correctSequence === false) {
  gameOver();
 }else if (currentIndex >= sequence.length) {
  nextRound();
 }
}

function gameOver(){
 if (!correctSequence) {
  alert("Game Over! You were able to remember " + sequence.length + " steps!");
  currentIndex = 0;
  gameRunning = false;
 }
}

function startGame(){
 gameRunning = true;
 currentIndex = 0;
 sequence = [];
 correctSequence = true;
 generateSequenceStep();
 generateSequenceStep();
 sequenceCountDisplay.innerHTML = sequence.length;
 playBackSequence();

}

function nextRound(){
 correctSequence = true;
 currentIndex = 0;
 generateSequenceStep();
 sequenceCountDisplay.innerHTML = sequence.length;
 playBackSequence();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*General ----------------------------------------------*/

body {}

#pageContainer {
 display: block;
 position: relative;
 text-align: center;
 margin: auto;
 height: 100%;
 width: 100%;
}

/*------------------------------------------------------*/

/*Button Styles -----------------------------------------*/

#buttons {
 max-width: 720px;
 width: 100%;
 height: 100%;
 margin: auto;
 z-index: -1;
 stroke: #000;
 stroke-miterlimit: 10;
 stroke-width: 3px;
}

#buttonYellow {
 fill: #fcee21;
}
#buttonYellow:hover {
 fill: #fcf14f;
 stroke-width: 4px;
}
#buttonYellow:active {
 fill: #c9bc03;
 stroke-width: 3px;
}

#buttonGreen {
 fill: #00dc00;
}
#buttonGreen:hover {
 fill: #1aff1a;
 stroke-width: 4px;
}
#buttonGreen:active {
 fill: #008000;
 stroke-width: 3px;
}

#buttonRed {
 fill: red;
}
#buttonRed:hover {
 fill: #ff4d4d;
 stroke-width: 4px;
}
#buttonRed:active {
 fill: #990000;
 stroke-width: 3px;
}

#buttonBlue {
 fill: blue;
}
#buttonBlue:hover {
 fill: #3333ff;
 stroke-width: 4px;
}
#buttonBlue:active {
 fill: #000099;
 stroke-width: 3px;
}

/*------------------------------------------------------*/

/*Center Control --------------------------*/

#center {
 position: relative;
 top: -500px;
 left: -35px;
 margin: auto;
 width: 100%;
 text-align: center;
 font-size: 35px;
 max-width: 200px;
}

#sequenceCountDisplay {
 margin: 20px;
 font-size: 45px;
}

#startButton {
 margin: 20px;
 font-size: 20px;
}</code>```

   <svg id="buttons" viewBox="0 0 500 500"><title>Buttons</title>
    <path id="buttonYellow" d="M56.08,238.5h46.85c5.93,0,7.28,1.15,8.19,6.92,7.53,47.9,43.75,84,91.68,91.46,5.25.81,6.66,2.32,6.66,7.51q0,47.54-.06,95.09c0,5.33-1.16,6.41-6.63,6A215.32,215.32,0,0,1,96.47,408.82,213.45,213.45,0,0,1,48,364.3c-23.49-29.56-38.7-62.89-44.3-100.39-.91-6.09-1.61-12.21-2.13-18.35-.42-5,1.67-7,6.75-7q23.89,0,47.77,0Z"/>
    <path id="buttonGreen" d="M56.08,208.57h46.85c5.93,0,7.28-1.15,8.19-6.92,7.53-47.9,43.75-84,91.68-91.46,5.25-.81,6.66-2.32,6.66-7.51q0-47.54-.06-95.09c0-5.33-1.16-6.41-6.63-6A215.32,215.32,0,0,0,96.47,38.25,213.45,213.45,0,0,0,48,82.77c-23.49,29.56-38.7,62.89-44.3,100.39-.91,6.09-1.61,12.21-2.13,18.35-.42,5,1.67,7,6.75,7q23.89,0,47.77,0Z"/>
    <path id="buttonRed" d="M394.08,208.57H347.23c-5.93,0-7.28-1.15-8.19-6.92-7.53-47.9-43.75-84-91.68-91.46-5.25-.81-6.66-2.32-6.66-7.51q0-47.54.06-95.09c0-5.33,1.16-6.41,6.63-6A215.32,215.32,0,0,1,353.69,38.25a213.45,213.45,0,0,1,48.5,44.52c23.49,29.56,38.7,62.89,44.3,100.39.91,6.09,1.61,12.21,2.13,18.35.42,5-1.67,7-6.75,7q-23.89,0-47.77,0Z"/>
    <path id="buttonBlue" d="M394.08,238.5H347.23c-5.93,0-7.28,1.15-8.19,6.92-7.53,47.9-43.75,84-91.68,91.46-5.25.81-6.66,2.32-6.66,7.51q0,47.54.06,95.09c0,5.33,1.16,6.41,6.63,6a215.32,215.32,0,0,0,106.29-36.68,213.45,213.45,0,0,0,48.5-44.52c23.49-29.56,38.7-62.89,44.3-100.39.91-6.09,1.61-12.21,2.13-18.35.42-5-1.67-7-6.75-7q-23.89,0-47.77,0Z"/>
  </svg>

0

   <button id="startButton" type="button">Start New Game</button>

```

答:
currentIndex isn't being set to 0 properly after playBackSequence()

Change the function to use a temporary variable:

```<code>function playBackSequence() {
    tmpCurrentIndex = currentIndex;
    setInterval(function(){
        if (sequence[tmpCurrentIndex] == "green") {
            buttonGreen.style.opacity = "0.4";
            greenSound.play();
        }else if(sequence[tmpCurrentIndex] == "red"){
            buttonRed.style.opacity = "0.4";
            redSound.play();
        }else if(sequence[tmpCurrentIndex] == "yellow"){
            buttonYellow.style.opacity = "0.4";
            yellowSound.play();
        }else if(sequence[tmpCurrentIndex] == "blue"){
            buttonBlue.style.opacity = "0.4";
            blueSound.play();
        }
        tmpCurrentIndex++;
        setTimeout(function(){
            buttonGreen.style.opacity = "1";
            buttonRed.style.opacity = "1";
            buttonYellow.style.opacity = "1";
            buttonBlue.style.opacity = "1";
        }, 500);
    }, 1000);
    currentIndex = 0;
}
</code>```

Body:
I'm trying to create a SimonSays-game but I'm having problems with the inputCheck()-function.

When a user presses a button, the variable userChoice equals whatever color the user pressed down. Then the inputCheck-function is called. The problem is that it always gives you an alert that you lost and ends the game, even if the user pressed the correct color. I added console.logs that log both user input and the current sequence step in the console.

Any help is appreciated. Thanks!

var gameRunning = false;
var userClick = "";
var correctSequence = true;
var sequence = [];
var sequenceCountDisplay = document.getElementById("sequenceCountDisplay");
var currentIndex = 0;

var startButton = document.getElementById("startButton");
startButton.addEventListener("click", startGame);

var buttonGreen = document.getElementById("buttonGreen");
buttonGreen.addEventListener("click", buttonPressGreen);
var buttonRed = document.getElementById("buttonRed");
buttonRed.addEventListener("click", buttonPressRed);
var buttonBlue = document.getElementById("buttonBlue");
buttonBlue.addEventListener("click", buttonPressBlue);
var buttonYellow = document.getElementById("buttonYellow");
buttonYellow.addEventListener("click", buttonPressYellow);

var greenSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3");
var redSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3");
var yellowSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3");
var blueSound = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3");

function buttonPressGreen(){
  greenSound.play();
  userClick = "green";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}
function buttonPressRed(){
  redSound.play();
  userClick = "red";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}
function buttonPressYellow(){
  yellowSound.play();
  userClick = "yellow";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}
function buttonPressBlue(){
  blueSound.play();
  userClick = "blue";
  if (gameRunning) {
   inputCheck();
  }
  console.log(userClick);
  console.log(sequence[currentIndex]);
}

function generateSequenceStep() {
 var randomNumber = Math.floor(Math.random() * 4);

 switch(randomNumber){
  case 0: sequence.push("green");
   break;
  case 1: sequence.push("red");
   break;
  case 2: sequence.push("yellow");
   break;
  case 3: sequence.push("blue");
   break;
 }
}

function playBackSequence() {
 currentIndex = 0;
 setInterval(function(){
  if (sequence[currentIndex] == "green") {
   buttonGreen.style.opacity = "0.4";
   greenSound.play();
  }else if(sequence[currentIndex] == "red"){
   buttonRed.style.opacity = "0.4";
   redSound.play();
  }else if(sequence[currentIndex] == "yellow"){
   buttonYellow.style.opacity = "0.4";
   yellowSound.play();
  }else if(sequence[currentIndex] == "blue"){
   buttonBlue.style.opacity = "0.4";
   blueSound.play();
  }
  currentIndex++;
  setTimeout(function(){
   buttonGreen.style.opacity = "1";
   buttonRed.style.opacity = "1";
   buttonYellow.style.opacity = "1";
   buttonBlue.style.opacity = "1";
  }, 500);
 }, 1000);
 currentIndex = 0;
}

function inputCheck(){
 if (userClick == sequence[currentIndex]) {
  currentIndex++;
 }else{
  correctSequence = false;
 }

 if (correctSequence === false) {
  gameOver();
 }else if (currentIndex >= sequence.length) {
  nextRound();
 }
}

function gameOver(){
 if (!correctSequence) {
  alert("Game Over! You were able to remember " + sequence.length + " steps!");
  currentIndex = 0;
  gameRunning = false;
 }
}

function startGame(){
 gameRunning = true;
 currentIndex = 0;
 sequence = [];
 correctSequence = true;
 generateSequenceStep();
 generateSequenceStep();
 sequenceCountDisplay.innerHTML = sequence.length;
 playBackSequence();

}

function nextRound(){
 correctSequence = true;
 currentIndex = 0;
 generateSequenceStep();
 sequenceCountDisplay.innerHTML = sequence.length;
 playBackSequence();
}

/*General ----------------------------------------------*/

body {}

#pageContainer {
 display: block;
 position: relative;
 text-align: center;
 margin: auto;
 height: 100%;
 width: 100%;
}

/*------------------------------------------------------*/

/*Button Styles -----------------------------------------*/

#buttons {
 max-width: 720px;
 width: 100%;
 height: 100%;
 margin: auto;
 z-index: -1;
 stroke: #000;
 stroke-miterlimit: 10;
 stroke-width: 3px;
}

#buttonYellow {
 fill: #fcee21;
}
#buttonYellow:hover {
 fill: #fcf14f;
 stroke-width: 4px;
}
#buttonYellow:active {
 fill: #c9bc03;
 stroke-width: 3px;
}

#buttonGreen {
 fill: #00dc00;
}
#buttonGreen:hover {
 fill: #1aff1a;
 stroke-width: 4px;
}
#buttonGreen:active {
 fill: #008000;
 stroke-width: 3px;
}

#buttonRed {
 fill: red;
}
#buttonRed:hover {
 fill: #ff4d4d;
 stroke-width: 4px;
}
#buttonRed:active {
 fill: #990000;
 stroke-width: 3px;
}

#buttonBlue {
 fill: blue;
}
#buttonBlue:hover {
 fill: #3333ff;
 stroke-width: 4px;
}
#buttonBlue:active {
 fill: #000099;
 stroke-width: 3px;
}

/*------------------------------------------------------*/

/*Center Control --------------------------*/

#center {
 position: relative;
 top: -500px;
 left: -35px;
 margin: auto;
 width: 100%;
 text-align: center;
 font-size: 35px;
 max-width: 200px;
}

#sequenceCountDisplay {
 margin: 20px;
 font-size: 45px;
}

#startButton {
 margin: 20px;
 font-size: 20px;
}

   <svg id="buttons" viewBox="0 0 500 500"><title>Buttons</title>
    <path id="buttonYellow" d="M56.08,238.5h46.85c5.93,0,7.28,1.15,8.19,6.92,7.53,47.9,43.75,84,91.68,91.46,5.25.81,6.66,2.32,6.66,7.51q0,47.54-.06,95.09c0,5.33-1.16,6.41-6.63,6A215.32,215.32,0,0,1,96.47,408.82,213.45,213.45,0,0,1,48,364.3c-23.49-29.56-38.7-62.89-44.3-100.39-.91-6.09-1.61-12.21-2.13-18.35-.42-5,1.67-7,6.75-7q23.89,0,47.77,0Z"/>
    <path id="buttonGreen" d="M56.08,208.57h46.85c5.93,0,7.28-1.15,8.19-6.92,7.53-47.9,43.75-84,91.68-91.46,5.25-.81,6.66-2.32,6.66-7.51q0-47.54-.06-95.09c0-5.33-1.16-6.41-6.63-6A215.32,215.32,0,0,0,96.47,38.25,213.45,213.45,0,0,0,48,82.77c-23.49,29.56-38.7,62.89-44.3,100.39-.91,6.09-1.61,12.21-2.13,18.35-.42,5,1.67,7,6.75,7q23.89,0,47.77,0Z"/>
    <path id="buttonRed" d="M394.08,208.57H347.23c-5.93,0-7.28-1.15-8.19-6.92-7.53-47.9-43.75-84-91.68-91.46-5.25-.81-6.66-2.32-6.66-7.51q0-47.54.06-95.09c0-5.33,1.16-6.41,6.63-6A215.32,215.32,0,0,1,353.69,38.25a213.45,213.45,0,0,1,48.5,44.52c23.49,29.56,38.7,62.89,44.3,100.39.91,6.09,1.61,12.21,2.13,18.35.42,5-1.67,7-6.75,7q-23.89,0-47.77,0Z"/>
    <path id="buttonBlue" d="M394.08,238.5H347.23c-5.93,0-7.28,1.15-8.19,6.92-7.53,47.9-43.75,84-91.68,91.46-5.25.81-6.66,2.32-6.66,7.51q0,47.54.06,95.09c0,5.33,1.16,6.41,6.63,6a215.32,215.32,0,0,0,106.29-36.68,213.45,213.45,0,0,0,48.5-44.52c23.49-29.56,38.7-62.89,44.3-100.39.91-6.09,1.61-12.21,2.13-18.35.42-5-1.67-7-6.75-7q-23.89,0-47.77,0Z"/>
  </svg>

0

   <button id="startButton" type="button">Start New Game</button>

Body:
currentIndex isn't being set to 0 properly after playBackSequence()

Change the function to use a temporary variable:

function playBackSequence() {
    tmpCurrentIndex = currentIndex;
    setInterval(function(){
        if (sequence[tmpCurrentIndex] == "green") {
            buttonGreen.style.opacity = "0.4";
            greenSound.play();
        }else if(sequence[tmpCurrentIndex] == "red"){
            buttonRed.style.opacity = "0.4";
            redSound.play();
        }else if(sequence[tmpCurrentIndex] == "yellow"){
            buttonYellow.style.opacity = "0.4";
            yellowSound.play();
        }else if(sequence[tmpCurrentIndex] == "blue"){
            buttonBlue.style.opacity = "0.4";
            blueSound.play();
        }
        tmpCurrentIndex++;
        setTimeout(function(){
            buttonGreen.style.opacity = "1";
            buttonRed.style.opacity = "1";
            buttonYellow.style.opacity = "1";
            buttonBlue.style.opacity = "1";
        }, 500);
    }, 1000);
    currentIndex = 0;
}


问:
Calculating Cosine Integral and Ci(x)
I have a basic background in Java, so my knowledge of different structures and implementations is limited.

I was wondering how to calculate the Cosine-Integral in Java.

Specifically, I have f(x) = sin(2pi C*x)/x^2

The integral of this = Constant * Ci(2pi Constant * x) - sin(2pi Constant * x)/x

I want to calculate the integral of sin(2pi C * x) / x^2 from 0 to 0.5x (or sin(0) to sin(pi) in the original f(x).  Unfortunately, I don't know how to evaluate the Ci(x) part of the function at my current skill level.

I downloaded the Apache Math3 *.jar and imported it in to my BuildPath, then imported the .analysis.Integration., but have no idea how to:

Define a function as input to integrate

Actually integrate

I could do with a simple example of evaluating the Cosine-Integral, but I would prefer to learn how to do integrals more generally.

答:
Abramowitz and Stegun show you how to do it.  So does Numerical Recipes.  The NR code is licensed, so be careful about using it without paying up.

The series expansion for Ci(x) appears on this page of A&S.

It should be easy enough to program if you can't find it in existing Java math libraries.

Title: Calculating Cosine Integral and Ci(x)


问:
SSRS with Stored Procedure containing multiple count statements
I have few lines query which has multiple count statements. I have created Stored procedure for the select count statements and it is giving results when i run it on SSMS but when i use the stored procedure in SSRS it is giving only 1st query output. How do I get other queries output too while using ssrs?

Code from Comments:

```<code>select count(*) as Field1
from #TempTable1;

select count(*) as Field2
from #TempTable2;

select count(distinct ANo) as F3
from #TempTable1;

select count(distinct BNo) as F4
from #TempTable2;

select count(*) as F5
from Table1
where InsertDate >= StartDate
      and InsertDate <= EndDate
      and value1 >= 2
      and TestField = 0;

select count(*) as F6
from Table1
where InsertDate >= StartDate
      and InsertDate <= EndDate
      and value1 >= 2
      and TestField = 1;

select count(*) as F7
from Table1
where InsertDate >= StartDate
      and InsertDate <= EndDate
      and value1 >= 2
      and TestField = 0;
</code>```

答:
Finally Found the answer

Here is what I've done
Declared local variables and used them as below in query

select @A= count() from Table1
Select @B= count() from Table 2

Select @A as Field1,@B as Field2

This gives the output in single row.

Body:
I have few lines query which has multiple count statements. I have created Stored procedure for the select count statements and it is giving results when i run it on SSMS but when i use the stored procedure in SSRS it is giving only 1st query output. How do I get other queries output too while using ssrs?

Code from Comments:

select count(*) as Field1
from #TempTable1;

select count(*) as Field2
from #TempTable2;

select count(distinct ANo) as F3
from #TempTable1;

select count(distinct BNo) as F4
from #TempTable2;

select count(*) as F5
from Table1
where InsertDate >= StartDate
      and InsertDate <= EndDate
      and value1 >= 2
      and TestField = 0;

select count(*) as F6
from Table1
where InsertDate >= StartDate
      and InsertDate <= EndDate
      and value1 >= 2
      and TestField = 1;

select count(*) as F7
from Table1
where InsertDate >= StartDate
      and InsertDate <= EndDate
      and value1 >= 2
      and TestField = 0;


问:
Why can't I call a class's start function from within itself?
I'm totally new to programming with threads, and since the class is using QThreads, I'm wondering why I cannot call a QThread's start function from within itself and have its run function start executing independently of another thread (the program seems to crash when I do this). Instead, I have to call the start function from wherever the object was declared. Why is this?

Some code:

```<code>class ClassWithThread : public QThread
{
public:
    ClassWithThread() {}
    someFunction() {start();}
    run()
    {
        //do some stuff here
    }
}
</code>```

That is basically what my class does. When I call someFunction the program crashes. If I remove the start statement from someFunction though, and call start from outside the program, then it works fine.

答:
QThread should be derived only if you want to extend thread capability, not to specialize it for your job like this. This article would help you to understand the use of QThread.

So you must create a QThread and start it from outside and then move an object to it that will do the job. Read this example: http://labs.qt.nokia.com/2006/12/04/threading-without-the-headache/

Hope that helps to avoid this kind of problem

Body:
I'm totally new to programming with threads, and since the class is using QThreads, I'm wondering why I cannot call a QThread's start function from within itself and have its run function start executing independently of another thread (the program seems to crash when I do this). Instead, I have to call the start function from wherever the object was declared. Why is this?

Some code:

class ClassWithThread : public QThread
{
public:
    ClassWithThread() {}
    someFunction() {start();}
    run()
    {
        //do some stuff here
    }
}

That is basically what my class does. When I call someFunction the program crashes. If I remove the start statement from someFunction though, and call start from outside the program, then it works fine.


问:
Can weak symbol be resolved among libraries during linking?
My scenario is about cross-compiling to a Arduino Due (ARM target), but I guess it's a generic C weak symbol problem.

I want to break my firmware into 3 parts:
 1. The hardware library (CMSIS, Middleware) -> libHardware.a
 2. Realtime OS library -> libOS.a
 3. Application code -> Output.elf linked to above.

the referenced CMSIS implementation has declared the followings:

```<code>void SysTick_Handler    ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
// ...and a few dozen IRQ handler hook skipped for brevity
</code>```

The idea of the CMSIS design is to have the Application Code implementing and handling some of IRQ selectively.

nm reports for libHardware.a

```<code>startup_sam3xa.o:
00000000 W SysTick_Handler
...
</code>```

And in my scenario, I would like to implement theses IRQ handlers in the libOS.a.

I implement void SysTick_Handler(void), nm reports:

```<code>cortex_handlers.o:
00000000 T SysTick_Handler
....
</code>```

Then I link them together, which basically boils down to

```<code>g++ -o app.elf -Wl,--start-group app.o libHardware.a libOS.a -Wl,--end-group
</code>```

(Grouping is necessary because OS depends on the low level Hardware function. And Hardware need to calls the IRQ/main() function provdided by the OS)

nm reports:

```<code>...
00080124 W SysTick_Handler
...
</code>```

It's still weak! I expect it to be using the strong symbol defined in the libOS.a.
At the end, SysTick isn't handled, which of course leads to catastrophic failure.

On the other hand, if I don't declare them as weak in libHardware/startup_sam3xa.c, everything works fine.
If I choose to implement SysTick_Handler in the app/app.c, it's strongly linked too.

So my question is: how could libOS.a implements the weak handler defined in libHardware.a?
Or what would be the best practice in these firmware development scenarios?

答: Another solution is to keep the source for your handler (or whatever) separate, but #include it into a source file that must always be referenced when using the library (if your library has such a thing and is not all optional.)  Using different words than another answer, the linker when examining a library .a works in units of object files .o : if an object file has any symbol that resolves an unresolved symbol when the linker is making a pass over the .o units in the archive (and the linker can make many passes), the linker puts all the symbols from the object file into the linked binary, resolving unresolved symbols and overriding weak definitions.  Order of libraries in the link command is important and you may need a library to appear twice in the link command. The linker flag whole-archive also can solve the problem.  My answer is succinct, but could be wrong.</p>

Body:
My scenario is about cross-compiling to a Arduino Due (ARM target), but I guess it's a generic C weak symbol problem.

I want to break my firmware into 3 parts:
 1. The hardware library (CMSIS, Middleware) -> libHardware.a
 2. Realtime OS library -> libOS.a
 3. Application code -> Output.elf linked to above.

the referenced CMSIS implementation has declared the followings:

void SysTick_Handler    ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
// ...and a few dozen IRQ handler hook skipped for brevity

The idea of the CMSIS design is to have the Application Code implementing and handling some of IRQ selectively.

nm reports for libHardware.a

startup_sam3xa.o:
00000000 W SysTick_Handler
...

And in my scenario, I would like to implement theses IRQ handlers in the libOS.a.

I implement void SysTick_Handler(void), nm reports:

cortex_handlers.o:
00000000 T SysTick_Handler
....

Then I link them together, which basically boils down to

g++ -o app.elf -Wl,--start-group app.o libHardware.a libOS.a -Wl,--end-group

(Grouping is necessary because OS depends on the low level Hardware function. And Hardware need to calls the IRQ/main() function provdided by the OS)

nm reports:

...
00080124 W SysTick_Handler
...

It's still weak! I expect it to be using the strong symbol defined in the libOS.a.
At the end, SysTick isn't handled, which of course leads to catastrophic failure.

On the other hand, if I don't declare them as weak in libHardware/startup_sam3xa.c, everything works fine.
If I choose to implement SysTick_Handler in the app/app.c, it's strongly linked too.

So my question is: how could libOS.a implements the weak handler defined in libHardware.a?
Or what would be the best practice in these firmware development scenarios?


问:
How to download and save excel file using UFT?
I need to download and save excel to a specific location using UFT.

Step 1: Click on hyperlink as seen below

Step 2: Save the downloaded excel as shown below.

Can you please advice on how to automate this scenario using uft?

答:
As far as I know UFT's web support can't handle such cases. This may be a case where UFT's image-based automation (aka Insight) can be used.

You can use Insight to identify the required buttons if UFT doesn't recognise them as native WinButtons.


问:
Why do we use volatile keyword?

Possible Duplicate:

Why does volatile exist?

I have never used it but I wonder why people use it? What does it exactly do? I searched the forum, I found it only C# or Java topics.

答:
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own."   (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

ContentLicense: CC BY-SA 4.0

Title: Why do we use volatile keyword?


问:
Getting TokenMismatchException in VerifyCsrfToken.php line 53 in Laravel 5.1 while using csrf token
I am getting TokenMismatchException in VerifyCsrfToken.php line 53:
I am using {!!Form::open()!!}
{!!Form::close!!}. When I click the add Button in my form with empty field for the first time, it shows me error as I set the validation rule. But when I click the Add button again without refreshing the page, it shows me the TokenMismatchException error. I have checked with dd() and it shows me the token like this:

```<code> array:3 [▼
 "_token" => "5dXwRHbz4GNY1tx9OVeWPcOkirVIm0YtpkZufFbr"
 "menu_name" => ""
 "menu_price" => ""
</code>```

Here is my form code:

```<code>{!! Form::open(array('route' =>'upcoming.store', 'method'=>'POST')) !!}
                    <div class="col-lg-6 col-sm-offset-3 top-spacing">
                        <input type="text" name="menu_name" placeholder="Menu Name.." class="form-control">
                    </div>
                    <div class="col-lg-6 col-sm-offset-3 top-spacing">
                        <input type="text" name="menu_price" placeholder="Menu Price.." class="form-control">
                    </div>

                    <div class="col-sm-2 col-sm-offset-8 top-spacing">
                        <button class="btn btn-success">
                            Add +
                        </button>
                    </div>

                </div>
                {!! Form::close() !!}
</code>```

Here is my controller store function:

```<code>public function store(Request $request)
{
    dd($request->all());
    $this->validate($request, array(
        'menu_name'=>'required',
        'menu_price'=>'required',
        ));
    $upcoming = new Upcomingfood;
    $upcoming->menu_name=$request->menu_name;
    $upcoming->menu_price=$request->menu_price;
    $upcoming->save();
    Session::flash('success','Food Menu Added Successfullly');
    return redirect()->back();
}
</code>```

Can anyone help?

答:
Try add ``` {{ csrf_field() }} ``` inside the form.

I really recommend that you read official documentation https://laravel.com/docs/5.4/csrf

Body:
I am getting TokenMismatchException in VerifyCsrfToken.php line 53:
I am using {!!Form::open()!!}
{!!Form::close!!}. When I click the add Button in my form with empty field for the first time, it shows me error as I set the validation rule. But when I click the Add button again without refreshing the page, it shows me the TokenMismatchException error. I have checked with dd() and it shows me the token like this:

 array:3 [▼
 "_token" => "5dXwRHbz4GNY1tx9OVeWPcOkirVIm0YtpkZufFbr"
 "menu_name" => ""
 "menu_price" => ""

Here is my form code:

{!! Form::open(array('route' =>'upcoming.store', 'method'=>'POST')) !!}

                        <input type="text" name="menu_name" placeholder="Menu Name.." class="form-control">

                        <input type="text" name="menu_price" placeholder="Menu Price.." class="form-control">

                        <button class="btn btn-success">
                            Add +
                        </button>

                {!! Form::close() !!}

Here is my controller store function:

public function store(Request $request)
{
    dd($request->all());
    $this->validate($request, array(
        'menu_name'=>'required',
        'menu_price'=>'required',
        ));
    $upcoming = new Upcomingfood;
    $upcoming->menu_name=$request->menu_name;
    $upcoming->menu_price=$request->menu_price;
    $upcoming->save();
    Session::flash('success','Food Menu Added Successfullly');
    return redirect()->back();
}

Can anyone help?

Body:
Try add
 {{ csrf_field() }}
 inside the form.

I really recommend that you read official documentation https://laravel.com/docs/5.4/csrf


问:
displaying images Gallery from assets/images
i would like to Display an image gallery but from "assets/images" folder not from the phone storage.

like this one:

答:
The question is not clear, if you want to load a single image from assets,
then you can do it this way. </p>

```<code>//read image from asset
InputStream is = getAssets().open("image.jpg");

//    create a drawable
Drawable drawable = Drawable.createFromStream(is, null);

//find reference to your imageview and set drawable
ImageView i=(ImageView)findViewById(R.id.image_id);
i.setImageDrawable(drawable);
</code>```

Body:
The question is not clear, if you want to load a single image from assets,
then you can do it this way.

//read image from asset
InputStream is = getAssets().open("image.jpg");

//    create a drawable
Drawable drawable = Drawable.createFromStream(is, null);

//find reference to your imageview and set drawable
ImageView i=(ImageView)findViewById(R.id.image_id);
i.setImageDrawable(drawable);


问:
Code to reverse linked list
i have made code for reversing the linked list.
if i run this code given linked list is printed but not reversed one.

I think there is some mistake in reverse function.

can someone pls.. tell me the mistake in my code.
i have done it using three pointers

```<code>#include<stdio.h>
#include<stdlib.h>

struct node {
    int data;
    struct node* next;
};

void reverse(struct node** headr) {
    struct node* current=*headr;
    struct node*temp=*headr;
    struct node* prev;
    struct node* next;

    while (current!=NULL) {
        prev=current;
        current=current->next;
        next=current;
        next->next=prev;
    }

    temp->next=NULL;
    *headr=current;
}

void push(struct node** headr, int new_data) {
    struct node* new_node = (struct node*) malloc(sizeof(struct node));

    new_node->data  = new_data;
    new_node->next = (*headr);
    (*headr)    = new_node;
}

void print(struct node *head) {
    struct node *temp = head;
    while (temp != NULL) {
        printf("%d  ", temp->data);
        temp = temp->next;
    }
}

int main() {
    struct node* head = NULL;

     push(&head, 20);
     push(&head, 4);
     push(&head, 15);
     push(&head, 85);

     printf("Given linked list\n");
     print(head);
     reverse(&head);
     printf("\nReversed Linked list \n");
     print(head);
     getchar();
}
</code>```

答:
This may help you:

```<code>void reverse(struct node** headr)
{
    struct node* current=*headr;
    struct node* prev = NULL;
    struct node* next;
    while(current!=NULL)
    {
        next=current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    *headr=prev;
}
</code>```

Your Main:

```<code>int main()
{

    struct node* head = NULL;

    push(&head, 20);
    push(&head, 4);
    push(&head, 15);
    push(&head, 85);

    printf("Befor:\n");
    print(head);

    reverse(&head);

    printf("\nAfter:\n");
    print(head);

    getchar();
}
</code>```

Output:

```<code>Befor:
85  15  4  20
After:
20  4  15  85
</code>```

Title: Code to reverse linked list

Body:
i have made code for reversing the linked list.
if i run this code given linked list is printed but not reversed one.

I think there is some mistake in reverse function.

can someone pls.. tell me the mistake in my code.
i have done it using three pointers

#include<stdio.h>
#include<stdlib.h>

struct node {
    int data;
    struct node* next;
};

void reverse(struct node** headr) {
    struct node* current=*headr;
    struct node*temp=*headr;
    struct node* prev;
    struct node* next;

    while (current!=NULL) {
        prev=current;
        current=current->next;
        next=current;
        next->next=prev;
    }

    temp->next=NULL;
    *headr=current;
}

void push(struct node** headr, int new_data) {
    struct node* new_node = (struct node*) malloc(sizeof(struct node));

    new_node->data  = new_data;
    new_node->next = (*headr);
    (*headr)    = new_node;
}

void print(struct node *head) {
    struct node *temp = head;
    while (temp != NULL) {
        printf("%d  ", temp->data);
        temp = temp->next;
    }
}

int main() {
    struct node* head = NULL;

     push(&head, 20);
     push(&head, 4);
     push(&head, 15);
     push(&head, 85);

     printf("Given linked list\n");
     print(head);
     reverse(&head);
     printf("\nReversed Linked list \n");
     print(head);
     getchar();
}

Body:
This may help you:

void reverse(struct node** headr)
{
    struct node* current=*headr;
    struct node* prev = NULL;
    struct node* next;
    while(current!=NULL)
    {
        next=current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    *headr=prev;
}

Your Main:

int main()
{

    struct node* head = NULL;

    push(&head, 20);
    push(&head, 4);
    push(&head, 15);
    push(&head, 85);

    printf("Befor:\n");
    print(head);

    reverse(&head);

    printf("\nAfter:\n");
    print(head);

    getchar();
}

Output:

Befor:
85  15  4  20
After:
20  4  15  85


问:
How to remove consecutive rows with duplicate data in certain fields (in SQLite)?
Let's say for example you have a table like this:

```<code>-------------------------------
Date        Name          Type
2017-01-01  John          1
2017-01-02  John          1
2017-01-03  Mike          2
2017-01-04  John          1
-------------------------------
</code>```

I want to be able to group by the type to get a result like the following

```<code>-------------------------
Name          Type
John          1
Mike          2
John          1
-------------------------
</code>```

As you can see the first two rows was grouped because there is no different type in between them, like the thing you see in mobile phones call logs.

How can I achieve that in SQLite?

答:
The following query achieves this by a NOT EXISTS for the same Name and Type values on the previous row (if any). The previous row is found by looking for the maximum date that is strictly less than the date of the current row.

```<code>SELECT *
FROM tbl t1
WHERE NOT EXISTS (
  SELECT *
  FROM tbl t2
  WHERE t2.Name = t1.Name
  AND t2.Type = t1.Type
  AND t2.`Date` = (SELECT MAX(`Date`)
                   FROM tbl t3
                   WHERE t3.`Date` < t1.`Date`)
);
</code>```

SQL Fiddle demo: http://sqlfiddle.com/#!5/0700cb/3

Body:
Let's say for example you have a table like this:

-------------------------------
Date        Name          Type
2017-01-01  John          1
2017-01-02  John          1
2017-01-03  Mike          2
2017-01-04  John          1
-------------------------------

I want to be able to group by the type to get a result like the following

-------------------------
Name          Type
John          1
Mike          2
John          1
-------------------------

As you can see the first two rows was grouped because there is no different type in between them, like the thing you see in mobile phones call logs.

How can I achieve that in SQLite?

Body:
The following query achieves this by a NOT EXISTS for the same Name and Type values on the previous row (if any). The previous row is found by looking for the maximum date that is strictly less than the date of the current row.

SELECT *
FROM tbl t1
WHERE NOT EXISTS (
  SELECT *
  FROM tbl t2
  WHERE t2.Name = t1.Name
  AND t2.Type = t1.Type
  AND t2.`Date` = (SELECT MAX(`Date`)
                   FROM tbl t3
                   WHERE t3.`Date` < t1.`Date`)
);

SQL Fiddle demo: http://sqlfiddle.com/#!5/0700cb/3


问:
Does Cython support the ternary style if statement (if ? then : else)?
I forget the technical term for the (if ? then : else) format in C/C++. Also, is this syntax supported in the Cython (a C variant of Python)?

I need to know the technical name so I can lookup if Cython supports this feature.

UPDATE: Does anyone know if Cython supports this?

Solution: In cython/python this is written as (b if a else c) compare to (a ? b : c)

答: It's often called the ternary operator, or inline if.</p>


问:
Getter and Setter Aliasing in C#
How would I go about aliasing a variable from it's plural form so that referencing the plural form changes or returns the single form?

I have a global variable as such with a Getter and Setter:

```<code>public string UserName { get; set; }
</code>```

And would like to set up an aliased variable UserNames that would return UserName and when set would modify UserName?

I've tried public string UserNames { get => UserName; set => UserName = UserNames } but that didn't seem to work.

答:
You can write like this:</p>

```<code>private string UserName;
public string UserNames
{
  get
  {
    return UserName;
  }
  set
  {
    UserName=value;
  }
 }
</code>```

Title: Getter and Setter Aliasing in C#

Body:
How would I go about aliasing a variable from it's plural form so that referencing the plural form changes or returns the single form?

I have a global variable as such with a Getter and Setter:

public string UserName { get; set; }

And would like to set up an aliased variable UserNames that would return UserName and when set would modify UserName?

I've tried public string UserNames { get => UserName; set => UserName = UserNames } but that didn't seem to work.

Body:
You can write like this:

private string UserName;
public string UserNames
{
  get
  {
    return UserName;
  }
  set
  {
    UserName=value;
  }
 }