问:
Unable to set content type of http header in REST

The below requests always takes the default Content Type irrespective of what I am setting. I set to application/xml, but still it goes as application/json. This problem however is not there when I invoke the service via Postman.

```<code>Set objHTTPRequest=##class(%Net.HttpRequest).%New()
Set objHTTPResponse=##class(%Net.HttpResponse).%New()
Do objHTTPRequest.SetHeader("Authorization", "username:password")
Do objHTTPRequest.SetHeader("Content-Type", "application/xml")
Do objHTTPRequest.Send("GET","url")
Set Op=objHTTPRequest.HttpResponse.Data.Read()
</code>```

zw objHTTPRequest -> No Content-Type Set

答:
How did you check that default Content-Type?

Maybe you missed something about how HTTP really works?

When you send some data with POST or PUT request, you can set Content-Type for this data. If you want to retrieve some data from the server in the format which you want, you can set header Accept, but when you set this header, it does not mean, that you really get this data in the asked format, it only depends on the realization of this particular server. To some examples.

```<code>set ht=##class(%Net.HttpRequest).%New()
set ht.Server="example.org"
set ht.Port=80
set ht.Username="username"
set ht.Password="password"
#; we a going to send some xml
do ht.ContentBody.Write("<root></root>")
#; for this data we can set ContentType
set ht.ContentType="application/xml"
#; then we POST this data, where 1 it is just test flag, for debug
set sc=ht.Post("/somepath", 1)

#; As a result you can see that Content-Type has our value
POST /somepath HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; Cache;)
Host: example.org
Accept-Encoding: gzip
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Length: 13
Content-Type: application/xml

<root></root>
</code>```

Body:
The below requests always takes the default Content Type irrespective of what I am setting. I set to application/xml, but still it goes as application/json. This problem however is not there when I invoke the service via Postman.

Set objHTTPRequest=##class(%Net.HttpRequest).%New()
Set objHTTPResponse=##class(%Net.HttpResponse).%New()
Do objHTTPRequest.SetHeader("Authorization", "username:password")
Do objHTTPRequest.SetHeader("Content-Type", "application/xml")
Do objHTTPRequest.Send("GET","url")
Set Op=objHTTPRequest.HttpResponse.Data.Read()

zw objHTTPRequest -> No Content-Type Set

Body:
How did you check that default Content-Type?

Maybe you missed something about how HTTP really works?

When you send some data with POST or PUT request, you can set Content-Type for this data. If you want to retrieve some data from the server in the format which you want, you can set header Accept, but when you set this header, it does not mean, that you really get this data in the asked format, it only depends on the realization of this particular server. To some examples.

set ht=##class(%Net.HttpRequest).%New()
set ht.Server="example.org"
set ht.Port=80
set ht.Username="username"
set ht.Password="password"
#; we a going to send some xml
do ht.ContentBody.Write("<root></root>")
#; for this data we can set ContentType
set ht.ContentType="application/xml"
#; then we POST this data, where 1 it is just test flag, for debug
set sc=ht.Post("/somepath", 1)

#; As a result you can see that Content-Type has our value
POST /somepath HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; Cache;)
Host: example.org
Accept-Encoding: gzip
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Length: 13
Content-Type: application/xml

<root></root>


来源: stackexchange

问:
Loops for assigning/calculating student grade (c++)
I'm sort of having a hard time with my program, and I would really appreciate any help. Forgive me for my really bad code, I'm new.

```<code>#include <iostream>
#include <string.h>

using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double avg, double sum);
char calculateGrade(double score, char grade);
void displayResults(string firstname, string lastname, double avg, char
grade);

int main(){
//variables
string firstname;
string lastname;
int score;
double sum;
double avg;
char grade;
//functions and parameters
firstname = getFirstName();
lastname = getLastName();
score = getScores();
sum = calculateSum(sum, score);
avg = calculateAvg(avg, sum);
grade = calculateGrade(score, grade);
displayResults(firstname,lastname,avg,grade);

while (true)
{
firstname = getFirstName();
cin >> firstname;
if (firstname == "done")break;
lastname = getLastName();
cin >> lastname;
sum=0.0;

  for (int i = 0; i<10; i++)
    {
        double score;
     cin >> score;
     sum - calculateSum(sum, score);
      sum+=score;
      //sum = sum+score;
    }
     avg = calculateAvg(avg, sum);
  avg = sum/10.0;
    displayResults(firstname,lastname,avg,grade);
 }
return 0;
}

string getFirstName()
{
string firstname;
cout<<"Enter first name: " << endl;
cin >>firstname;
return firstname;
}

string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}

int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}

double calculateSum(double sum, double score)
{
sum+=score;
return sum;
}

double calculateAvg(double avg, double sum)
{
avg = sum/10.0;
return avg;
}

char calculateGrade(double score, char grade)
{

if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}

void displayResults(string firstname, string lastname, double avg, char
grade)
{
cout<<firstname<< lastname<<": "<<avg << grade;
}
</code>```

I don't really understand loops, or how they work, so what I have written down for my loop was just given to us by our professor, so if anyone could please explain/dissect it then I would really appreciate it! I want to know how to do this, not just have answers handed to me.

So, I'm not sure why my program won't properly execute. I've listed the call functions and all of the functions seem to be correct. My loops are inside of the main as well, but I don't know why they're not working. Also, when I run it, I don't have any errors.

It seems to be stuck on the enter first name and enter last name part, but I'm not sure why.Again, I'd really appreciate any help, thank you!

答:
You code was full of bugs, but I will lead you through it step by step.

First things first, we will need to check what each function does :

1- string getFirstName(); Prompt the user to enter his/her first name. Working

2- string getLastName(); Prompt the user to enter his/her last name. Working

3- int getScores(); Prompt the user to enter his/her score. Working

4- double calculateSum(double sum, double score); Adds both the sum and the score. What you did in your implementation of the function :

```<code>{
sum+=score;
return sum;
}
</code>```

Will only be valid if you pass variable sum by reference. There is no need to get into this now. An easier way to do it is to do so :

```<code>{
double add = sum + score;
return add;
}
</code>```

Next up :

5- double calculateAvg(double avg, double sum); Divides sum by 10 to get the average, there's no need to pass avg as a parameter as that's what we are going to return.

The function should be written as double calculateAvg(double sum);

6- Same goes char calculateGrade(double score, char grade);. There's no need to pass grade. It will be written aschar calculateGrade(double score);.

7- Last one : void displayResults(string firstname, string lastname, double avg, char grade); Working

Ok, now to the main() function :
You'll need to declare all of your variables like so

```<code>string firstname;
string lastname;
double score;
double sum ;
double avg ;
char grade;
</code>```

No need to use our functions here, we are going to use them inside our while loop.

Into the while loop :

There's no need to use cin>> with any of variables cause that's what our functions is doing for us.

When the user enters done as his/her first name exit the loop.

Else, create a for loop that iterates 10 times asking the user to input his/her score, add this score to the sum and then after the for loop ends calculate both the average and the grade and print them out.

The final working version of your code should look like this, if you still have any further questions don't hesitate to ask.

```<code>#include <iostream>
#include <string.h>

using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double sum);
char calculateGrade(double score);
void displayResults(string firstname, string lastname, double avg, char grade);

int main(){
//variables
string firstname;
string lastname;
double score;
double sum ;
double avg ;
char grade;

while (true)
{
    firstname = getFirstName();
    if (firstname == "done")
        break;
    lastname = getLastName();
    sum=0.0;
        for (int i = 0; i<10; i++)
        {
         score = getScores();
         sum = calculateSum(sum, score); //sum = sum+score;
        }
         avg = calculateAvg(sum);
        grade = calculateGrade(avg);
        displayResults(firstname,lastname,avg,grade);
     }
    return 0;
}

string getFirstName()
{
string firstname;
cout<<"Enter first name: ";
cin >>firstname;
return firstname;
}

string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}

int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}

double calculateSum(double sum, double score)
{
int add = sum + score;
return add;
}

double calculateAvg(double sum)
{
double avg = sum/10.0;
return avg;
}

char calculateGrade(double score)
{
char grade;
if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}

void displayResults(string firstname, string lastname, double avg, char grade)
{
cout<<firstname<< lastname<<" - Average : "<<avg << " - Grade : "<< grade<<endl;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm sort of having a hard time with my program, and I would really appreciate any help. Forgive me for my really bad code, I'm new.

#include <iostream>
#include <string.h>

using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double avg, double sum);
char calculateGrade(double score, char grade);
void displayResults(string firstname, string lastname, double avg, char
grade);

int main(){
//variables
string firstname;
string lastname;
int score;
double sum;
double avg;
char grade;
//functions and parameters
firstname = getFirstName();
lastname = getLastName();
score = getScores();
sum = calculateSum(sum, score);
avg = calculateAvg(avg, sum);
grade = calculateGrade(score, grade);
displayResults(firstname,lastname,avg,grade);

while (true)
{
firstname = getFirstName();
cin >> firstname;
if (firstname == "done")break;
lastname = getLastName();
cin >> lastname;
sum=0.0;

  for (int i = 0; i<10; i++)
    {
        double score;
     cin >> score;
     sum - calculateSum(sum, score);
      sum+=score;
      //sum = sum+score;
    }
     avg = calculateAvg(avg, sum);
  avg = sum/10.0;
    displayResults(firstname,lastname,avg,grade);
 }
return 0;
}

string getFirstName()
{
string firstname;
cout<<"Enter first name: " << endl;
cin >>firstname;
return firstname;
}

string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}

int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}

double calculateSum(double sum, double score)
{
sum+=score;
return sum;
}

double calculateAvg(double avg, double sum)
{
avg = sum/10.0;
return avg;
}

char calculateGrade(double score, char grade)
{

if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}

void displayResults(string firstname, string lastname, double avg, char
grade)
{
cout<<firstname<< lastname<<": "<<avg << grade;
}

I don't really understand loops, or how they work, so what I have written down for my loop was just given to us by our professor, so if anyone could please explain/dissect it then I would really appreciate it! I want to know how to do this, not just have answers handed to me.

So, I'm not sure why my program won't properly execute. I've listed the call functions and all of the functions seem to be correct. My loops are inside of the main as well, but I don't know why they're not working. Also, when I run it, I don't have any errors.

It seems to be stuck on the enter first name and enter last name part, but I'm not sure why.Again, I'd really appreciate any help, thank you!

Body:
You code was full of bugs, but I will lead you through it step by step.

First things first, we will need to check what each function does :

1- string getFirstName(); Prompt the user to enter his/her first name. Working

2- string getLastName(); Prompt the user to enter his/her last name. Working

3- int getScores(); Prompt the user to enter his/her score. Working

4- double calculateSum(double sum, double score); Adds both the sum and the score. What you did in your implementation of the function :

{
sum+=score;
return sum;
}

Will only be valid if you pass variable sum by reference. There is no need to get into this now. An easier way to do it is to do so :

{
double add = sum + score;
return add;
}

Next up :

5- double calculateAvg(double avg, double sum); Divides sum by 10 to get the average, there's no need to pass avg as a parameter as that's what we are going to return.

The function should be written as double calculateAvg(double sum);

6- Same goes char calculateGrade(double score, char grade);. There's no need to pass grade. It will be written aschar calculateGrade(double score);.

7- Last one : void displayResults(string firstname, string lastname, double avg, char grade); Working

Ok, now to the main() function :
You'll need to declare all of your variables like so

string firstname;
string lastname;
double score;
double sum ;
double avg ;
char grade;

No need to use our functions here, we are going to use them inside our while loop.

Into the while loop :

There's no need to use cin>> with any of variables cause that's what our functions is doing for us.

When the user enters done as his/her first name exit the loop.

Else, create a for loop that iterates 10 times asking the user to input his/her score, add this score to the sum and then after the for loop ends calculate both the average and the grade and print them out.

The final working version of your code should look like this, if you still have any further questions don't hesitate to ask.

#include <iostream>
#include <string.h>

using namespace std;
//functions
string getFirstName();
string getLastName();
int getScores();
double calculateSum(double sum, double score);
double calculateAvg(double sum);
char calculateGrade(double score);
void displayResults(string firstname, string lastname, double avg, char grade);

int main(){
//variables
string firstname;
string lastname;
double score;
double sum ;
double avg ;
char grade;

while (true)
{
    firstname = getFirstName();
    if (firstname == "done")
        break;
    lastname = getLastName();
    sum=0.0;
        for (int i = 0; i<10; i++)
        {
         score = getScores();
         sum = calculateSum(sum, score); //sum = sum+score;
        }
         avg = calculateAvg(sum);
        grade = calculateGrade(avg);
        displayResults(firstname,lastname,avg,grade);
     }
    return 0;
}

string getFirstName()
{
string firstname;
cout<<"Enter first name: ";
cin >>firstname;
return firstname;
}

string getLastName()
{
string lastname;
cout<<"Enter last name: ";
cin >>lastname;
return lastname;
}

int getScores()
{
int score;
cout <<"Input score: ";
cin >>score;
return score;
}

double calculateSum(double sum, double score)
{
int add = sum + score;
return add;
}

double calculateAvg(double sum)
{
double avg = sum/10.0;
return avg;
}

char calculateGrade(double score)
{
char grade;
if (score >= 90)
grade = 'A';
else if (score >=80)
grade = 'B';
else if (score >=70)
grade = 'C';
else if (score >=60)
grade = 'D';
else
grade = 'F';
return grade;
}

void displayResults(string firstname, string lastname, double avg, char grade)
{
cout<<firstname<< lastname<<" - Average : "<<avg << " - Grade : "<< grade<<endl;
}


问:
need to sort .txt file into data frame with Pandas using Python 2.7
I'm new to using programming languages and I'm having trouble working this particular issue out. I'm a journalist trying to use Python to reorganize 911 data from a county dispatch office that has been provided in a .txt file.

This is how one call comes in the current format:

```<code>Incident Number: PD160010001
Incident Type: SUSPICIOUS PERSON(S)
EMS Blk: 186605  Fire Blk: 65005   Police Blk: 22145
Location: Location name,22
          at XXXX Name RD ,22
       Entered: 01/01/16  00:00
    Dispatched: 01/01/16  00:00
       Enroute: 01/01/16  00:00
      On Scene: 01/01/16  00:00
     Transport:   /  /      :
Trans Complete:   /  /      :
        Closed: 01/01/16  00:04

01/01/16  00:00  OUTSRV
01/01/16  00:00  DISPOS  22H4
01/01/16  00:00  PREMPT  22H4
01/01/16  00:00  DISPOS  2212
01/01/16  00:00  EXCH    22H4
01/01/16  00:01  ADDER   22H4
01/01/16  00:04  CLEAR   2212
01/01/16  00:04  CLEAR   22H4
01/01/16  00:04  CLOSE   22H4
</code>```

I was able to reorganize this in Excel using the Right and Left functions and a few other steps to get something like this:

```<code>Incident Number Incident Type         EMS Blk:    Closed
PD160010001     SUSPICIOUS PERSON(S)  186605  ... 01/01/16  00:04
</code>```

The 9-10 rows of data with dispatched times at the bottom of each incident is redundant is not necessary.

What I'm having trouble with is finding a way to tell Pandas to take the name to the left of the colon and recognize that as one column head, while taking the info to the right of the column and assign it to the corresponding column, then repeat until after the closed column and skip the redundant information.

One year's worth of data in the .txt file is approximately 6 million rows and is cut down to just over 501,000 once it's been reorganized. Doing it in excel by hand is going to take about 4 hours per file and I want to do an analysis of call times over 10 years.

I need to learn to do this in Python to make it a practical project to follow through with.
Thank everyone. First time posting a question here.

答:
Your description of the layout of the data is ambiguous, so I'm making some assumptions. I'm guessing the .txt file looks somewhat like this:

```<code>          header2  header3  header4  header5  header6  header7  header8  header9
index 1   data12   data13   data14   data15   data16   data17   data18   data19
index 2   data22   data23   data24   data25   data26   data27   data28   data29
</code>```

Where each index corresponds to a certain call and each column corresponds to some attribute of the call with the headers denoting what the data in the column represents.

The following program turns the above .txt file into a pandas dataframe and prints it out.

```<code>import pandas as pd
import re

with open(filename) as file:
    rows = file.readlines()
columns = rows[0] # get the top row
columns = re.sub(' {2,}', ',', columns) # substitute whitespaces of more than
                                     # two spaces with commas
columns = columns.strip().split(',') # turn the row into a list
content = rows[1:] # All but the first row
content = [re.sub(' {2,}',',',row).strip() for row in content] # again, whitespace to commas
content = [row.split(',') for row in content] # turn rows into lists
index = [row[0] for row in content] # take the first element of each row as the index
content = [row[1:] for row in content] # remove index from content
df = pd.DataFrame(data=content, index=index, columns=columns) # Combine into a dataframe
print(df)
</code>```

Here we've assumed the columns have at least two spaces between them and that your data won't have any double spaces in it. If there's more space than that between the columns, you can change the regex to look for 3 or more consecutive spaces.

The output is

```<code>        header2 header3 header4 header5 header6 header7 header8 header9
index 1  data12  data13  data14  data15  data16  data17  data18  data19
index 2  data22  data23  data24  data25  data26  data27  data28  data29
</code>```

but you could do much more than print it out now that it's a dataframe.

Body:
I'm new to using programming languages and I'm having trouble working this particular issue out. I'm a journalist trying to use Python to reorganize 911 data from a county dispatch office that has been provided in a .txt file.

This is how one call comes in the current format:

Incident Number: PD160010001
Incident Type: SUSPICIOUS PERSON(S)
EMS Blk: 186605  Fire Blk: 65005   Police Blk: 22145
Location: Location name,22
          at XXXX Name RD ,22
       Entered: 01/01/16  00:00
    Dispatched: 01/01/16  00:00
       Enroute: 01/01/16  00:00
      On Scene: 01/01/16  00:00
     Transport:   /  /      :
Trans Complete:   /  /      :
        Closed: 01/01/16  00:04

01/01/16  00:00  OUTSRV
01/01/16  00:00  DISPOS  22H4
01/01/16  00:00  PREMPT  22H4
01/01/16  00:00  DISPOS  2212
01/01/16  00:00  EXCH    22H4
01/01/16  00:01  ADDER   22H4
01/01/16  00:04  CLEAR   2212
01/01/16  00:04  CLEAR   22H4
01/01/16  00:04  CLOSE   22H4

I was able to reorganize this in Excel using the Right and Left functions and a few other steps to get something like this:

Incident Number Incident Type         EMS Blk:    Closed
PD160010001     SUSPICIOUS PERSON(S)  186605  ... 01/01/16  00:04

The 9-10 rows of data with dispatched times at the bottom of each incident is redundant is not necessary.

What I'm having trouble with is finding a way to tell Pandas to take the name to the left of the colon and recognize that as one column head, while taking the info to the right of the column and assign it to the corresponding column, then repeat until after the closed column and skip the redundant information.

One year's worth of data in the .txt file is approximately 6 million rows and is cut down to just over 501,000 once it's been reorganized. Doing it in excel by hand is going to take about 4 hours per file and I want to do an analysis of call times over 10 years.

I need to learn to do this in Python to make it a practical project to follow through with.
Thank everyone. First time posting a question here.

Body:
Your description of the layout of the data is ambiguous, so I'm making some assumptions. I'm guessing the .txt file looks somewhat like this:

          header2  header3  header4  header5  header6  header7  header8  header9
index 1   data12   data13   data14   data15   data16   data17   data18   data19
index 2   data22   data23   data24   data25   data26   data27   data28   data29

Where each index corresponds to a certain call and each column corresponds to some attribute of the call with the headers denoting what the data in the column represents.

The following program turns the above .txt file into a pandas dataframe and prints it out.

import pandas as pd
import re

with open(filename) as file:
    rows = file.readlines()
columns = rows[0] # get the top row
columns = re.sub(' {2,}', ',', columns) # substitute whitespaces of more than
                                     # two spaces with commas
columns = columns.strip().split(',') # turn the row into a list
content = rows[1:] # All but the first row
content = [re.sub(' {2,}',',',row).strip() for row in content] # again, whitespace to commas
content = [row.split(',') for row in content] # turn rows into lists
index = [row[0] for row in content] # take the first element of each row as the index
content = [row[1:] for row in content] # remove index from content
df = pd.DataFrame(data=content, index=index, columns=columns) # Combine into a dataframe
print(df)

Here we've assumed the columns have at least two spaces between them and that your data won't have any double spaces in it. If there's more space than that between the columns, you can change the regex to look for 3 or more consecutive spaces.

The output is

        header2 header3 header4 header5 header6 header7 header8 header9
index 1  data12  data13  data14  data15  data16  data17  data18  data19
index 2  data22  data23  data24  data25  data26  data27  data28  data29

but you could do much more than print it out now that it's a dataframe.


问:
No connection string named 'MyEntities' could be found in the application config file
I am using entity framework and ASP.NET MVC 4 to build an application

My solution is split into two projects;

A class library that includes my data model (.edmx) file and a few custom interfaces

The 'container' MVC project that references the class library above

My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:

No connection string named 'MyEntities' could be found in the
  application config file.

I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.

Does anyone have any suggestions?

答:
I had this problem when running MSTest.  I could not get it to work without the "noisolation" flag.

Hopefully this helps someone.  Cost me a lot of time to figure that out.  Everything ran fine from the IDE.  Something weird about the Entity Framework in this context.


问:
How to join two tables in Django Admin system
I have two models connected to Django Admin system.
And would like to have a possibility such that by using the dropdown list, choose a specific value from the first model in a second model.

What do you think? Is this possible?

Thanks in advance

答: Adding a foreign key relationship will add this to the UI but make sure you haven’t included that field’s name in raw_id_fields </p>


问:
How to get id value from database using ajax? .net
I have a blog site and I made a comment panel under the article. example; user name, mail adress and comment...

I can add these fields using ajax but can't determine which article the comment is made on.
That's inputs..

```<code><div class="form-group">
                    <%-- <label for="name" class="col-sm-2 control-label" style="color: #fff;">Name</label>--%>
                    <div class="col-sm-8">
                        <input type="text" class="form-control" id="t1" name="name" placeholder="Adınız" required tabindex="1">
                    </div>
                </div>
                <div class="form-group">
                    <%-- <label for="email" class="col-sm-2 control-label" style="color: #fff;">E-mail</label>--%>
                    <div class="col-sm-8">
                        <input type="email" class="form-control" id="t2" name="email" placeholder="E-mail Adresiniz" required>
                    </div>
                </div>
                <div class="form-group">
                    <%--  <label for="name" class="col-sm-2 control-label" style="color: #fff;">Message</label>--%>
                    <div class="col-sm-10">
                        <textarea id="t3" name="message" class="form-control" placeholder="Yorumunuz" rows="5" required></textarea>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-6">
                        <button type="submit" style="float: right;" class="btn btn-primary" onclick="ekle()">Gönder</button>
                    </div>
</code>```

that's commentAjax.aspx code behind;

```<code>      sqlBaglantisi baglan = new sqlBaglantisi();
string adsoyad, email, yorum, makaleID;
protected void Page_Load(object sender, EventArgs e)
{
    makaleID = Request.QueryString["makaleID"];
    adsoyad = Request.QueryString["adsyd"].ToString();
    email = Request.QueryString["em"].ToString();
    yorum = Request.QueryString["yrm"].ToString();

    SqlCommand cmd = new SqlCommand("insert into Yorum (yorumAdSoyad, yorumEmail, yorumIcerik, yorumResim, makaleID) values('" + adsoyad.ToString() + "','" + email.ToString() + "','" + yorum.ToString() + "','/tema/yorumm.png')", baglan.baglan());
    cmd.ExecuteNonQuery();
}
</code>```

and js codes;

```<code>function ekle() {
var ad = document.getElementById("t1").value;
var mail = document.getElementById("t2").value;
var yorum = document.getElementById("t3").value;

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "yorumAjax.aspx?adsyd=" + ad + "&em=" + mail + "&yrm="+yorum, false);
xmlhttp.send(null);

document.getElementById("t1").value = "";
document.getElementById("t2").value = "";
document.getElementById("t3").value = "";

alert("Mesaj Gönderildi");
</code>```

I can't understand which comment has come to which article because I can't get the value of articleID.

答:
You can put a hidden input in your form, containing the actual ID of your article. Something like:

```<code><input type="hidden" id="articleID" name="articleID" value="<the id for this article>" />
</code>```

If you are using an MVC architecture, you can define the ID for the article in your view and then pass it to the template when rendering.

```<code><input type="hidden" id="articleID" name="articleID" value="{{ article.id }}" />
</code>```

or

```<code><input type="hidden" id="articleID" name="articleID" value="{{ id }}" />
</code>```

This way, you can then obtain the value of the article id like you did with the other fields in the javascript function.

Body:
I have a blog site and I made a comment panel under the article. example; user name, mail adress and comment...

I can add these fields using ajax but can't determine which article the comment is made on.
That's inputs..

                    <%-- Name--%>

                        <input type="text" class="form-control" id="t1" name="name" placeholder="Adınız" required tabindex="1">

                    <%-- E-mail--%>

                        <input type="email" class="form-control" id="t2" name="email" placeholder="E-mail Adresiniz" required>

                    <%--  Message--%>

                        <textarea id="t3" name="message" class="form-control" placeholder="Yorumunuz" rows="5" required></textarea>

                        <button type="submit" style="float: right;" class="btn btn-primary" onclick="ekle()">Gönder</button>

that's commentAjax.aspx code behind;

      sqlBaglantisi baglan = new sqlBaglantisi();
string adsoyad, email, yorum, makaleID;
protected void Page_Load(object sender, EventArgs e)
{
    makaleID = Request.QueryString["makaleID"];
    adsoyad = Request.QueryString["adsyd"].ToString();
    email = Request.QueryString["em"].ToString();
    yorum = Request.QueryString["yrm"].ToString();

    SqlCommand cmd = new SqlCommand("insert into Yorum (yorumAdSoyad, yorumEmail, yorumIcerik, yorumResim, makaleID) values('" + adsoyad.ToString() + "','" + email.ToString() + "','" + yorum.ToString() + "','/tema/yorumm.png')", baglan.baglan());
    cmd.ExecuteNonQuery();
}

and js codes;

function ekle() {
var ad = document.getElementById("t1").value;
var mail = document.getElementById("t2").value;
var yorum = document.getElementById("t3").value;

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "yorumAjax.aspx?adsyd=" + ad + "&em=" + mail + "&yrm="+yorum, false);
xmlhttp.send(null);

document.getElementById("t1").value = "";
document.getElementById("t2").value = "";
document.getElementById("t3").value = "";

alert("Mesaj Gönderildi");

I can't understand which comment has come to which article because I can't get the value of articleID.

Body:
You can put a hidden input in your form, containing the actual ID of your article. Something like:

<input type="hidden" id="articleID" name="articleID" value="<the id for this article>" />

If you are using an MVC architecture, you can define the ID for the article in your view and then pass it to the template when rendering.

<input type="hidden" id="articleID" name="articleID" value="{{ article.id }}" />

or

<input type="hidden" id="articleID" name="articleID" value="{{ id }}" />

This way, you can then obtain the value of the article id like you did with the other fields in the javascript function.


问:
Yammer Rest API sender_type = "guide"
We have developed a site that uses the Yammer rest API to retrieve the latest Yammer posts.

We've had an issue where a user has posted a message but the sender_type field is "guide" and not "user". I have looked at the post and other posts that are similar and the other posts all have the sender_type = "user".

```<code>       "sender_id": 130784,
       "replied_to_id": null,
       "created_at": "2016/02/22 07:13:29 +0000",
       "network_id": 130886,
       "message_type": "update",
       "sender_type": "guide",
</code>```

Snippet of the incoming JSON message. We have asked the user and he has not done anything different and their other posts have the send_type as "user". The only difference I can see is that the attachment has been deleted from the post. Other than that the post is a normal post.

If anyone could shed some light on this this would be great.

Thank you.

答:
According to https://github.com/mammerla/YammerIntegration/blob/master/Yammer/SenderType.cs
the following types of sender_type are used at Yammer.

user: Indicates that the creator of a message is a standard user.

guide: Indicates that the message was created to help a user and community within Yammer, e.g., "Welcome to the network, John Doe"

bot: Programmatically created messages, such as those created by an RSS or Twitter import.

chat: Messages created via the chart feature.

announcement: Indicates that the message was created to server as an announcement.

system: System message created on behalf of a user, e.g., "John Doe created a group Foo".

Title: Yammer Rest API sender_type = "guide"

Body:
We have developed a site that uses the Yammer rest API to retrieve the latest Yammer posts.

We've had an issue where a user has posted a message but the sender_type field is "guide" and not "user". I have looked at the post and other posts that are similar and the other posts all have the sender_type = "user".

       "sender_id": 130784,
       "replied_to_id": null,
       "created_at": "2016/02/22 07:13:29 +0000",
       "network_id": 130886,
       "message_type": "update",
       "sender_type": "guide",

Snippet of the incoming JSON message. We have asked the user and he has not done anything different and their other posts have the send_type as "user". The only difference I can see is that the attachment has been deleted from the post. Other than that the post is a normal post.

If anyone could shed some light on this this would be great.

Thank you.


问:
Bash can't find makepkg on server
I'm currently running into an issue where I am not able to use makepkg on my server.

I've verified that pacman is installed correctly so I'm assuming this has to have something to do with my environment PATH?

Trying to run makepkg from my bash prompt I just get

```<code>-bash: makepkg: command not found
</code>```

答:
Well, you need the correct path of command...
Try exec echo in $PATH and try export the path command to $PATH.</p>

```<code>export PATH=$PATH:/path/of/command
</code>```

Title: Bash can't find makepkg on server

Body:
I'm currently running into an issue where I am not able to use makepkg on my server.

I've verified that pacman is installed correctly so I'm assuming this has to have something to do with my environment PATH?

Trying to run makepkg from my bash prompt I just get

-bash: makepkg: command not found

Body:
Well, you need the correct path of command...
Try exec echo in $PATH and try export the path command to $PATH.

export PATH=$PATH:/path/of/command


问:
last entry per group with additional conditions
I have the following code for MYSQL.

```<code>SELECT p1.*
  FROM `tags` p1
  LEFT
  JOIN `tags` p2
    ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp)
 WHERE p2.timestamp IS NULL
</code>```

I want to add the conditional "WHERE unitid = 5".  I'm having a brain fart moment and cannot figure out where to put that.

the source table looks like this:

```<code>Let me clarify what I want this to do.  I have one table.
</code>```

The structure looks like this :

```<code>unitid - cabinetid - timestamp
5        -      6          - timestamp
5        -       7        - timestamp
6        -       6        -   timestamp
7       -        8        - timestamp
</code>```

I want to get all entries for unitid 5, and get the latest entry for each cabinetid

答:
Figured it out.  I just had to double nest the conditional.   </p>

```<code>SELECT o.* FROM( SELECT * FROM `tags` WHERE `unitid` = 6) o LEFT JOIN (

 SELECT * FROM `tags` WHERE `unitid` = 6) b
ON o.cabinetid = b.cabinetid AND o.timestamp < b.timestamp
WHERE b.timestamp is NULL
</code>```

Body:
I have the following code for MYSQL.

SELECT p1.*
  FROM `tags` p1
  LEFT
  JOIN `tags` p2
    ON (p1.cabinetid = p2.cabinetid AND p1.timestamp < p2.timestamp)
 WHERE p2.timestamp IS NULL

I want to add the conditional "WHERE unitid = 5".  I'm having a brain fart moment and cannot figure out where to put that.

the source table looks like this:

Let me clarify what I want this to do.  I have one table.

The structure looks like this :

unitid - cabinetid - timestamp
5        -      6          - timestamp
5        -       7        - timestamp
6        -       6        -   timestamp
7       -        8        - timestamp

I want to get all entries for unitid 5, and get the latest entry for each cabinetid

Body:
Figured it out.  I just had to double nest the conditional.

SELECT o.* FROM( SELECT * FROM `tags` WHERE `unitid` = 6) o LEFT JOIN (

 SELECT * FROM `tags` WHERE `unitid` = 6) b
ON o.cabinetid = b.cabinetid AND o.timestamp < b.timestamp
WHERE b.timestamp is NULL


问:
Android Text to Speech pitch like chipmunk voice
Need help.

How to make an Android TTS like chipmunk voice?

I was set pitch to 15, but nothing much different with pitch = 1.

I'm using TTS with Indonesian local language and work great.

Here is my code:

```<code>@Override
public void onInit(int status) {

    if (status == TextToSpeech.SUCCESS) {

        int result = tts.setLanguage(new Locale("id","ID"));
        tts.setPitch(15);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
            speakOut();
        }

    } else {
        Log.e("TTS", "Initilization Failed!");
    }

}

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void speakOut() {

    String text = mSpeak.toString();

    Toast.makeText(getApplicationContext(), text,Toast.LENGTH_LONG).show();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        tts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
    } else {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}
</code>```

Thanks

答:
I got result like yours.
I changed the

```<code>tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
</code>```

to:

```<code>tts.speak(text, TextToSpeech.QUEUE_ADD, null);
</code>```

Finally it doesn't go like chipmunk voice again.

Body:
Need help.

How to make an Android TTS like chipmunk voice?

I was set pitch to 15, but nothing much different with pitch = 1.

I'm using TTS with Indonesian local language and work great.

Here is my code:

@Override
public void onInit(int status) {

    if (status == TextToSpeech.SUCCESS) {

        int result = tts.setLanguage(new Locale("id","ID"));
        tts.setPitch(15);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
            speakOut();
        }

    } else {
        Log.e("TTS", "Initilization Failed!");
    }

}

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void speakOut() {

    String text = mSpeak.toString();

    Toast.makeText(getApplicationContext(), text,Toast.LENGTH_LONG).show();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        tts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
    } else {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}

Thanks

Body:
I got result like yours.
I changed the

tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

to:

tts.speak(text, TextToSpeech.QUEUE_ADD, null);

Finally it doesn't go like chipmunk voice again.


问:
Getting specific row from a list fails
This is the API output:

```<code>{
    "resultLength":133710,
    "resultList" : [
            {
            "date" :  1510872659568,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6"
            ],
            "score" :  1,
            "totalRequestTime" :  1261,
            "userId" :  167895
            },
            {
            "date" :  1510872659679,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78"
            ],
            "score" :  1,
            "totalRequestTime" :  1255,
            "userId" :  452669
            }
    ]
}
</code>```

I am trying to extract the requestId for each userId, however for some reason I am not able to. This is what I tried:

```<code>req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

solr_df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame(record['requestParameters'][3],columns=['requestId'])
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    solr_df = solr_df.append(df)
</code>```

However it throws a ValueError: DataFrame constructor not properly called!
Can you assist with rectifying the error?

If it too hard to only extract the requestId row for each requestParameter, perhaps you can assist instead removing all rows that aren't requestId related after the for statement runs?

Edit:

When I run it for record['requestParameters'], it runs succesfully but it extracts all rows of requestParameters per userId.

I just tried slicing as such: portfolioId = pd.DataFrame(record['requestParameters'][-1:0]) and it did return results (unlike a single index call), however it was for both outputFormat and requestId rows.
I then tried portfolioId = pd.DataFrame(record['requestParameters'][1:2]) and it returned results for both requestId and datesAsStrings.

It looks like requestParameters rows are not indexed consistently (not sure why it is possible), is there still a way to get a specific row from a list?

Thank you

答:
Why don't you try parsing your json string in Json Editor Online(http://www.jsoneditoronline.org/)? It might help you if your json string is valid or not.

You are missing a comma after 12th line ("totalRequestTime" :  1261). I think that might be the very first problem.

Title: Getting specific row from a list fails

Body:
This is the API output:

{
    "resultLength":133710,
    "resultList" : [
            {
            "date" :  1510872659568,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6"
            ],
            "score" :  1,
            "totalRequestTime" :  1261,
            "userId" :  167895
            },
            {
            "date" :  1510872659679,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78"
            ],
            "score" :  1,
            "totalRequestTime" :  1255,
            "userId" :  452669
            }
    ]
}

I am trying to extract the requestId for each userId, however for some reason I am not able to. This is what I tried:

req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

solr_df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame(record['requestParameters'][3],columns=['requestId'])
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    solr_df = solr_df.append(df)

However it throws a ValueError: DataFrame constructor not properly called!
Can you assist with rectifying the error?

If it too hard to only extract the requestId row for each requestParameter, perhaps you can assist instead removing all rows that aren't requestId related after the for statement runs?

Edit:

When I run it for record['requestParameters'], it runs succesfully but it extracts all rows of requestParameters per userId.

I just tried slicing as such: portfolioId = pd.DataFrame(record['requestParameters'][-1:0]) and it did return results (unlike a single index call), however it was for both outputFormat and requestId rows.
I then tried portfolioId = pd.DataFrame(record['requestParameters'][1:2]) and it returned results for both requestId and datesAsStrings.

It looks like requestParameters rows are not indexed consistently (not sure why it is possible), is there still a way to get a specific row from a list?

Thank you


问:
Eclipse: how to enable compile options, build error in C++, OpenCL program
I get this error when I build C++, OpenCl program by Eclipse IDE for C/C++ Developers Version: Luna Service Release 2 (4.4.2):

```<code>Description Resource    Path    Location    Type
#error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options. SNM     line 32, external location: /usr/include/c++/4.8/bits/c++0x_warning.h   C/C++ Problem
</code>```

I can successfully compile it by terminal($g++...)

How can I solve this problem?

答: add -opencl to the flags. Project Explorer -> Properties -> C/C++ Build -> compiler that you are using -> miscellaneous.</p>

Body:
I get this error when I build C++, OpenCl program by Eclipse IDE for C/C++ Developers Version: Luna Service Release 2 (4.4.2):

Description Resource    Path    Location    Type
#error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options. SNM     line 32, external location: /usr/include/c++/4.8/bits/c++0x_warning.h   C/C++ Problem

I can successfully compile it by terminal($g++...)

How can I solve this problem?


问:
Facebook and Google Play services on unity Error
I have been trying to resolve an error in Unity and can't get it to work at all.

I have Admob and Google Play services installed and by themselves everything is okay; as soon as I add Facebook SDK this is the error I get. I try deleting one of the conflicts and none of them work when deleted. Does anyone know a fix?

```<code> Found conflicting Android library gpgs-plugin-support

Assets/Plugins/Android/gpgs-plugin-support-0.9.42 (managed by the Android Resolver) conflicts with:
Assets/GooglePlayGames/Editor/m2repository/com/google/games/gpgs-plugin-support/0.9.42/gpgs-plugin-support-0.9.42.aar

Your application is unlikely to build in the current state.

To resolve this problem you can try one of the following:
* Updating the dependencies managed by the Android Resolver
  to remove references to old libraries.  Be careful to not
  include conflicting versions of Google Play services.
* Contacting the plugin vendor(s) with conflicting
  dependencies and asking them to update their plugin.

UnityEngine.Debug:LogWarning(Object)
Google.Logger:Log(String, LogLevel)
GooglePlayServices.PlayServicesResolver:Log(String, LogLevel)
GooglePlayServices.ResolverVer1_1:FindAndResolveConflicts()
GooglePlayServices.<DoResolution>c__AnonStorey17:<>m__29()
GooglePlayServices.<DoResolutionUnsafe>c__AnonStorey18:<>m__26(List`1)
GooglePlayServices.<GradleResolution>c__AnonStorey14:<>m__1F(Result)
GooglePlayServices.<GradleResolution>c__AnonStorey15:<>m__28()
GooglePlayServices.PlayServicesResolver:PumpUpdateQueue()
UnityEditor.EditorApplication:Internal_CallUpdateFunctions()
</code>```

答:
There is a tool provided by Google which called Google Play Services Jar Resolver, and you should use it to resolve these conflicts. The latest Facebook SDK (7.10.1) already contains resolver when imported from unitypackage file.

After importing the package, you can resolve client jars in the Unity Editor menu bar, under Assets > Play Services Resolver > Android Resolver.

If it doesn't work for you, you can also get detailed info from github page of jar resolver.

Body:
I have been trying to resolve an error in Unity and can't get it to work at all.

I have Admob and Google Play services installed and by themselves everything is okay; as soon as I add Facebook SDK this is the error I get. I try deleting one of the conflicts and none of them work when deleted. Does anyone know a fix?

 Found conflicting Android library gpgs-plugin-support

Assets/Plugins/Android/gpgs-plugin-support-0.9.42 (managed by the Android Resolver) conflicts with:
Assets/GooglePlayGames/Editor/m2repository/com/google/games/gpgs-plugin-support/0.9.42/gpgs-plugin-support-0.9.42.aar

Your application is unlikely to build in the current state.

To resolve this problem you can try one of the following:
* Updating the dependencies managed by the Android Resolver
  to remove references to old libraries.  Be careful to not
  include conflicting versions of Google Play services.
* Contacting the plugin vendor(s) with conflicting
  dependencies and asking them to update their plugin.

UnityEngine.Debug:LogWarning(Object)
Google.Logger:Log(String, LogLevel)
GooglePlayServices.PlayServicesResolver:Log(String, LogLevel)
GooglePlayServices.ResolverVer1_1:FindAndResolveConflicts()
GooglePlayServices.<DoResolution>c__AnonStorey17:<>m__29()
GooglePlayServices.<DoResolutionUnsafe>c__AnonStorey18:<>m__26(List`1)
GooglePlayServices.<GradleResolution>c__AnonStorey14:<>m__1F(Result)
GooglePlayServices.<GradleResolution>c__AnonStorey15:<>m__28()
GooglePlayServices.PlayServicesResolver:PumpUpdateQueue()
UnityEditor.EditorApplication:Internal_CallUpdateFunctions()


问:
How can I union or combine some columns and not others using sql
I have the following separate reports that I have a request to combine:

```<code>--REPORT #1
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-NOV-2017' and '17-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #2
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-OCT-2017' and '01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #3
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate >='01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #4
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate is null
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)
</code>```

I need to combine these reports so they can be run as one query. The issue I am running into is that the quantity column needs to be separate for each of the reports and using UNION combines them. Each separate Report may not have any results in common so a join doesn't work. So the end result would be something like:

orderid, orderdate, shippeddate, itemcode, itemdescription, QuanitityA, QuantityB, QuantityC, QuantityD

答:
Doesn't OR do what you want?

```<code>select o.orderid, o.orderdate, o.shippeddate, od.itemcode,
       od.itemdescription, od.quantity
from orders o join
     orderdetails od
     on od.orderid = o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017' and
      (o.shippeddate between '01-NOV-2017' and '17-NOV-2017' or
       o.shippeddate between '01-OCT-2017' and '01-NOV-2017' or
       o.shippeddate >= '01-NOV-2017' or
       o.shippeddate is null
      ) and
      o.warehouseid = 1 and
      o.ordertypeid not in (7, 8) and
      o.orderstatusid in (7, 8, 9);
</code>```

Assuming shippeddate is always greater than orderdate (or NULL), then you can remove those conditions.  I would also advise using standard date formats:

```<code>select o.orderid, o.orderdate, o.shippeddate, od.itemcode,
       od.itemdescription, od.quantity
from orders o join
     orderdetails od
     on od.orderid = o.orderid
where o.orderdate between '2017-10-01' and '2017-11-01' and
      ) and
      o.warehouseid = 1 and
      o.ordertypeid not in (7, 8) and
      o.orderstatusid in (7, 8, 9);
</code>```

Body:
I have the following separate reports that I have a request to combine:

--REPORT #1
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-NOV-2017' and '17-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #2
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate  between '01-OCT-2017' and '01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #3
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate >='01-NOV-2017'
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

--REPORT #4
select o.orderid, o.orderdate, o.shippeddate, od.itemcode, od.itemdescription, od.quantity from orders o
join orderdetails od on od.orderid=o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017'
and o.shippeddate is null
and o.warehouseid=1
and o.ordertypeid not in (7,8)
and o.orderstatusid in (7,8,9)

I need to combine these reports so they can be run as one query. The issue I am running into is that the quantity column needs to be separate for each of the reports and using UNION combines them. Each separate Report may not have any results in common so a join doesn't work. So the end result would be something like:

orderid, orderdate, shippeddate, itemcode, itemdescription, QuanitityA, QuantityB, QuantityC, QuantityD

Body:
Doesn't OR do what you want?

select o.orderid, o.orderdate, o.shippeddate, od.itemcode,
       od.itemdescription, od.quantity
from orders o join
     orderdetails od
     on od.orderid = o.orderid
where o.orderdate between '01-OCT-2017' and '01-NOV-2017' and
      (o.shippeddate between '01-NOV-2017' and '17-NOV-2017' or
       o.shippeddate between '01-OCT-2017' and '01-NOV-2017' or
       o.shippeddate >= '01-NOV-2017' or
       o.shippeddate is null
      ) and
      o.warehouseid = 1 and
      o.ordertypeid not in (7, 8) and
      o.orderstatusid in (7, 8, 9);

Assuming shippeddate is always greater than orderdate (or NULL), then you can remove those conditions.  I would also advise using standard date formats:

select o.orderid, o.orderdate, o.shippeddate, od.itemcode,
       od.itemdescription, od.quantity
from orders o join
     orderdetails od
     on od.orderid = o.orderid
where o.orderdate between '2017-10-01' and '2017-11-01' and
      ) and
      o.warehouseid = 1 and
      o.ordertypeid not in (7, 8) and
      o.orderstatusid in (7, 8, 9);


问:
Inputting as a Char Array
I am trying to get input as a character array and manipulate it. For example this is what I have. But I just started arrays and I am confused getting confused on how I should be storing the char array.

```<code>   void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS; i++)
        {
            cin >> message[i];
            if (message[i] == NULL)
                break;
        }
            cout << "The message you entered was:" << endl << message[i] << endl;
   }
</code>```

Characters is equal to the constant 100 since I do not know the size of the array, it is based off of user input. When I try to get the array to output it doesn't.

答:
```<code>// Example program
#include <iostream>
#include <string>

using namespace std;

const int CHARACTERS = 100;

void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS-1; i++)
        {
            message[i] = cin.get(); // cin >> message[i] can't detect enter press as was in your case, so you need to use a lower level function like cin.get()
            if (message[i] == '\n'){
                message[i+1] = '\0'; // This is a c++ marker for end of string otherwise garbage values will print
                break;
            }
        }
            cout << "The message you entered was:" << endl << message << endl; //You were printing only one letter of the message
   }

int main()
{
    char inputArray[CHARACTERS];
    getMessage(inputArray);
}
</code>```

Run online: http://cpp.sh/6rh3w

Title: Inputting as a Char Array

Body:
I am trying to get input as a character array and manipulate it. For example this is what I have. But I just started arrays and I am confused getting confused on how I should be storing the char array.

   void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS; i++)
        {
            cin >> message[i];
            if (message[i] == NULL)
                break;
        }
            cout << "The message you entered was:" << endl << message[i] << endl;
   }

Characters is equal to the constant 100 since I do not know the size of the array, it is based off of user input. When I try to get the array to output it doesn't.

Body:
// Example program
#include <iostream>
#include <string>

using namespace std;

const int CHARACTERS = 100;

void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS-1; i++)
        {
            message[i] = cin.get(); // cin >> message[i] can't detect enter press as was in your case, so you need to use a lower level function like cin.get()
            if (message[i] == '\n'){
                message[i+1] = '\0'; // This is a c++ marker for end of string otherwise garbage values will print
                break;
            }
        }
            cout << "The message you entered was:" << endl << message << endl; //You were printing only one letter of the message
   }

int main()
{
    char inputArray[CHARACTERS];
    getMessage(inputArray);
}

Run online: http://cpp.sh/6rh3w


问:
How to model users & permissions in EA?
I wonder how can I model relations between users and functions. I have 12 different actors in the system. On the other hand, there are 120 unique functions (not use cases) I can assign to users.

Does EA provide any matrix I can define connections between users and functions? Which type of diagram should I use?

答:
There is no relationship matrix for this. You could write your own, but that's not trivial (though possible). What you could do is to create associations between actors and class operations (which is what I think you mean by functions) and issue the context menu near the class:

Link to Element Feature opens a menu where you choose Operation and select the appropriate operation:

This finally results in this:

You can attach more than one association this way. Note that the quick linker does not offer Association so you need to choose it from the context menu or the toolbox.

Title: How to model users & permissions in EA?


问:
JQuery POST request user feedback
I have the form that submits with a jQuery post request. Something like this:

```<code>$('#foo').submit(function (e) {
    $.post('/api/baz/break', $(this).serialize())
        .done(function (guidString) {
            // manipulate good result
        })
        .fail(function (data) {
            // manipulate bad result
        });
    e.preventDefault();
});
</code>```

My problem is that on the good result there is no visual feedback to the user to show that a process is completing.

What is the simplest way that I show the user a visual spinner that lets them see that something is going on? Since the page doesn't reload because the promise hasn't been resolved.

答:
So I managed to fix this on my own. I made a css loader component following the guidelines from w3schools linked here https://www.w3schools.com/howto/howto_css_loader.asp

I customized mine like so:

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loader {
  /*Warning- this class must be attached to a div to work properly, can attach and remove dynamically with javascript for async operations*/
  border-top: 1em solid #106A3A;
  border-right: 1em solid #E58242;
  border-bottom: 1em solid #91D3EF;
  border-left: 1em solid #7F3E97;
  border-radius: 50%;
  width: 7.5em;
  height: 7.5em;
  animation: spin 2s linear infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='loader'></div></code>```

So in the js I just added the component in the javascript layer like so:

```<code>$('#foo').submit(function (e) {
    $('#foo').toggle();
    $('fooParent').append('<div class="loader"></div>');
    $.post('/api/baz/break', $(this).serialize())
        .done(function (guidString) {
            // manipulate good result
            $('#foo').toggle();
            $('loader').remove();
        })
        .fail(function (data) {
            // manipulate bad result
            $('#foo').toggle();
            $('loader').remove();
        });
    e.preventDefault();
});
</code>```

Title: JQuery POST request user feedback

Body:
I have the form that submits with a jQuery post request. Something like this:

$('#foo').submit(function (e) {
    $.post('/api/baz/break', $(this).serialize())
        .done(function (guidString) {
            // manipulate good result
        })
        .fail(function (data) {
            // manipulate bad result
        });
    e.preventDefault();
});

My problem is that on the good result there is no visual feedback to the user to show that a process is completing.

What is the simplest way that I show the user a visual spinner that lets them see that something is going on? Since the page doesn't reload because the promise hasn't been resolved.

Body:
So I managed to fix this on my own. I made a css loader component following the guidelines from w3schools linked here https://www.w3schools.com/howto/howto_css_loader.asp

I customized mine like so:

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loader {
  /*Warning- this class must be attached to a div to work properly, can attach and remove dynamically with javascript for async operations*/
  border-top: 1em solid #106A3A;
  border-right: 1em solid #E58242;
  border-bottom: 1em solid #91D3EF;
  border-left: 1em solid #7F3E97;
  border-radius: 50%;
  width: 7.5em;
  height: 7.5em;
  animation: spin 2s linear infinite;
}

<div class='loader'></div>

So in the js I just added the component in the javascript layer like so:

$('#foo').submit(function (e) {
    $('#foo').toggle();
    $('fooParent').append('<div class="loader"></div>');
    $.post('/api/baz/break', $(this).serialize())
        .done(function (guidString) {
            // manipulate good result
            $('#foo').toggle();
            $('loader').remove();
        })
        .fail(function (data) {
            // manipulate bad result
            $('#foo').toggle();
            $('loader').remove();
        });
    e.preventDefault();
});


问:
Apache ignite QueryEntity Based Configuration
My  model (i.e. valueType) is wrapped Map -

```<code>class Model {
  Map<String,Object> data;
  Object  get(String key){}
}
</code>```

How to get all "Models" ordered by data's some keys.

I want to execute this query on Models cache "select * from Model ORDER BY name* " where the "name" is some key of the "data".
How can I do that  my "indexes" to be my "data" 's some keys.

答: You can't index collection elements. Instead, you should have name as a separate field and configure it to be indexed in corresponding QueryEntity.

Body:
My  model (i.e. valueType) is wrapped Map -

class Model {
  Map<String,Object> data;
  Object  get(String key){}
}

How to get all "Models" ordered by data's some keys.

I want to execute this query on Models cache "select * from Model ORDER BY name* " where the "name" is some key of the "data".
How can I do that  my "indexes" to be my "data" 's some keys.


问:
How to enable GZip in a Vapor app?
I found two GitHub repositories, but both of them seem to be outdated:

https://github.com/vapor-community/gzip-provider

https://github.com/jhonny-me/GzipMiddleware

The second solution worked fine before Vapor 2.0 release.

I'm using Vapor 2.1 with Swift 3, how can I enable GZip?

答:
You cannot... At this moment there is no gzip middleware for Vapor.

Also, probably no-one would be interested in fixing those libs before Vapor 3 release.

Title: How to enable GZip in a Vapor app?


问:
is passport required when using JWT
Very basic question but probably I miss something very big in the big picture.
I cannot figure out whether passport.js is needed or not when using JWT auth. Most examples have it but I fail to see the need.

In my app, there is a /login route and once the user authenticates successfully ( local auth, I check user, a hash pair in the database) I create a token with user id in it, set an expiry, sign it and send it back as the cookie in the response. Then I check the req cookies, decrypt and if they contain user id and not expired, I consider the request authenticated. (also traffic is https only if it changes anything)

Am I doing something wrong here as I don't have passport etc. in the process?

答: No, JWT (RFC 7519) is a standard. passport.js is an implementation that uses JWT. It is not required.

Title: is passport required when using JWT


问:
How to get start and end of day in Javascript?
How to get start ( 00:00:00 ) and end ( 23:59:59 ) of today in timestamp ( GMT )? Computer use a local time.</p>

答:
Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter

```<code>var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
</code>```

remove .toUTC() if you need only the local time

and you may ask why not moment.js, answer is here for that.

Body:
Using the luxon.js library, same can be achieved using startOf and endOf methods by passing the 'day' as parameter

var DateTime = luxon.DateTime;
DateTime.local().startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z
DateTime.local().endOf('day').toUTC().toISO(); //2017-11-17T18:29:59.999Z
DateTime.fromISO(new Date().toISOString()).startOf('day').toUTC().toISO(); //2017-11-16T18:30:00.000Z

remove .toUTC() if you need only the local time

and you may ask why not moment.js, answer is here for that.


问:
Java reference outer Class scope in callback
In class Foo, I'm performing an HTTP post, returning to a callback:

```<code>class Foo {

    private static void send() {

        HttpPostRequest task = new HttpPostRequest(data, new HttpPostRequest.CustomCallback() {
            @Override
            public void completionHandler(Boolean success, String result) {

                // this doesn't work
                // this.anotherMethod();
            }
        });
        task.execute("https://foo.org");
    }

    private static void anotherMethod() {
      // i need to do things here...
    }

}
</code>```

This callback works, however I need to call another method in the outer class scope. I can't figure out how to do this: How do I properly reference this outer scope?

答:
When both methods are static you can simply call:

```<code>Foo.anotherMethod()
</code>```

if both are not static, you can do:

```<code>Foo.this.anotherMethod()
</code>```

Body:
In class Foo, I'm performing an HTTP post, returning to a callback:

class Foo {

    private static void send() {

        HttpPostRequest task = new HttpPostRequest(data, new HttpPostRequest.CustomCallback() {
            @Override
            public void completionHandler(Boolean success, String result) {

                // this doesn't work
                // this.anotherMethod();
            }
        });
        task.execute("https://foo.org");
    }

    private static void anotherMethod() {
      // i need to do things here...
    }

}

This callback works, however I need to call another method in the outer class scope. I can't figure out how to do this: How do I properly reference this outer scope?

Body:
When both methods are static you can simply call:

Foo.anotherMethod()

if both are not static, you can do:

Foo.this.anotherMethod()


答: I would do a select distint with the common columns (orderid, orderdate, shippeddate, itemcode, itemdescription) and then start doing left join with each one of your queries.</p>

Title: How can I union or combine some columns and not others using sql


问:
Having trouble with the syntax of a string in Javascript
```<code>fill(225, 0, 225);
var draw = function() {
    background(255, 255, 255);
    ellipse(mouseX, mouseY, 12, 12);
    var label = mouseX + "36", "45" + mouseY;
    text(label, mouseX, mouseY);
};
</code>```

I'm creating a small mouse tracker program that calls the coordinates of the mouse pointer just below and to the right of a small circle, using Khan Academy, it's one of their challenges. In particular I'm getting errors when creating the string where I'm attempting to store mouseX and Y along with some coordinates in to the variable 'label'.

答:
You do not need var next to the draw = function(), and instead of putting the numbers in the quotes, put a space between the quotes, also make the label variable outside of the draw function, so that your code looks like this :</p>

```<code>var label;
draw = function() {
    background(255, 255, 255);
    fill(225, 0, 225);
    ellipse(mouseX, mouseY, 12, 12);
    label = "    " + mouseX + "   " + mouseY;
    fill(0,0,0);
    text(label, mouseX, mouseY);
};
</code>```

Body:
fill(225, 0, 225);
var draw = function() {
    background(255, 255, 255);
    ellipse(mouseX, mouseY, 12, 12);
    var label = mouseX + "36", "45" + mouseY;
    text(label, mouseX, mouseY);
};

I'm creating a small mouse tracker program that calls the coordinates of the mouse pointer just below and to the right of a small circle, using Khan Academy, it's one of their challenges. In particular I'm getting errors when creating the string where I'm attempting to store mouseX and Y along with some coordinates in to the variable 'label'.

Body:
You do not need var next to the draw = function(), and instead of putting the numbers in the quotes, put a space between the quotes, also make the label variable outside of the draw function, so that your code looks like this :

var label;
draw = function() {
    background(255, 255, 255);
    fill(225, 0, 225);
    ellipse(mouseX, mouseY, 12, 12);
    label = "    " + mouseX + "   " + mouseY;
    fill(0,0,0);
    text(label, mouseX, mouseY);
};


问:
Correctly use export = and export default in Typescript to create types for lighthouse
I'm trying to create a .d.ts for this lighthouse file and I strugle to understand how to deal with the default export

https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/index.js#L28

```<code>module.exports = function(url, flags = {}, configJSON) {
  const startTime = Date.now();
  return Promise.resolve().then(_ => {
    // set logging preferences, assume quiet
    flags.logLevel = flags.logLevel || 'error';
    log.setLevel(flags.logLevel);

    // Use ConfigParser to generate a valid config file
    const config = new Config(configJSON, flags.configPath);

    const connection = new ChromeProtocol(flags.port, flags.hostname);

    // kick off a lighthouse run
    return Runner.run(connection, {url, flags, config})
      .then(lighthouseResults => {
        // Annotate with time to run lighthouse.
        const endTime = Date.now();
        lighthouseResults.timing = lighthouseResults.timing || {};
        lighthouseResults.timing.total = endTime - startTime;

        return lighthouseResults;
      });
  });
};

module.exports.getAuditList = Runner.getAuditList;
module.exports.traceCategories = require('./gather/driver').traceCategories;
module.exports.Audit = require('./audits/audit');
module.exports.Gatherer = require('./gather/gatherers/gatherer');
</code>```

At this stage, I have a lighthouse.d.ts file in my project with:

```<code>declare module "lighthouse" {

  export interface flags {
    port: number;
    disableCpuThrottling: boolean;
    disableDeviceEmulation: boolean;
    disableNetworkThrottling: boolean;
  }

  export default function lighthouse(url: string, flags: flags, perfConfig: any): any
}
</code>```

It seems to be typed properly. if I import using import * as lighthouse from "lighthouse";, I can do lighthouse.default and lighthouse.flags where I need.

But if I run my code, I get TypeError: lighthouse.default is not a function. Am I forced to use export =? If I don't have choice, how to use export = but export the function, the flags type, and getAuditList, traceCategories, Audit, Gatherer?

答:
This is the way that a commonjs module exports something as default ...

```<code>module.exports.default = ...;
</code>```

... and there's no sign of it in the code sample. The module exports just one function and assign some properties to it. Try using this as a starting point for a .d.ts:

```<code>declare module "lighthouse" { // the module name must be in quotes

    const lighthouse: { // it must be a "const".

        //here starts the signature "(...): any " that describes the object as callable
        (url: string,
         flags: {
                     port?: number;                       // all of these flags keys must be "?"
                     disableCpuThrottling?: boolean;      // because the parameter initializer
                     disableDeviceEmulation?: boolean;    // is an empty {}
                     disableNetworkThrottling?: boolean;  //
         } = {},
         perfConfig: any): any;

        //  and here are all the properties that the library has attached to the function.
        getAuditList: ...;    //
        traceCategories: ...; //  give them the correct type for a better compiler support
        Audit: ...;           //
        Gatherer: ...;        //
    }

    export = lighthouse; // <-finally
}
</code>```

And this is how it must be used in a .ts file

```<code>import * as lighthouse from "lighthouse";

lighthouse(...);                //<- invoke it directly
...lighthouse.traceCategories...; //<- get access to one of it's properties
</code>```

Using "export ="  will not wrap the function inside an object so the transpiled .js file will be like:

```<code>var lighthouse = require("lighthouse");
lighthouse(...); // this is the desired result and not _whateverName.lighthouse(...);
</code>```

Body:
I'm trying to create a .d.ts for this lighthouse file and I strugle to understand how to deal with the default export

https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/index.js#L28

module.exports = function(url, flags = {}, configJSON) {
  const startTime = Date.now();
  return Promise.resolve().then(_ => {
    // set logging preferences, assume quiet
    flags.logLevel = flags.logLevel || 'error';
    log.setLevel(flags.logLevel);

    // Use ConfigParser to generate a valid config file
    const config = new Config(configJSON, flags.configPath);

    const connection = new ChromeProtocol(flags.port, flags.hostname);

    // kick off a lighthouse run
    return Runner.run(connection, {url, flags, config})
      .then(lighthouseResults => {
        // Annotate with time to run lighthouse.
        const endTime = Date.now();
        lighthouseResults.timing = lighthouseResults.timing || {};
        lighthouseResults.timing.total = endTime - startTime;

        return lighthouseResults;
      });
  });
};

module.exports.getAuditList = Runner.getAuditList;
module.exports.traceCategories = require('./gather/driver').traceCategories;
module.exports.Audit = require('./audits/audit');
module.exports.Gatherer = require('./gather/gatherers/gatherer');

At this stage, I have a lighthouse.d.ts file in my project with:

declare module "lighthouse" {

  export interface flags {
    port: number;
    disableCpuThrottling: boolean;
    disableDeviceEmulation: boolean;
    disableNetworkThrottling: boolean;
  }

  export default function lighthouse(url: string, flags: flags, perfConfig: any): any
}

It seems to be typed properly. if I import using import * as lighthouse from "lighthouse";, I can do lighthouse.default and lighthouse.flags where I need.

But if I run my code, I get TypeError: lighthouse.default is not a function. Am I forced to use export =? If I don't have choice, how to use export = but export the function, the flags type, and getAuditList, traceCategories, Audit, Gatherer?

Body:
This is the way that a commonjs module exports something as default ...

module.exports.default = ...;

... and there's no sign of it in the code sample. The module exports just one function and assign some properties to it. Try using this as a starting point for a .d.ts:

declare module "lighthouse" { // the module name must be in quotes

    const lighthouse: { // it must be a "const".

        //here starts the signature "(...): any " that describes the object as callable
        (url: string,
         flags: {
                     port?: number;                       // all of these flags keys must be "?"
                     disableCpuThrottling?: boolean;      // because the parameter initializer
                     disableDeviceEmulation?: boolean;    // is an empty {}
                     disableNetworkThrottling?: boolean;  //
         } = {},
         perfConfig: any): any;

        //  and here are all the properties that the library has attached to the function.
        getAuditList: ...;    //
        traceCategories: ...; //  give them the correct type for a better compiler support
        Audit: ...;           //
        Gatherer: ...;        //
    }

    export = lighthouse; // <-finally
}

And this is how it must be used in a .ts file

import * as lighthouse from "lighthouse";

lighthouse(...);                //<- invoke it directly
...lighthouse.traceCategories...; //<- get access to one of it's properties

Using "export ="  will not wrap the function inside an object so the transpiled .js file will be like:

var lighthouse = require("lighthouse");
lighthouse(...); // this is the desired result and not _whateverName.lighthouse(...);


问:
Break from loop after given a number
I am having issue to have my "break loop" to work, it doesn't throw any error so I can't even see what's happening. It is the option 3 when I tell the script to start blinking my LED. Originally I was looking into some ways if there is a way to run your loop and go back to your MainMenu while the loop is still running, But that wasn't the options, so I wanted to try something similar to use "for number in range(10):"

```<code>def loop():
    while True:
        os.system('clear')
        print
        print ('1. ON')
        print ('2. OFF')
        print ('3. Blink')
        print
        choice = int(raw_input('1-[ON], 2-[OFF]: '))
        if choice == 1:
            print
            print ('Turning ON')
            GPIO.output(LedPin, GPIO.LOW)  # Led ON
        elif choice == 2:
            print
            print ('Turning OFF')
            GPIO.output(LedPin, GPIO.HIGH)  # Led OFF
        elif choice == 3:
            number = 0
            for number in range(10):
               number = number + 1
               if number == 5:
                  break
                  GPIO.output(LedPin, GPIO.LOW + str(number))  # Led ON
                  time.sleep(0.05)
                  GPIO.output(LedPin, GPIO.HIGH + str(number))  # Led OFF
                  time.sleep(0.05)
               #print ('Number is ' + str(number))
</code>```

this example works fine:

```<code>    number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      break    # break here

   print('Number is ' + str(number))

print('Out of loop')
</code>```

Output:

```<code>Number is 1
Number is 2
Number is 3
Number is 4
Out of loop
</code>```

答:
If I understand correctly, you want to toggle the light if number == 5

```<code>        elif choice == 3:
           for number in range(0,5):
              GPIO.output(LedPin, GPIO.LOW + str(number))  # Led ON
                 time.sleep(0.05)
                 GPIO.output(LedPin, GPIO.HIGH + str(number))  # Led OFF
                 time.sleep(0.05)
           #print ('Number is ' + str(number)) #will be 4, went 5 times
</code>```

Title: Break from loop after given a number

Body:
I am having issue to have my "break loop" to work, it doesn't throw any error so I can't even see what's happening. It is the option 3 when I tell the script to start blinking my LED. Originally I was looking into some ways if there is a way to run your loop and go back to your MainMenu while the loop is still running, But that wasn't the options, so I wanted to try something similar to use "for number in range(10):"

def loop():
    while True:
        os.system('clear')
        print
        print ('1. ON')
        print ('2. OFF')
        print ('3. Blink')
        print
        choice = int(raw_input('1-[ON], 2-[OFF]: '))
        if choice == 1:
            print
            print ('Turning ON')
            GPIO.output(LedPin, GPIO.LOW)  # Led ON
        elif choice == 2:
            print
            print ('Turning OFF')
            GPIO.output(LedPin, GPIO.HIGH)  # Led OFF
        elif choice == 3:
            number = 0
            for number in range(10):
               number = number + 1
               if number == 5:
                  break
                  GPIO.output(LedPin, GPIO.LOW + str(number))  # Led ON
                  time.sleep(0.05)
                  GPIO.output(LedPin, GPIO.HIGH + str(number))  # Led OFF
                  time.sleep(0.05)
               #print ('Number is ' + str(number))

this example works fine:

    number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      break    # break here

   print('Number is ' + str(number))

print('Out of loop')

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Out of loop

Body:
If I understand correctly, you want to toggle the light if number == 5

        elif choice == 3:
           for number in range(0,5):
              GPIO.output(LedPin, GPIO.LOW + str(number))  # Led ON
                 time.sleep(0.05)
                 GPIO.output(LedPin, GPIO.HIGH + str(number))  # Led OFF
                 time.sleep(0.05)
           #print ('Number is ' + str(number)) #will be 4, went 5 times


问:
Angular2 - Importing angular modules
Modules are imported in app.module.ts, by adding an entry below,

```<code>@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DirectoryComponent,
    FilterPipe,
    LoggingService
  ],
  imports: [
    FormsModule,
    BrowserModule,
    HttpClientModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
</code>```

but RouterModule is directly used in ../src/app/app.routes.ts, as shown below,

```<code>import {Routes, RouterModule} from "@angular/router";
export const routes:Routes = [
    /* Each route will be an object {}*/
    {path: 'directory', component: DirectoryComponent},
    {path: '',          component: HomeComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

There is no entry of RouterModule in @NgModule(imports: [..]).

1)
Are there different ways to import an angular module?

2)
Is import of angular module different from import of typescript module?

答:
In your routes.ts you are creating the constant called routes, assigning it the RouterModule and exporting it.

In your app, you're importing the routes constant, which is just a reference to the Module, just like any other:

```<code>@NgModule(
 .... imports: [
         routing, // here you are using the const
      ],
....
)
</code>```

And you are assigning it on this line:

```<code> export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

You could instead use the exported routes and use that in your app.module:

```<code>@NgModule(
 .... imports: [
         RouterModule.forRoot(routes),
      ],
....
</code>```

The first is just assigning it to a variable (well const) before using it.

Typescript modules are different from Angular modules. Typescript modules allow you to share typescript objects between typescript files. You use them everywhere, even in non angular typescript. They're the import { something } from 'myfile.ts' and it gets transpiled to JavaScript ES5 require statements, and just like ES6 importing. Not many people refer to these as modules much in my experience.

Angular modules are modular chunks of angular components, services, directives and pipes etc bundled to so the compiler knows what to do with them, and you can easily compose angular apps from them. If anyone is talking about angular and modules it's likely they're talking about these because typescript modules are so fundamental - every typescript file will have multiple imports at the top.

Title: Angular2 - Importing angular modules

Body:
Modules are imported in app.module.ts, by adding an entry below,

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DirectoryComponent,
    FilterPipe,
    LoggingService
  ],
  imports: [
    FormsModule,
    BrowserModule,
    HttpClientModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})

but RouterModule is directly used in ../src/app/app.routes.ts, as shown below,

import {Routes, RouterModule} from "@angular/router";
export const routes:Routes = [
    /* Each route will be an object {}*/
    {path: 'directory', component: DirectoryComponent},
    {path: '',          component: HomeComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

There is no entry of RouterModule in @NgModule(imports: [..]).

1)
Are there different ways to import an angular module?

2)
Is import of angular module different from import of typescript module?

Body:
In your routes.ts you are creating the constant called routes, assigning it the RouterModule and exporting it.

In your app, you're importing the routes constant, which is just a reference to the Module, just like any other:

@NgModule(
 .... imports: [
         routing, // here you are using the const
      ],
....
)

And you are assigning it on this line:

 export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

You could instead use the exported routes and use that in your app.module:

@NgModule(
 .... imports: [
         RouterModule.forRoot(routes),
      ],
....

The first is just assigning it to a variable (well const) before using it.

Typescript modules are different from Angular modules. Typescript modules allow you to share typescript objects between typescript files. You use them everywhere, even in non angular typescript. They're the import { something } from 'myfile.ts' and it gets transpiled to JavaScript ES5 require statements, and just like ES6 importing. Not many people refer to these as modules much in my experience.

Angular modules are modular chunks of angular components, services, directives and pipes etc bundled to so the compiler knows what to do with them, and you can easily compose angular apps from them. If anyone is talking about angular and modules it's likely they're talking about these because typescript modules are so fundamental - every typescript file will have multiple imports at the top.


问:
Removing Duplication In Ramda Function
How can I remove the duplicated calls to findIndexInO in compareIndexes?

```<code>const a = [
  {name: 'charlie', value: 1},
  {name: 'bravo', value: 7},
  {name: 'delta', value: 12},
  {name: 'alpha', value: 19},
]

const propEqName = propEq('name');
const findIndexInO = findIndex(__, a);
const compareIndexes = comparator((from, to) => lt(findIndexInO(propEqName(from)), findIndexInO(propEqName(to))))
const sortOnIndex = sort(compareIndexes);

const decideOrder = (...args) => sortOnIndex(args);

decideOrder('delta', 'charlie'); // ['charlie', 'delta']
decideOrder('bravo', 'alpha'); // ['bravo', 'alpha']
decideOrder('alpha', 'charlie'); // ['charlie', 'alpha']
</code>```

REPL

答:
How about

```<code>const order = addIndex(reduce)((ord, a, idx) => assoc(a.name, idx, ord), {}, a)
const decideOrder = unapply(sortBy(prop(__, order)))
</code>```

? Since you're already embedding a in your function.  As an added benefit, you would then also be able to do this, if it matters to you:

```<code>decideOrder('delta', 'alpha', 'bravo') //=> ["bravo", "delta", "alpha"]
</code>```

Title: Removing Duplication In Ramda Function

Body:
How can I remove the duplicated calls to findIndexInO in compareIndexes?

const a = [
  {name: 'charlie', value: 1},
  {name: 'bravo', value: 7},
  {name: 'delta', value: 12},
  {name: 'alpha', value: 19},
]

const propEqName = propEq('name');
const findIndexInO = findIndex(__, a);
const compareIndexes = comparator((from, to) => lt(findIndexInO(propEqName(from)), findIndexInO(propEqName(to))))
const sortOnIndex = sort(compareIndexes);

const decideOrder = (...args) => sortOnIndex(args);

decideOrder('delta', 'charlie'); // ['charlie', 'delta']
decideOrder('bravo', 'alpha'); // ['bravo', 'alpha']
decideOrder('alpha', 'charlie'); // ['charlie', 'alpha']

<a href="http://ramdajs.com/repl/?v=0.24.1#?const%20a%20%3D%20%5B%0A%20%20%7Bname%3A%20%27charlie%27%2C%20value%3A%201%7D%2C%0A%20%20%7Bname%3A%20%27bravo%27%2C%20value%3A%207%7D%2C%0A%20%20%7Bname%3A%20%27delta%27%2C%20value%3A%2012%7D%2C%0A%20%20%7Bname%3A%20%27alpha%27%2C%20value%3A%2019%7D%2C%0A%5D%0A%0Aconst%20propEqName%20%3D%20propEq%28%27name%27%29%3B%0Aconst%20findIndexInO%20%3D%20findIndex%28__%2C%20a%29%3B%0Aconst%20compareIndexes%20%3D%20comparator%28%28from%2C%20to%29%20%3D%3E%20lt%28findIndexInO%28propEqName%28from%29%29%2C%20findIndexInO%28propEqName%28to%29%29%29%29%0Aconst%20sortOnIndex%20%3D%20sort%28compareIndexes%29%3B%0A%0Aconst%20decideOrder%20%3D%20%28...args%29%20%3D%3E%20sortOnIndex%28args%29%3B%0A%0AdecideOrder%28%27delta%27%2C%20%27charlie%27%29%3B%20%2F%2F%20%5B%27charlie%27%2C%20%27delta%27%5D%0AdecideOrder%28%27bravo%27%2C%20%27alpha%27%29%3B%20%2F%2F%20%5B%27bravo%27%2C%20%27alpha%27%5D%0AdecideOrder%28%27alpha%27%2C%20%27charlie%27%29%3B%20%2F%2F%20%5B%27charlie%27%2C%20%27alpha%27%5D%0A%0A" rel="nofollow noreferrer">REPL

Body:
How about

const order = addIndex(reduce)((ord, a, idx) => assoc(a.name, idx, ord), {}, a)
const decideOrder = unapply(sortBy(prop(__, order)))

? Since you're already embedding a in your function.  As an added benefit, you would then also be able to do this, if it matters to you:

decideOrder('delta', 'alpha', 'bravo') //=> ["bravo", "delta", "alpha"]