问:
Segmentation fault error when returning the function
So,I am writing an interpreter for LC3b machines. I need to write a function to check whether the input is a valid opcode or not. For that, I have written a function as follows:

```<code>int isOpcode(char* oput)//oput=Opcode under test
{
  FILE* isa_file = NULL;
  int i,j;
  char * line = NULL;
  size_t len = 0;
  ssize_t nread;

  //printf("Entered opcode checking function \n");
  /*convert to lower case */
  //for( i = 0; i < strlen( oput ); i++ )
  //    oput[i] = tolower( oput[i] );
  //printf("Entered opcode checking function1 \n");

  /*for modularity, using the file */
   isa_file = fopen("isa", "r");
   if(isa_file == NULL)
       printf("Error in file opening\n");
   int flag;
   while ((nread = getline(&line, &len, isa_file)) != -1)
   {
       printf("Retrieved line of length %zu :\n", nread);
       printf("%s", line);
       //Solving the new line character problem which resulted in the improper difference of strcmp ..now it is proper...
       //char final[strlen(line)-1];
       //strcpy(final,line);
       //final[strlen(line)-1]='\0';
       //  printf("Entered opcode checking function2 \n");
       //  printf("%s \n",oput);
       // overwrite \n with nul-terminator
       line[strcspn(line, "\n")] = 0;
       char final[strlen(line)];
       strcpy(final,line);
       flag=strcmp(oput,final);
       printf("%s \n",oput);
       printf("flag: %d \n",flag );
       if(flag < 0 || flag >0)
       {
           flag=-1;
           //printf("entered 1st condition \n");
           printf("final flag: %d \n", flag);
        }
       else
       {
           flag=1;
           //printf("entered negative \n");
           printf("final flag: %d \n", flag);
           break;
       }

   }
   printf("end of loop \n");//this is not getting printed
   fclose(isa_file);
   if (line)
       free(line);
   return flag;
}
</code>```

Now, when I call the function with one of the valid opcodes,the function prints the final flag(=1) and then goes into segmentation fault. It doesnt even print end of loop statement. Could someone tell me what is the problem? I tried executing parts of this function in parts as separate files and it seems to work perfectly.

UPDATE:
The end of loop statement now gets printed on the screen when I commented out the toLower code.However,even then code then throws a seg fault. Interestingly, it throws an error only when the final flag is set to 1. Else, it works fine! I am unable to understand this strange issue!

答:
After your comment I can say:

strlen already gives you the length of read chars -1, 'cause the nul-terminator is not counted. Moreover you cannot use strcpy to do what you need to do, 'cause it will copy all chars of source string into a smaller string causing UB.

What you can do is to remove the '\n' in the source string and then copy it, like:

```<code>// overwrite \n with nul-terminator
line[strcspn(line, "\n")] = 0;
// allocate new string less by one
char final[strlen(line)+1];
// allocate new string less by one
strcpy(final,line);
</code>```

Body:
So,I am writing an interpreter for LC3b machines. I need to write a function to check whether the input is a valid opcode or not. For that, I have written a function as follows:

int isOpcode(char* oput)//oput=Opcode under test
{
  FILE* isa_file = NULL;
  int i,j;
  char * line = NULL;
  size_t len = 0;
  ssize_t nread;

  //printf("Entered opcode checking function \n");
  /*convert to lower case */
  //for( i = 0; i < strlen( oput ); i++ )
  //    oput[i] = tolower( oput[i] );
  //printf("Entered opcode checking function1 \n");

  /*for modularity, using the file */
   isa_file = fopen("isa", "r");
   if(isa_file == NULL)
       printf("Error in file opening\n");
   int flag;
   while ((nread = getline(&line, &len, isa_file)) != -1)
   {
       printf("Retrieved line of length %zu :\n", nread);
       printf("%s", line);
       //Solving the new line character problem which resulted in the improper difference of strcmp ..now it is proper...
       //char final[strlen(line)-1];
       //strcpy(final,line);
       //final[strlen(line)-1]='\0';
       //  printf("Entered opcode checking function2 \n");
       //  printf("%s \n",oput);
       // overwrite \n with nul-terminator
       line[strcspn(line, "\n")] = 0;
       char final[strlen(line)];
       strcpy(final,line);
       flag=strcmp(oput,final);
       printf("%s \n",oput);
       printf("flag: %d \n",flag );
       if(flag < 0 || flag >0)
       {
           flag=-1;
           //printf("entered 1st condition \n");
           printf("final flag: %d \n", flag);
        }
       else
       {
           flag=1;
           //printf("entered negative \n");
           printf("final flag: %d \n", flag);
           break;
       }

   }
   printf("end of loop \n");//this is not getting printed
   fclose(isa_file);
   if (line)
       free(line);
   return flag;
}

Now, when I call the function with one of the valid opcodes,the function prints the final flag(=1) and then goes into segmentation fault. It doesnt even print end of loop statement. Could someone tell me what is the problem? I tried executing parts of this function in parts as separate files and it seems to work perfectly.

UPDATE:
The end of loop statement now gets printed on the screen when I commented out the toLower code.However,even then code then throws a seg fault. Interestingly, it throws an error only when the final flag is set to 1. Else, it works fine! I am unable to understand this strange issue!

Body:
After your comment I can say:

strlen already gives you the length of read chars -1, 'cause the nul-terminator is not counted. Moreover you cannot use strcpy to do what you need to do, 'cause it will copy all chars of source string into a smaller string causing UB.

What you can do is to remove the '\n' in the source string and then copy it, like:

// overwrite \n with nul-terminator
line[strcspn(line, "\n")] = 0;
// allocate new string less by one
char final[strlen(line)+1];
// allocate new string less by one
strcpy(final,line);


来源: stackexchange

问:
How to use nchar with like operator in SQL Server
I am trying to use like operator with nchar(1) type column, below is my stored procedure:

```<code>Create procedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType like '%'+@DiscountType+'%'
set nocount off
end
</code>```

I have 2 records in table tblCoupons, but I call proc CouponSearch '' it return 0 records. TIA.

I have also tried below line but not working as well.

```<code> Select Couponcode from tblCoupons where DiscountType like N'%'+@DiscountType+'%'
</code>```

答:
IIF() function if you’re using SQL Server 2012:

```<code>Select Couponcode from tblCoupons where DiscountType = IIF(ISNULL(@DiscountType,'') = '', DiscountType, @DiscountType)
</code>```

You can make use of a CASE statement for the lower versions

```<code>Select Couponcode from tblCoupons where DiscountType = CASE WHEN ISNULL(@DiscountType,'') = '' THEN DiscountType ELSE @DiscountType END
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use like operator with nchar(1) type column, below is my stored procedure:

Create procedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType like '%'+@DiscountType+'%'
set nocount off
end

I have 2 records in table tblCoupons, but I call proc CouponSearch '' it return 0 records. TIA.

I have also tried below line but not working as well.

 Select Couponcode from tblCoupons where DiscountType like N'%'+@DiscountType+'%'

Body:
IIF() function if you’re using SQL Server 2012:

Select Couponcode from tblCoupons where DiscountType = IIF(ISNULL(@DiscountType,'') = '', DiscountType, @DiscountType)

You can make use of a CASE statement for the lower versions

Select Couponcode from tblCoupons where DiscountType = CASE WHEN ISNULL(@DiscountType,'') = '' THEN DiscountType ELSE @DiscountType END


问:
Test scrapy spider still working - find page changes

How can I test a scrapy spider against online data.

I now from this post that it is possible to test a spider against offline data.

My target is to check if my spider still extracts the right data from a page, or if the page changed. I extract the data via XPath and sometimes the page receives and update and my scraper is no longer working. I would love to have the test as close to my code as possible, eg. using the spider and scrapy setup and just hook into the parse method.

答:
Referring to the link you provided, you could try this method for online testing which I used for my problem which was similar to yours. All you have to do is instead of reading the requests from a file you can use the Requests library to fetch the live webpage for you and compose a scrapy response from the response you get from Requests like below</p>

```<code>import os
import requests

from scrapy.http import Response, Request

def online_response_from_url (url=None):

    if not url:
        url = 'http://www.example.com'

    request = Request(url=url)

    oresp = requests.get(url)

    response = TextResponse(url=url, request=request,
    body=oresp.text, encoding = 'utf-8')

    return response
</code>```

Body:
Referring to the link you provided, you could try this method for online testing which I used for my problem which was similar to yours. All you have to do is instead of reading the requests from a file you can use the Requests library to fetch the live webpage for you and compose a scrapy response from the response you get from Requests like below

import os
import requests

from scrapy.http import Response, Request

def online_response_from_url (url=None):

    if not url:
        url = 'http://www.example.com'

    request = Request(url=url)

    oresp = requests.get(url)

    response = TextResponse(url=url, request=request,
    body=oresp.text, encoding = 'utf-8')

    return response


问:
How to automatically identify hypernyms from a group of words?
I have several groups of words, for example
in group A: apple, pear, banana, fruit, grape, watermelon;
in group B: cat, animal, dog, pig, monkey, duck;
in group C: Italy, Australia, country, China, Greece.

How can I automatically identify the hypernyms from these 3 groups (e.g., fruit for group A, animal for group B and country for group C)? Thank you very much.

答:
You can use WordNet which is built into nltk. For more information check out this question here: Determining Hypernym or Hyponym using wordnet nltk

It's important to understand however that identification of hypernyms will only be as good as the training data allows. There is no magical system for identifying groupings of similar objects other than to train using tagged data.


问:
Changing activity indicator color to black
I'm trying to change my activity indicator to a custom color like black. However it does not seem to apply at all and has the standard white color still.

What i've done is creating a UIView and and added a activity indicator as a subView and then added this to the tableFooterView.

How can I change the activity indicator color?

ViewDidLoad:

```<code>    let footerView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 40))
    footerView.backgroundColor = UIColor(rgba: "#f6f7f9")
    var actInd: UIActivityIndicatorView = UIActivityIndicatorView()
    actInd.color = UIColor.blackColor()
    actInd.frame = CGRectMake(self.view.frame.size.width/2-10, 0.0, 20.0, 20.0);

    actInd.activityIndicatorViewStyle =
        UIActivityIndicatorViewStyle.WhiteLarge
    footerView.addSubview(actInd)
    actInd.startAnimating()
    self.tableVIew.tableFooterView = footerView
</code>```

答:
Swift 3 version

In main class ViewController add activityIndicator:

```<code>class ViewController: UIViewController, WKNavigationDelegate {

let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
</code>```

Then in viewDidLoad():

```<code>override func viewDidLoad() {
super.viewDidLoad()

activityIndicator.color = UIColor.black
activityIndicator.center = CGPoint(x: view.bounds.size.width/2, y: view.bounds.size.height/2)
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
</code>```

To remove activityIndicator:

```<code>activityIndicator.stopAnimating()
</code>```

Body:
I'm trying to change my activity indicator to a custom color like black. However it does not seem to apply at all and has the standard white color still.

What i've done is creating a UIView and and added a activity indicator as a subView and then added this to the tableFooterView.

How can I change the activity indicator color?

ViewDidLoad:

    let footerView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 40))
    footerView.backgroundColor = UIColor(rgba: "#f6f7f9")
    var actInd: UIActivityIndicatorView = UIActivityIndicatorView()
    actInd.color = UIColor.blackColor()
    actInd.frame = CGRectMake(self.view.frame.size.width/2-10, 0.0, 20.0, 20.0);

    actInd.activityIndicatorViewStyle =
        UIActivityIndicatorViewStyle.WhiteLarge
    footerView.addSubview(actInd)
    actInd.startAnimating()
    self.tableVIew.tableFooterView = footerView

Body:
Swift 3 version

In main class ViewController add activityIndicator:

class ViewController: UIViewController, WKNavigationDelegate {

let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)

Then in viewDidLoad():

override func viewDidLoad() {
super.viewDidLoad()

activityIndicator.color = UIColor.black
activityIndicator.center = CGPoint(x: view.bounds.size.width/2, y: view.bounds.size.height/2)
view.addSubview(activityIndicator)
activityIndicator.startAnimating()

To remove activityIndicator:

activityIndicator.stopAnimating()


问:
Issue assigning form fields in the HTML template django
I have a model form and I wanted to know if it is possible to take a model form and assign the name of the specific field when it is running through a for loop within the template html file.

Here is what i have in the current html template:

```<code>{% extends "base.html" %}

{% block content %}
  <h1>Add members to {{record.name}}</h1>
  {% if message %}
    <p>{{message}}</p>
  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {% for trans in transactions %}
      {% if trans.record.id == record.id %}
        {{ trans.user.username }}
        {{ form.as_p }}
      {% endif %}
    {% endfor %}
    <p>Tax: <input type="text" name="tax" value=""></p>
    <p>Tip: <input type="text" name="tip" value=""></p>
    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}
</code>```

here is the current form model:

```<code>class IndividualSplitTransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = ['amount', 'description']
</code>```

currently the format is looking like this:

```<code>omar
amount
description
hani
amount
description
assad
amount
description
tax
tip
</code>```

so when i process it and i want to grab the amount assigned to each of the specific users and update a record. I want it to look something like this for easier processing in the view.

```<code>omar
omaramount
omardescription
hani
haniamount
hanidescription
assad
assadamount
assaddescription
tax
tip
</code>```

so that when i am processing I can properly assign the corrent amount and description for each user when i am updating existing records with the amount.

is it possible to do that within the template itself or would i have to do it somewhere else.

UPDATED

So i tried to change my code and update it to get what i am trying to get but this is what i am getting...

Here is the html

```<code> {% extends "base.html" %}

{% block content %}
  <h1>Add members to {{record.name}}</h1>
  {% if message %}
    <p>{{message}}</p>
  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {% for trans in transactions %}
      {% if trans.record.id == record.id %}
        {% for field in form %}
          <div class="fieldWrapper">
            {{ field.errors }}
            {{ trans.user.username }}{{ field.label }}{{ field|safe }}
          </div>
        {% endfor %}
      {% endif %}
    {% endfor %}
    <p>Tax: <input type="text" name="tax" value=""></p>
    <p>Tip: <input type="text" name="tip" value=""></p>
    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}
</code>```

and here is what I am getting.

request returs

So if you look at the image, it is still just returning the last amount and description of the three that i entered... should i just create the whole form manually in the html file....

答:
If you wanted the username + amount or username + description, then you to change away from form.as_p, because you will get the html

 tag for each field with label preceding it.

You want to dynamically add username then do by designing your own html content of the form manually.

There is a label_suffix, but prefix is not available. Even with suffix you should be doing it at the time of creating the form object.

Update:

```<code>{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ trans.user.username }} {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}
</code>```

Body:
I have a model form and I wanted to know if it is possible to take a model form and assign the name of the specific field when it is running through a for loop within the template html file.

Here is what i have in the current html template:

{% extends "base.html" %}

{% block content %}

Add members to {{record.name}}

  {% if message %}

{{message}}

  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {% for trans in transactions %}
      {% if trans.record.id == record.id %}
        {{ trans.user.username }}
        {{ form.as_p }}
      {% endif %}
    {% endfor %}

Tax: <input type="text" name="tax" value="">

Tip: <input type="text" name="tip" value="">

    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}

here is the current form model:

class IndividualSplitTransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = ['amount', 'description']

currently the format is looking like this:

omar
amount
description
hani
amount
description
assad
amount
description
tax
tip

so when i process it and i want to grab the amount assigned to each of the specific users and update a record. I want it to look something like this for easier processing in the view.

omar
omaramount
omardescription
hani
haniamount
hanidescription
assad
assadamount
assaddescription
tax
tip

so that when i am processing I can properly assign the corrent amount and description for each user when i am updating existing records with the amount.

is it possible to do that within the template itself or would i have to do it somewhere else.

UPDATED

So i tried to change my code and update it to get what i am trying to get but this is what i am getting...

Here is the html

 {% extends "base.html" %}

{% block content %}

Add members to {{record.name}}

  {% if message %}

{{message}}

  {% endif %}
  <form action="." method="POST">
    {% csrf_token %}
    {% for trans in transactions %}
      {% if trans.record.id == record.id %}
        {% for field in form %}

            {{ field.errors }}
            {{ trans.user.username }}{{ field.label }}{{ field|safe }}

        {% endfor %}
      {% endif %}
    {% endfor %}

Tax: <input type="text" name="tax" value="">

Tip: <input type="text" name="tip" value="">

    <input type="submit" name="submit" value="submit">
  </form>
{% endblock %}

and here is what I am getting.

request returs

So if you look at the image, it is still just returning the last amount and description of the three that i entered... should i just create the whole form manually in the html file....

Body:
If you wanted the username + amount or username + description, then you to change away from form.as_p, because you will get the html <p><p/> tag for each field with label preceding it.

You want to dynamically add username then do by designing your own html content of the form manually.

There is a label_suffix, but prefix is not available. Even with suffix you should be doing it at the time of creating the form object.

Update:

{% for field in form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ trans.user.username }} {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}


问:
How to process multiple files separately after SparkContext.wholeTextFiles?
I'm trying to use wholeTextFiles to read all the files names in a folder and process them one-by-one seperately(For example, I'm trying to get the SVD vector of each data set and there are 100 sets in total). The data are saved in .txt files spitted by space and arranged in different lines(like a matrix).

The problem I came across with is that after I use "wholeTextFiles("path with all the text files")", It's really difficult to read and parse the data and I just can't use the method like what I used when reading only one file. The method works fine when I just read one file and it gives me the correct output. Could someone please let me know how to fix it here? Thanks!

```<code>public static void main (String[] args) {
    SparkConf sparkConf = new SparkConf().setAppName("whole text files").setMaster("local[2]").set("spark.executor.memory","1g");;
    JavaSparkContext jsc = new JavaSparkContext(sparkConf);
    JavaPairRDD<String, String> fileNameContentsRDD = jsc.wholeTextFiles("/Users/peng/FMRITest/regionOutput/");

    JavaRDD<String[]> lineCounts = fileNameContentsRDD.map(new Function<Tuple2<String, String>, String[]>() {
        @Override
        public String[] call(Tuple2<String, String> fileNameContent) throws Exception {
                String content = fileNameContent._2();
                String[] sarray = content .split(" ");
                double[] values = new double[sarray.length];
                for (int i = 0; i< sarray.length; i++){
                    values[i] = Double.parseDouble(sarray[i]);
                }

            pd.cache();
            RowMatrix mat = new RowMatrix(pd.rdd());

            SingularValueDecomposition<RowMatrix, Matrix> svd = mat.computeSVD(84, true, 1.0E-9d);
            Vector s = svd.s();
    }});
</code>```

答:
Quoting the scaladoc of SparkContext.wholeTextFiles:

wholeTextFiles(path: String, minPartitions: Int = defaultMinPartitions): RDD[(String, String)] Read a directory of text files from HDFS, a local file system (available on all nodes), or any Hadoop-supported file system URI. Each file is read as a single record and returned in a key-value pair, where the key is the path of each file, the value is the content of each file.

In other words, wholeTextFiles might not simply be what you want.

Since by design "Small files are preferred" (see the scaladoc), you could mapPartitions or collect (with filter) to grab a subset of the files to apply the parsing to.

Once you have the files per partitions in your hands, you could use Scala's Parallel Collection API and schedule Spark jobs to execute in parallel:

Inside a given Spark application (SparkContext instance), multiple parallel jobs can run simultaneously if they were submitted from separate threads. By “job”, in this section, we mean a Spark action (e.g. save, collect) and any tasks that need to run to evaluate that action. Spark’s scheduler is fully thread-safe and supports this use case to enable applications that serve multiple requests (e.g. queries for multiple users).

By default, Spark’s scheduler runs jobs in FIFO fashion. Each job is divided into “stages” (e.g. map and reduce phases), and the first job gets priority on all available resources while its stages have tasks to launch, then the second job gets priority, etc. If the jobs at the head of the queue don’t need to use the whole cluster, later jobs can start to run right away, but if the jobs at the head of the queue are large, then later jobs may be delayed significantly.

Body:
I'm trying to use wholeTextFiles to read all the files names in a folder and process them one-by-one seperately(For example, I'm trying to get the SVD vector of each data set and there are 100 sets in total). The data are saved in .txt files spitted by space and arranged in different lines(like a matrix).

The problem I came across with is that after I use "wholeTextFiles("path with all the text files")", It's really difficult to read and parse the data and I just can't use the method like what I used when reading only one file. The method works fine when I just read one file and it gives me the correct output. Could someone please let me know how to fix it here? Thanks!

public static void main (String[] args) {
    SparkConf sparkConf = new SparkConf().setAppName("whole text files").setMaster("local[2]").set("spark.executor.memory","1g");;
    JavaSparkContext jsc = new JavaSparkContext(sparkConf);
    JavaPairRDD<String, String> fileNameContentsRDD = jsc.wholeTextFiles("/Users/peng/FMRITest/regionOutput/");

    JavaRDD<String[]> lineCounts = fileNameContentsRDD.map(new Function<Tuple2<String, String>, String[]>() {
        @Override
        public String[] call(Tuple2<String, String> fileNameContent) throws Exception {
                String content = fileNameContent._2();
                String[] sarray = content .split(" ");
                double[] values = new double[sarray.length];
                for (int i = 0; i< sarray.length; i++){
                    values[i] = Double.parseDouble(sarray[i]);
                }

            pd.cache();
            RowMatrix mat = new RowMatrix(pd.rdd());

            SingularValueDecomposition<RowMatrix, Matrix> svd = mat.computeSVD(84, true, 1.0E-9d);
            Vector s = svd.s();
    }});


答:
You can try this too:</p>

```<code>DECLARE @DiscountType nchar(1)

SELECT COUPONCODE
FROM TBLCOUPONS
WHERE CASE WHEN COALESCE(@DISCOUNTTYPE,'')='' THEN 1 ELSE 0 END=1  OR DISCOUNTTYPE = @DISCOUNTTYPE
</code>```

Title: How to use nchar with like operator in SQL Server

Body:
You can try this too:

DECLARE @DiscountType nchar(1)

SELECT COUPONCODE
FROM TBLCOUPONS
WHERE CASE WHEN COALESCE(@DISCOUNTTYPE,'')='' THEN 1 ELSE 0 END=1  OR DISCOUNTTYPE = @DISCOUNTTYPE


问:
C++ script behaving badly when using "string" data type
I just want to write a simple script that asks for someone's name and prints it out. But for some reason, when I use the string data type it just kind of, does nothing.

Here is the code and output if I use a string:

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

using namespace std;

int main()
{
    string name;

    cout << "Please give me your name: ";
    getline(cin, name);
    cout << "Hello " << name << endl;
    return 0;
}
</code>```

As you can see, it just runs the .exe and nothing happens. However if I take the C approach to strings and use a character array and also don't use getline(), it works fine (but doesn't skip the '\0' character):

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

using namespace std;

int main()
{
    //string name;
    char name[15];

    cout << "Please give me your name: ";
    //getline(cin, name);
    cin >> name;
    cout << "Hello " << name << endl;
    return 0;
}
</code>```

I have tried a few other approaches and all have worked fine. For some reason, making the variable name as a string data type makes it behave weirdly. I tried looking around some C++ based books and the web but no one seems to have
 had this problem.

I'm just going to add this for clarification, I checked to see if the program was just executing too fast for me to see what was going on. It is not doing that, it even skips the part where it is supposed to wait for input.

I am using Visual Studio Code to write the programs and MinGW to compile. I took my code and ran it over at https://www.onlinegdb.com/ and it worked as expected:

Could this possibly be a Windows or Command Prompt problem?

答:
Depending on STL implementation and OS, std::cout may be buffering data in memory. It typically does not flush buffered data to console until either:

a threshold is reached

a '\n' character is output

std::cout.flush() is called (which includes outputting std::endl, which calls flush() after writing a line break).

Try calling std::cout.flush() (directly, or via std::flush) after outputting the prompt and before reading the name:

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

using namespace std;

int main() {
    string name;
    cout << "Please give me your name: " << flush;
    getline(cin, name);
    cout << "Hello " << name << endl;
    return 0;
}
</code>```

Body:
I just want to write a simple script that asks for someone's name and prints it out. But for some reason, when I use the string data type it just kind of, does nothing.

Here is the code and output if I use a string:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;

    cout << "Please give me your name: ";
    getline(cin, name);
    cout << "Hello " << name << endl;
    return 0;
}

As you can see, it just runs the .exe and nothing happens. However if I take the C approach to strings and use a character array and also don't use getline(), it works fine (but doesn't skip the '\0' character):

#include <iostream>
#include <string>

using namespace std;

int main()
{
    //string name;
    char name[15];

    cout << "Please give me your name: ";
    //getline(cin, name);
    cin >> name;
    cout << "Hello " << name << endl;
    return 0;
}

I have tried a few other approaches and all have worked fine. For some reason, making the variable name as a string data type makes it behave weirdly. I tried looking around some C++ based books and the web but no one seems to have
 had this problem.

I'm just going to add this for clarification, I checked to see if the program was just executing too fast for me to see what was going on. It is not doing that, it even skips the part where it is supposed to wait for input.

I am using Visual Studio Code to write the programs and MinGW to compile. I took my code and ran it over at https://www.onlinegdb.com/ and it worked as expected:

Could this possibly be a Windows or Command Prompt problem?

Body:
Depending on STL implementation and OS, std::cout may be buffering data in memory. It typically does not flush buffered data to console until either:

a threshold is reached

a '\n' character is output

std::cout.flush() is called (which includes outputting std::endl, which calls flush() after writing a line break).

Try calling std::cout.flush() (directly, or via std::flush) after outputting the prompt and before reading the name:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string name;
    cout << "Please give me your name: " << flush;
    getline(cin, name);
    cout << "Hello " << name << endl;
    return 0;
}


问:
not able to create controller by referencing to javascript file having module declared in it
I created angular module in a javascript file app.js as below:

var app = angular.module('myApp', []);

Further i went to the controller folder of my project and added a javascript file for Controllers.
Next i referenced the already created app.js file(which is havning module creation) in the first step and then i tried to create controller using it as in below lines:

```<code>/// <reference path="app.js" />
app.controller('myctrl', function ($scope) {
$scope.tesdtata = 'test';
})
</code>```

Now when i am binding the scope variable to UI and running the solution, i am getting exceptions as:  'app' not defined

Finally i am not able to vied the value of 'testdata' in browser.

Moreover when i type the line: app.controller(..)  the intellisence shows me some diffenet overload variables i.e. app.controller(recepiename,factoryfunction)   which is not correct.

Everything works fine if i create module individualy for every controller file and then using that create controller in same file. And problem occurs when i try to reference the single app.js file (having module creation it) and try to create controllers.

答:
It is discouraged to use global variables in javascript nowadays.

Instead of doing this

```<code>// app.js
var app = angular.module('myApp, []');

// controller.js
app.controller...
</code>```

Do this

```<code>// app.js
var app = angular.module('myApp, []');

// controller.js
angular.module('myApp').controller...
</code>```

Reference not needed and intellisense won't complain too.l

Body:
I created angular module in a javascript file app.js as below:

var app = angular.module('myApp', []);

Further i went to the controller folder of my project and added a javascript file for Controllers.
Next i referenced the already created app.js file(which is havning module creation) in the first step and then i tried to create controller using it as in below lines:

/// <reference path="app.js" />
app.controller('myctrl', function ($scope) {
$scope.tesdtata = 'test';
})

Now when i am binding the scope variable to UI and running the solution, i am getting exceptions as:  'app' not defined

Finally i am not able to vied the value of 'testdata' in browser.

Moreover when i type the line: app.controller(..)  the intellisence shows me some diffenet overload variables i.e. app.controller(recepiename,factoryfunction)   which is not correct.

Everything works fine if i create module individualy for every controller file and then using that create controller in same file. And problem occurs when i try to reference the single app.js file (having module creation it) and try to create controllers.

Body:
It is discouraged to use global variables in javascript nowadays.

Instead of doing this

// app.js
var app = angular.module('myApp, []');

// controller.js
app.controller...

Do this

// app.js
var app = angular.module('myApp, []');

// controller.js
angular.module('myApp').controller...

Reference not needed and intellisense won't complain too.l


问:
Eclipse Maven project structure
I am fairly new to maven. In Eclipse, I created a maven project
Inside this I can see src/main/java and src/test/java also there is one more src folder which again contains main and test folder. Here I am confused in which src folder I need to write the code. What is the main benefit of using main and test folder? Why there are two main and two src folder

答: the bottom src folder us where the unit tests should be. Don't worry if you dont know what that means. In the top folder is where the java code should be located.</p>

Title: Eclipse Maven project structure


问:
how to use a onkeyup function in javaScript to get the value using ajax with spring
How to use the on key up event with timeout option. The values typed should return the data that matched in the data base

here my Jquery code is

```<code>function searchUserId() {
  var userId = $('#userId').val();
  //var moduleID = $('#moduleIdList').val();

  $.ajax({
    url: "controlpanel/SearchUserData",
    type: "POST",
    data: "userId=" + userId,
      //+ "&roleName=" + roleName,
      //For Progress Bar
    success: function(response) {
      alert(userId);
      $('#page-wrapper').html(response);
    }
  });
}
</code>```

<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
   onkeyup="searchUserId();"data-validation-engine="validate[required]"/>
```

答:
You can do like this

HTML

```<code><input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
   "data-validation-engine="validate[required]"/>
</code>```

Jauery

```<code>$('#userId').on('keyup',function () {
    var userId = $(thi).val();
    //var moduleID = $('#moduleIdList').val();

    $.ajax({
        url: "controlpanel/SearchUserData",
        type: "POST",
        data: "userId=" + userId,
        //+ "&roleName=" + roleName,
        //For Progress Bar
        success: function(response) {
            alert(userId);
            $('#page-wrapper').html(response);
        }
    });
});
</code>```

Body:
How to use the on key up event with timeout option. The values typed should return the data that matched in the data base

here my Jquery code is

function searchUserId() {
  var userId = $('#userId').val();
  //var moduleID = $('#moduleIdList').val();

  $.ajax({
    url: "controlpanel/SearchUserData",
    type: "POST",
    data: "userId=" + userId,
      //+ "&roleName=" + roleName,
      //For Progress Bar
    success: function(response) {
      alert(userId);
      $('#page-wrapper').html(response);
    }
  });
}

<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
   onkeyup="searchUserId();"data-validation-engine="validate[required]"/>

Body:
You can do like this

HTML

<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
   "data-validation-engine="validate[required]"/>

Jauery

$('#userId').on('keyup',function () {
    var userId = $(thi).val();
    //var moduleID = $('#moduleIdList').val();

    $.ajax({
        url: "controlpanel/SearchUserData",
        type: "POST",
        data: "userId=" + userId,
        //+ "&roleName=" + roleName,
        //For Progress Bar
        success: function(response) {
            alert(userId);
            $('#page-wrapper').html(response);
        }
    });
});


问:
Match substring in string divided by a dot
I have following strings:

```<code>'sample1.sample2'
'sample1.sample2.samaple3'
</code>```

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

```<code>$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);
</code>```

works fine only for first case.

答: why don't you split string using preg_split. You can refer here

Body:
I have following strings:

'sample1.sample2'
'sample1.sample2.samaple3'

on so on..

I want to separate values sample1, sample2 and sample3 from this string (please note the quotation mark is there).

My code:

$matches = [];
$regex = "'(.*?)\.(.*?)'";
$string = "'dużotekstu.tekstpokropce'";
$match = preg_match(sprintf("/^%s$/", $regex), $string, $matches);

works fine only for first case.


问:
IIS7 Application Configuration
I have a custom ASP.NET application that I utilize for several clients that I host.  Each client has a separate domain and the application is normally a child application under the root domain (http://domain.com/customapp).  The application files are the same (aspx, ascx, style sheets, images, etc.).  The only thing different is the web.config file for each client.  As development of the application continues to evolve, I have to update the application for each directory and this obviously becoming tedious.  I am trying to come up with a method keep the application up to date.  My first though is placing the application into a single physical path and creating multiple applications pointing to that path (the problem with this method is I can't have different web.config files).  I am curious as to what solution others are using in this scenario...</p>

答:
Can you just move your web.config content to a database and load it conditionally based on the domain that was referenced?

```<code>    Select Case Request.Url.Host.ToLowerInvariant()
        Case "xyz.com", "www.xyz.com"
            'Load XYZ stuff'
        Case "abc.com", "www.abc.com"
            'Load ABC stuff'
        Case Else
            'Throw an error probably'
    End Select
</code>```

Even better, store your domains in the database as keys so that you don't ever have to touch the code.

ContentLicense: CC BY-SA 2.5

Title: IIS7 Application Configuration

Body:
Can you just move your web.config content to a database and load it conditionally based on the domain that was referenced?

    Select Case Request.Url.Host.ToLowerInvariant()
        Case "xyz.com", "www.xyz.com"
            'Load XYZ stuff'
        Case "abc.com", "www.abc.com"
            'Load ABC stuff'
        Case Else
            'Throw an error probably'
    End Select

Even better, store your domains in the database as keys so that you don't ever have to touch the code.


问:
Why PyImport_ImportModule returns a PyObject* with a refcount of 3 instead of 1
I'm working with Python C API in my C++ program and I've noticed an odd thing.

While running a simple program like this in my debugger on my PC:

```<code>int main(int argc, const char * argv[]) {

    Py_Initialize();
    PyObject* scipy_stats_module = PyImport_ImportModule("scipy.stats"); // importing "scipy.stats" module

    Py_DecRef(scipy_stats_module);

    if (Py_FinalizeEx() < 0) {
        PyErr_Print();
        exit(-1);
    }

    return 0;

}
</code>```

I've seen that the ob_refcnt attribute of scipy_stats_module, right after its creation and before calling Py_DecRef, is set at 3 while I was expecting it to be equal to 1.

Can somebody help me understand why is this happening? Is this a problem with my code or is it normal? Should I call Py_DecRef three times or just once?

Thank you!

P.S. I'm using Xcode 8.3.3 as IDE and debugger on my PC with macOS 10.12.5

答:
You don't own the only reference to the new module. While in this case, it's simple to identify the other references - one is sys.modules['scipy.stats'], and one is the stats attribute of the scipy module object - in general, it's not your concern what other references a module might have.

When you clear your reference to the module, you should only Py_DECREF once, because you're only clearing one reference, the one you own. The other references still exist and still need to be accounted for in the refcount.

Body:
I'm working with Python C API in my C++ program and I've noticed an odd thing.

While running a simple program like this in my debugger on my PC:

int main(int argc, const char * argv[]) {

    Py_Initialize();
    PyObject* scipy_stats_module = PyImport_ImportModule("scipy.stats"); // importing "scipy.stats" module

    Py_DecRef(scipy_stats_module);

    if (Py_FinalizeEx() < 0) {
        PyErr_Print();
        exit(-1);
    }

    return 0;

}

I've seen that the ob_refcnt attribute of scipy_stats_module, right after its creation and before calling Py_DecRef, is set at 3 while I was expecting it to be equal to 1.

Can somebody help me understand why is this happening? Is this a problem with my code or is it normal? Should I call Py_DecRef three times or just once?

Thank you!

P.S. I'm using Xcode 8.3.3 as IDE and debugger on my PC with macOS 10.12.5


问:
How to use the same name classes but in separate styles
see the example to understand:

```<code>    <!--Standard Bootstrap -->
    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <!-- Material Design Bootstrap -->
    <link href="/build/css/site/mdb.min.css" rel="stylesheet">
</code>```

so i want a thing like it:

```<code>    <div class="btn btn-danger" >Standard Bootstrap Button</div>
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</code>```

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

答:
.btn-danger{
  background-color:red;
  width:90px;
  height:90px;
}

.m1 .btn-danger{
  background-color:green;
  width:90px;
  height:90px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="btn btn-danger" >Standard Bootstrap Button</div>
  <div class="m1">
    <div class="btn btn-danger" >Material Design Bootstrap Button</div></div></code>```

i think one way is like this, hope this may solve your problem

ContentLicense: CC BY-SA 4.0

Body:
see the example to understand:

    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <link href="/build/css/site/mdb.min.css" rel="stylesheet">

so i want a thing like it:

Standard Bootstrap Button

Material Design Bootstrap Button

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

Body:
.btn-danger{
  background-color:red;
  width:90px;
  height:90px;
}

.m1 .btn-danger{
  background-color:green;
  width:90px;
  height:90px;

}

 <div class="btn btn-danger" >Standard Bootstrap Button</div>
  <div class="m1">
    <div class="btn btn-danger" >Material Design Bootstrap Button</div></div>

i think one way is like this, hope this may solve your problem


问:
Azure Service Fabric logging with log4net into AppInsights
I have a website as 'App Service' in Azure and 'Service Fabric' with a number of services for background tasks. For logging I want to use log4net and for analyzing AppInsights. Like:

WebSite        --> log4net --> AppInsights appender --> AppInsights

Service Fabric --> log4net --> AppInsights appender --> AppInsights

The question is: what is the correct way to implement described logging flow, the idea is to log with log4net and analyze with AppInsights. And can I distinguish logs in AppInsights from website and service fabric.

答:
The question is: what is the correct way to implement described logging flow, the idea is to log with log4net and analyze with AppInsights.

Per my understanding, you could follow the steps below for logging with log4net into application insights:

Add Application insights to your project,for more details, you could refer to Set up Application Insights for your ASP.NET website.

Install the Application Insights Log4Net Appender.

For add diagnostic log via log4Net:

```<code>logger.Info("Hello world!!!");
</code>```

Here I created my asp.net MVC application, configured the application insights and installed the related package, then added the following configuration under the Application_Start method from the Global.asax.cs file as follows:

```<code>log4net.Config.XmlConfigurator.Configure();
</code>```

Then, I deployed my web application to my two azure web apps, then I could search the log as follows:

And can I distinguish logs in AppInsights from website and service fabric.

You could leverage Analytics in Application Insights and write your query to distinguish the logs from different services based on your filters as follows:

Additionally, I would prefer creating a new application insights for each of my azure web apps, since there has 1GB(s) per month for free and it would be simple for me to manage my diagnostic logging.

Body:
The question is: what is the correct way to implement described logging flow, the idea is to log with log4net and analyze with AppInsights.

Per my understanding, you could follow the steps below for logging with log4net into application insights:

Add Application insights to your project,for more details, you could refer to Set up Application Insights for your ASP.NET website.

Install the Application Insights Log4Net Appender.

For add diagnostic log via log4Net:

logger.Info("Hello world!!!");

Here I created my asp.net MVC application, configured the application insights and installed the related package, then added the following configuration under the Application_Start method from the Global.asax.cs file as follows:

log4net.Config.XmlConfigurator.Configure();

Then, I deployed my web application to my two azure web apps, then I could search the log as follows:

And can I distinguish logs in AppInsights from website and service fabric.

You could leverage Analytics in Application Insights and write your query to distinguish the logs from different services based on your filters as follows:

Additionally, I would prefer creating a new application insights for each of my azure web apps, since there has 1GB(s) per month for free and it would be simple for me to manage my diagnostic logging.


问:
List.remove() is behaving differently for negative values
I have a requirement in our code, where we need to catch ArrayIndexOutOfBoundsException and move forward with other elements.

However, when i try to do that i am getting ConcurrentModificationException

Following code is something that i want but it is throwing ConcurrentModificationException exception at line #1

Note that list.remove(1000) is not causing any issue  but list.remove(-1) does

```<code>public class Test1 {
        public static void main(String[] argv) {
            test(new ArrayList<>());
        }

        public static void test(List<Integer> list) {
            list.add(42);
            Iterator<Integer> it = list.iterator();

            try {
                list.remove(-1);
            } catch (Exception e) {
                System.out.println(e);
            }

            try {
                if (it.next() != 42);//Line #1
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
</code>```

Can some one help me understand this behavior and how can I fix this problem ?

答:
Because you are already getting an iterator from list and meanwhile removing items from the list directly hence the iterator cried.

Once you got to declare the iterator use only iterator to do the modifications.

So in the first try block remove using/ through iterator and not on list directly. Find the element and remove from iterator.

```<code>it.remove();
</code>```

Body:
I have a requirement in our code, where we need to catch ArrayIndexOutOfBoundsException and move forward with other elements.

However, when i try to do that i am getting ConcurrentModificationException

Following code is something that i want but it is throwing ConcurrentModificationException exception at line #1

Note that list.remove(1000) is not causing any issue  but list.remove(-1) does

public class Test1 {
        public static void main(String[] argv) {
            test(new ArrayList<>());
        }

        public static void test(List<Integer> list) {
            list.add(42);
            Iterator<Integer> it = list.iterator();

            try {
                list.remove(-1);
            } catch (Exception e) {
                System.out.println(e);
            }

            try {
                if (it.next() != 42);//Line #1
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

Can some one help me understand this behavior and how can I fix this problem ?

Body:
Because you are already getting an iterator from list and meanwhile removing items from the list directly hence the iterator cried.

Once you got to declare the iterator use only iterator to do the modifications.

So in the first try block remove using/ through iterator and not on list directly. Find the element and remove from iterator.

it.remove();


问:
How to fix "Missing required dependencies ['numpy']" error?
Hello how can i get past this error, I'v tried uninstalling and reinstalling pandas and Quandl but it still comes up with the same error? </p>

```<code>RESTART: C:/Users/Reece92/AppData/Local/Programs/Python/Python36/Machine learning sentdex IDLE.py
Traceback (most recent call last):

File "C:/Users/Reece92/AppData/Local/Programs/Python/Python36/Machine learning sentdex IDLE.py", line 1, in <module>
    import pandas as pd
File "C:\Users\Reece92\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\__init__.py", line 19, in <module>
    "Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']
</code>```

答:
In the python world, you have something called packages. You can use it to extend python with libraries and stuff. By default none of these "extra" packages are a installed, you have to use a command called pip to install all the requirements your application need.

In your case :

```<code>pip install numpy
</code>```

Body:
Hello how can i get past this error, I'v tried uninstalling and reinstalling pandas and Quandl but it still comes up with the same error?

RESTART: C:/Users/Reece92/AppData/Local/Programs/Python/Python36/Machine learning sentdex IDLE.py
Traceback (most recent call last):

File "C:/Users/Reece92/AppData/Local/Programs/Python/Python36/Machine learning sentdex IDLE.py", line 1, in <module>
    import pandas as pd
File "C:\Users\Reece92\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\__init__.py", line 19, in <module>
    "Missing required dependencies {0}".format(missing_dependencies))
ImportError: Missing required dependencies ['numpy']

Body:
In the python world, you have something called packages. You can use it to extend python with libraries and stuff. By default none of these "extra" packages are a installed, you have to use a command called pip to install all the requirements your application need.

In your case :

pip install numpy


问:
Add protocol to href value
I have added an editor and user can enter anything they want, then I show that entered text under message card, so if user has entered a link like Click here & its HTML part is Click here so when show this under message card and click on click here then its not redirecting to google.com it goes to http://my-website.com/google.com, its because href value don't have any protocol, so how I can add protocol to its value and there could be multiple links in single message, some could have protocol and some not.

答:
It may not be a nice idea to let user to enter HTML code in the editor. But if you insist to do so, you may try

$(function() {
  $('a').each(function() {
    if (!$(this).attr("href").startsWith("http")) {
      $(this).attr("href", "http://" + $(this).attr("href"));
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click here</code>```

Title: Add protocol to href value

Body:
It may not be a nice idea to let user to enter HTML code in the editor. But if you insist to do so, you may try

$(function() {
  $('a').each(function() {
    if (!$(this).attr("href").startsWith("http")) {
      $(this).attr("href", "http://" + $(this).attr("href"));
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="google.com">Click here</a>


问:
Inserting information in the sql lite database not working
The texts that were already stored in the database are displaying without any problem. But new inserted data not showing. I think "Nothing will be displayed by adding new text, as if the insertion action was not performed.". I don't know why it's not working.Please help...

My DatabaseHandler class

```<code> public class databaseHandler extends SQLiteOpenHelper
{

    private Context main_context;
    private static String DB_PATH;
    private static String DB_NAME = "word.sqlite";
    private static String DB_TBL_BOOKS = "word";
    private static String DB_TBL_SETTING = "setting";
    private static final  int DB_version = 1;
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_FIRST_NAME = "title";
    public static final String COLUMN_LAST_NAME = "content";
    private SQLiteDatabase db;

    public databaseHandler(Context con)
    {

        super(con, DB_NAME, null, DB_version);

        main_context = con;
        DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;

    }
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
            copyDB();
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query;
        query = "CREATE TABLE word (id INTEGER PRIMARY KEY  NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
        db.execSQL(query);
        Log.d("log","table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w("tag", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS word");
        onCreate(db);
    }

    private boolean db_exist() {

        File f = new File(DB_PATH);
        if (f.exists())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private boolean copyDB() {
        try {
            FileOutputStream out = new FileOutputStream(DB_PATH);
            InputStream in =main_context.getAssets().open(DB_NAME);
            byte[] buffer = new byte[1024];
            int ch;
            while ((ch = in.read(buffer)) > 0)
            {
                out.write(buffer , 0, ch);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            Log.i("amirmessage", "error in 84 -> " + e.toString());
            return false;
        }
    }

    public void open()
    {
        if (db_exist())
        {
            try {
                File temp = new File(DB_PATH);
                db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null ,  SQLiteDatabase.OPEN_READWRITE);
            }catch (Exception e) {
                Log.i("amirmessage", "error in 100 -> " + e.toString());

            }

        }
        else {
            if (copyDB())
            {
                open();
            }

        }
    }
    @Override
    public synchronized void close() {

        db.close();
    }
    //---------

    public List<HashMap<String , Object>> getresultOfSerach()
    {
        Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
        List<HashMap<String , Object>> all_data = new ArrayList<>();

       try {
           while ( result.moveToNext())
           {
               HashMap<String , Object> temp = new HashMap<>();
               temp.put("id" , result.getString(0));
               temp.put("content" , result.getString(2));

               temp.put("title" , result.getString(1));

               all_data.add(temp);
               Log.d("update","Query: ");

           }
       } finally
        {
            result.close();
        }

        return all_data;
    }

    public void addcontent(String state, String title)
    {

        ContentValues cv  = new ContentValues();
        cv.put("content", state);
        cv.put("title", title);
        db = this.getWritableDatabase();

            db.insert(DB_TBL_BOOKS,null,cv);

        Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    }
 }
</code>```

My Activity insert code is here

```<code>public class addcontent extends AppCompatActivity

  {

    private databaseHandler db;
    public String title1;
    public String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontent);
        db = new databaseHandler(getBaseContext());
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        EditText etcontent = (EditText)findViewById(R.id.editText);
        EditText ettitle1 = (EditText)findViewById(R.id.editText2);

        title1=ettitle1.getText().toString();
        content=etcontent.getText().toString();

    }

      public void onbtnadd(View v)
    {

        db.open();
        db.addcontent( content,title1);

        db.close();

    }
}
</code>```

My MainActivity  code to Show information is here

```<code> public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getBaseContext(),addcontent.class);
            startActivity(i);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    resultListView = (ListView) findViewById(R.id.catListview);
    db = new databaseHandler(getBaseContext());
    showresultOfSerarch();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void onbtnfind()
{
    resultListView.setAdapter(null);

    String serachBy;

    serachBy = "author";

    String query =" ";

    showresultOfSerarch();

}
  public void showresultOfSerarch()
{
    db.open();

    resultsbooks = db.getresultOfSerach();
    db.close();

    String[] from = {"title","content"};
    int[] to = {R.id.txttitle,  R.id.txtcontent};

    SimpleAdapter adp = new SimpleAdapter(
            getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
    );
    resultListView.setAdapter(adp);
 }
</code>```

}

答:
First of all I would like to say, please follow coding guidelines.

You have made no provision to display data inserted in 'word' table.

Your data insertion logic is working fine.
Once your data gets added in 'word' table, try reading values. You can make following changes to read values.

```<code>public void onbtnadd() {
    db.open();
    db.addcontent(content, title1);
    Cursor cursor = db.getReadableDatabase().rawQuery("select * from word", null);
    if (cursor.moveToFirst()) {
        do {
            // get all records inserted in 'word' table here
        } while (cursor.moveToNext());
    }
    db.close();
}
</code>```

Body:
The texts that were already stored in the database are displaying without any problem. But new inserted data not showing. I think "Nothing will be displayed by adding new text, as if the insertion action was not performed.". I don't know why it's not working.Please help...

My DatabaseHandler class

 public class databaseHandler extends SQLiteOpenHelper
{

    private Context main_context;
    private static String DB_PATH;
    private static String DB_NAME = "word.sqlite";
    private static String DB_TBL_BOOKS = "word";
    private static String DB_TBL_SETTING = "setting";
    private static final  int DB_version = 1;
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_FIRST_NAME = "title";
    public static final String COLUMN_LAST_NAME = "content";
    private SQLiteDatabase db;

    public databaseHandler(Context con)
    {

        super(con, DB_NAME, null, DB_version);

        main_context = con;
        DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;

    }
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
            copyDB();
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query;
        query = "CREATE TABLE word (id INTEGER PRIMARY KEY  NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
        db.execSQL(query);
        Log.d("log","table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w("tag", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS word");
        onCreate(db);
    }

    private boolean db_exist() {

        File f = new File(DB_PATH);
        if (f.exists())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private boolean copyDB() {
        try {
            FileOutputStream out = new FileOutputStream(DB_PATH);
            InputStream in =main_context.getAssets().open(DB_NAME);
            byte[] buffer = new byte[1024];
            int ch;
            while ((ch = in.read(buffer)) > 0)
            {
                out.write(buffer , 0, ch);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            Log.i("amirmessage", "error in 84 -> " + e.toString());
            return false;
        }
    }

    public void open()
    {
        if (db_exist())
        {
            try {
                File temp = new File(DB_PATH);
                db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null ,  SQLiteDatabase.OPEN_READWRITE);
            }catch (Exception e) {
                Log.i("amirmessage", "error in 100 -> " + e.toString());

            }

        }
        else {
            if (copyDB())
            {
                open();
            }

        }
    }
    @Override
    public synchronized void close() {

        db.close();
    }
    //---------

    public List<HashMap<String , Object>> getresultOfSerach()
    {
        Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
        List<HashMap<String , Object>> all_data = new ArrayList<>();

       try {
           while ( result.moveToNext())
           {
               HashMap<String , Object> temp = new HashMap<>();
               temp.put("id" , result.getString(0));
               temp.put("content" , result.getString(2));

               temp.put("title" , result.getString(1));

               all_data.add(temp);
               Log.d("update","Query: ");

           }
       } finally
        {
            result.close();
        }

        return all_data;
    }

    public void addcontent(String state, String title)
    {

        ContentValues cv  = new ContentValues();
        cv.put("content", state);
        cv.put("title", title);
        db = this.getWritableDatabase();

            db.insert(DB_TBL_BOOKS,null,cv);

        Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    }
 }

My Activity insert code is here

public class addcontent extends AppCompatActivity

  {

    private databaseHandler db;
    public String title1;
    public String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontent);
        db = new databaseHandler(getBaseContext());
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        EditText etcontent = (EditText)findViewById(R.id.editText);
        EditText ettitle1 = (EditText)findViewById(R.id.editText2);

        title1=ettitle1.getText().toString();
        content=etcontent.getText().toString();

    }

      public void onbtnadd(View v)
    {

        db.open();
        db.addcontent( content,title1);

        db.close();

    }
}

My MainActivity  code to Show information is here

 public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getBaseContext(),addcontent.class);
            startActivity(i);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    resultListView = (ListView) findViewById(R.id.catListview);
    db = new databaseHandler(getBaseContext());
    showresultOfSerarch();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void onbtnfind()
{
    resultListView.setAdapter(null);

    String serachBy;

    serachBy = "author";

    String query =" ";

    showresultOfSerarch();

}
  public void showresultOfSerarch()
{
    db.open();

    resultsbooks = db.getresultOfSerach();
    db.close();

    String[] from = {"title","content"};
    int[] to = {R.id.txttitle,  R.id.txtcontent};

    SimpleAdapter adp = new SimpleAdapter(
            getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
    );
    resultListView.setAdapter(adp);
 }

}

Body:
First of all I would like to say, please follow coding guidelines.

You have made no provision to display data inserted in 'word' table.

Your data insertion logic is working fine.
Once your data gets added in 'word' table, try reading values. You can make following changes to read values.

public void onbtnadd() {
    db.open();
    db.addcontent(content, title1);
    Cursor cursor = db.getReadableDatabase().rawQuery("select * from word", null);
    if (cursor.moveToFirst()) {
        do {
            // get all records inserted in 'word' table here
        } while (cursor.moveToNext());
    }
    db.close();
}


问:
Insert Image and set to circle in canvas
This is my code to insert image to canvas..

```<code><script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
<input type="file" id="file">
        <canvas id="canvas" width="750" height="550"></canvas>
        <a href='' id='txt' target="_blank">Click Me!</a>
        <br />
        <img id="preview" />
</code>```

https://jsfiddle.net/javasalden/yn04k565/

how to complete button:

```<code><button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
</code>```

when I click and image/element will be CIRCLE

答:
Try clipTo function

```<code>img.set({
 clipTo: function (ctx) {
  ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
 }
});
</code>```

Here is updated fiddle, the radius is half of uploaded image

Body:
This is my code to insert image to canvas..

<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>
<input type="file" id="file">
        <canvas id="canvas" width="750" height="550"></canvas>
        Click Me!

https://jsfiddle.net/javasalden/yn04k565/

how to complete button:

<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button>

when I click and image/element will be CIRCLE

Body:
Try clipTo function

img.set({
 clipTo: function (ctx) {
  ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
 }
});

Here is updated fiddle, the radius is half of uploaded image


问:
How to detect that the HTML element has text by clicking on text content area?
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

```<code><div>
some text
<span class="box"></span>
</div>

<div>
some text
</div>

<div><span class="box"></span></div>
</code>```

JS:

```<code>$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('<span>You clicked on a text</span>');
    }

});
</code>```

答:
This is the way you should do. As this selects the body element and any element inside body that has text, will go into the if statement, if you need elese statement as well, you add so after the if. </p>

```<code>$(document).on('click','body', function(e){
   var clickedTag, text;
   clickedtag = e.target;
   text = $(clickedtag).text().trim();
   if(text.length > 0){
     console.log(text);
   }
});
</code>```

Body:
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

some text

some text

JS:

$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('You clicked on a text');
    }

});

Body:
This is the way you should do. As this selects the body element and any element inside body that has text, will go into the if statement, if you need elese statement as well, you add so after the if.

$(document).on('click','body', function(e){
   var clickedTag, text;
   clickedtag = e.target;
   text = $(clickedtag).text().trim();
   if(text.length > 0){
     console.log(text);
   }
});


问:
Error using Pod Install command on Podfile in Terminal
I have installed Cocoapods, and created a Podfile using Atom containing the following lines:

```<code>pod ‘Parse’, ‘~> 1.7.1′
pod ‘ParseUI’, ‘~> 1.1.3′
</code>```

Upon placing this file into my Xcode Project Root Directory, and running 'pod install' in Terminal. The following is shown:

[!] Your Podfile has had smart quotes sanitised. To avoid issues in
  the future, you should not use TextEdit for editing it. If you are not
  using TextEdit, you should turn off smart quotes in your editor of
  choice.

```<code>/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.38.2/lib/cocoapods-core/standard_error.rb:87:in `message': incompatible character encodings: ASCII-8BIT and UTF-8 (Encoding::CompatibilityError)
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.9.1/lib/claide/command.rb:367:in `handle_exception'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.9.1/lib/claide/command.rb:315:in `rescue in run'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.9.1/lib/claide/command.rb:303:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.38.2/lib/cocoapods/command.rb:48:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.38.2/bin/pod:44:in `<top (required)>'
    from /usr/bin/pod:23:in `load'
    from /usr/bin/pod:23:in `<main>'
</code>```

I'm unsure what I have done incorrectly, if anyone could give me some advice - it would be really appreciated. Thank you.

答: Incase someone using Jenkins CI and after correcting the Podfile too error doesnt resolves. Updating your cocoapods version on your slave can help get this error resolved. As jenkins is unable to pinpoint the issue and gives this generic error.</p>

Body:
I have installed Cocoapods, and created a Podfile using Atom containing the following lines:

pod ‘Parse’, ‘~> 1.7.1′
pod ‘ParseUI’, ‘~> 1.1.3′

Upon placing this file into my Xcode Project Root Directory, and running 'pod install' in Terminal. The following is shown:

[!] Your Podfile has had smart quotes sanitised. To avoid issues in
  the future, you should not use TextEdit for editing it. If you are not
  using TextEdit, you should turn off smart quotes in your editor of
  choice.

/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.38.2/lib/cocoapods-core/standard_error.rb:87:in `message': incompatible character encodings: ASCII-8BIT and UTF-8 (Encoding::CompatibilityError)
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.9.1/lib/claide/command.rb:367:in `handle_exception'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.9.1/lib/claide/command.rb:315:in `rescue in run'
    from /Library/Ruby/Gems/2.0.0/gems/claide-0.9.1/lib/claide/command.rb:303:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.38.2/lib/cocoapods/command.rb:48:in `run'
    from /Library/Ruby/Gems/2.0.0/gems/cocoapods-0.38.2/bin/pod:44:in `<top (required)>'
    from /usr/bin/pod:23:in `load'
    from /usr/bin/pod:23:in `'

I'm unsure what I have done incorrectly, if anyone could give me some advice - it would be really appreciated. Thank you.


问:
Can't find the Class Diagram in Visual Studio 2017
I've installed Visual Studio 2017 Enterprise on my computer with the Installer and there are some optional options like the "Class-Diagram".
I've checked it but it won't show up in my project templates.

Programm language: C#

Version VS 2017: 15.0.26228.9

Version VS Installer: 1.5.30308.1

VS Installer - Class Diagram is checked and already installed (Screenshot)

On the left hand side, we can't find the category "Model Project" like in VS 2015

Regards

答: It seems the 'modelling project' feature is removed from Visual Studio 2017. Reasons are given here https://blogs.msdn.microsoft.com/devops/2016/10/14/uml-designers-have-been-removed-layer-designer-now-supports-live-architectural-analysis/ </p>


问:
Combining two queries and using HAVING
My solution about this problem is by using 2 queries, but I am wondering if I can do it in one query only.

I have tables like these:

saved_docs

```<code>   id   |   user_id   |   doc_id   |   date
-----------------------------------------------
   1    |   2         |   1        |   date
   2    |   3         |   2        |   date
   3    |   2         |   3        |   date
</code>```

docs_list

```<code>   id   |   url   |   title   |   date
-----------------------------------------
   1    |   url   |   title   |   date
   2    |   url   |   title   |   date
   3    |   url   |   title   |   date
</code>```

What I want is first to get the doc_id on where the user_id is equal to user's id. Then, get the docs on where the id in the docs_list is equal to doc_id/s I get in saved_docs and order by the saved_docs' date.

This can be done on 2 queries, but if there is a possibility that I can do it in one only then I will go for it.

Here is my current mysql query:

```<code>SELECT docs_list.url, docs_list.title

FROM docs_list

INNER JOIN saved_docs

ON saved_posts.user_id = {$user_id}

ORDER BY saved_docs.date DESC
</code>```

Note: I read about HAVING, problem is I do not know how to apply it to this query.

Current problem:

It is giving me all the docs in which is obvious because it does not give the right doc_id/s (automated). What do I need to do to make this the way I wanted to?

[SOLVED]

Note: Both etsa's and adam's answer solved my problem.

答:
Sounds like you want to do it in the opposite order.

First find all docs saved by user {$user_id}, then fetch the info about those docs and sort the list.

```<code>SELECT docs_list.url, docs_list.title
FROM saved_docs
LEFT JOIN docs_list
ON docs_list.id = saved_docs.doc_id
WHERE saved_docs.user_id = {$user_id}
ORDER BY saved_docs.date DESC
</code>```

Title: Combining two queries and using HAVING

Body:
My solution about this problem is by using 2 queries, but I am wondering if I can do it in one query only.

I have tables like these:

saved_docs

   id   |   user_id   |   doc_id   |   date
-----------------------------------------------
   1    |   2         |   1        |   date
   2    |   3         |   2        |   date
   3    |   2         |   3        |   date

docs_list

   id   |   url   |   title   |   date
-----------------------------------------
   1    |   url   |   title   |   date
   2    |   url   |   title   |   date
   3    |   url   |   title   |   date

What I want is first to get the doc_id on where the user_id is equal to user's id. Then, get the docs on where the id in the docs_list is equal to doc_id/s I get in saved_docs and order by the saved_docs' date.

This can be done on 2 queries, but if there is a possibility that I can do it in one only then I will go for it.

Here is my current mysql query:

SELECT docs_list.url, docs_list.title

FROM docs_list

INNER JOIN saved_docs

ON saved_posts.user_id = {$user_id}

ORDER BY saved_docs.date DESC

Note: I read about HAVING, problem is I do not know how to apply it to this query.

Current problem:

It is giving me all the docs in which is obvious because it does not give the right doc_id/s (automated). What do I need to do to make this the way I wanted to?

[SOLVED]

Note: Both etsa's and adam's answer solved my problem.

Body:
Sounds like you want to do it in the opposite order.

First find all docs saved by user {$user_id}, then fetch the info about those docs and sort the list.

SELECT docs_list.url, docs_list.title
FROM saved_docs
LEFT JOIN docs_list
ON docs_list.id = saved_docs.doc_id
WHERE saved_docs.user_id = {$user_id}
ORDER BY saved_docs.date DESC


问:
Grouping switch statement cases together?
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

```<code>SELECT CASE Answer
CASE 1, 2, 3, 4
</code>```

Example in C++ (For those that need it):

```<code>#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}
</code>```

答: No, unless you want to break compatibility and your compiler supports it.

Body:
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:

SELECT CASE Answer
CASE 1, 2, 3, 4

Example in C++ (For those that need it):

#include <iostream.h>
#include <stdio.h>
int main()
{
   int Answer;
   cout << "How many cars do you have?";
   cin >> Answer;
   switch (Answer)
      {
      case 1:
      case 2:
      case 3:
      case 4:
         cout << "You need more cars. ";
         break;
      case 5:
      case 6:
      case 7:
      case 8:
         cout << "Now you need a house. ";
         break;
      default:
         cout << "What are you? A peace-loving hippie freak? ";
      }
      cout << "\nPress ENTER to continue... " << endl;
      getchar();
      return 0;
}


问:
How to add whitespace between CheckBoxes in ASP.NET
I have problem adding spaces between CheckBoxes and text next to them. I want to have them intended a little bit, not next to each other without some space.

▓car▓wash▓next and have it like ▓ car ▓ wash ▓ next

CheckBoxes aren't fixed at size, they are gathered from database.

I have CheckBoxList like:

```<code><asp:CheckBoxList ID="chBoxListManufacturer" runat="server" BackColor="LightBlue" BorderColor="Red" CellPadding="5" CssClas="mycheckbox"
       TextAlign="Right" RepeatDirection="Horizontal" RepeatLayout="Flow" OnSelectedIndexChanged="BoxListManufacturer_OnSelectedIndexChanged" AutoPostBack="True" />
</code>```

Css:.mycheckbox {margin-right: 15px;}

I was reading docs, but nothing works.

答:
you can try with css class:

your checkboxlist here.

```<code><asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="test">
        <asp:ListItem Text="Yes" Value="Yes" Selected="True"></asp:ListItem>
        <asp:ListItem Text="No" Value="No"></asp:ListItem>
    </asp:CheckBoxList>
</code>```

css here.

```<code>.test td
{
    border:1px solid red;
    margin-right:10px;
    padding-right:20px;
}
</code>```

output.

Body:
I have problem adding spaces between CheckBoxes and text next to them. I want to have them intended a little bit, not next to each other without some space.

▓car▓wash▓next and have it like ▓ car ▓ wash ▓ next

CheckBoxes aren't fixed at size, they are gathered from database.

I have CheckBoxList like:

<asp:CheckBoxList ID="chBoxListManufacturer" runat="server" BackColor="LightBlue" BorderColor="Red" CellPadding="5" CssClas="mycheckbox"
       TextAlign="Right" RepeatDirection="Horizontal" RepeatLayout="Flow" OnSelectedIndexChanged="BoxListManufacturer_OnSelectedIndexChanged" AutoPostBack="True" />

Css:.mycheckbox {margin-right: 15px;}

I was reading docs, but nothing works.

Body:
you can try with css class:

your checkboxlist here.

<asp:CheckBoxList ID="CheckBoxList1" runat="server" CssClass="test">
        <asp:ListItem Text="Yes" Value="Yes" Selected="True"></asp:ListItem>
        <asp:ListItem Text="No" Value="No"></asp:ListItem>
    </asp:CheckBoxList>

css here.

.test td
{
    border:1px solid red;
    margin-right:10px;
    padding-right:20px;
}

output.


问:
during ajax processing when we click ouside of popup then popup should not be closed
I am doing ajax functionlity on popup, during ajax functionality when we click outside of popup then popup should not be closed

I am using..

```<code>$('.edits-photo').modal('toggle');
</code>```

so please suggest me the changes.

答:
Try like below:</p>

```<code>$( document ).ajaxStart(function() {
    $(".edits-photo").modal({
      escapeClose: false,
      clickClose: false,
      showClose: false
    });
});
</code>```

Body:
I am doing ajax functionlity on popup, during ajax functionality when we click outside of popup then popup should not be closed

I am using..

$('.edits-photo').modal('toggle');

so please suggest me the changes.

Body:
Try like below:

$( document ).ajaxStart(function() {
    $(".edits-photo").modal({
      escapeClose: false,
      clickClose: false,
      showClose: false
    });
});


问:
results from $wpdb->last_query
I am attempting to move a single page into Wordpress as a plugin as an Admin menu. I first verify that isset($wpdb) but my test query fails. I do $wpdb->last_query and I don't understand the results.

This is what I try:

```<code>    $clientquery = $wpdb->query("select post_title from wp_posts where id=390");
    exit(var_dump( $wpdb->last_query));
</code>```

This is the result:

```<code>string(44) "select post_title from wp_posts where id=390"
</code>```

Where is string(44) coming from?  BTW, I am absolutely new to developing in PHP and Wordpress learning this on my own.

Also, if I change the query to "select * from ..." the result changes to string(35)... . What?

答:
The $wpdb->last_query shows the exact MySQL Query itself and string(44) indicates that it is string type of length 44:

```<code> string(44)   select post_title from wp_posts where id=390
</code>```

WordPress defines a class called wpdb, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database. So it is not necessary to check using isset() function

Title: results from $wpdb->last_query

Body:
I am attempting to move a single page into Wordpress as a plugin as an Admin menu. I first verify that isset($wpdb) but my test query fails. I do $wpdb->last_query and I don't understand the results.

This is what I try:

    $clientquery = $wpdb->query("select post_title from wp_posts where id=390");
    exit(var_dump( $wpdb->last_query));

This is the result:

string(44) "select post_title from wp_posts where id=390"

Where is string(44) coming from?  BTW, I am absolutely new to developing in PHP and Wordpress learning this on my own.

Also, if I change the query to "select * from ..." the result changes to string(35)... . What?

Body:
The $wpdb->last_query shows the exact MySQL Query itself and string(44) indicates that it is string type of length 44:

 string(44)   select post_title from wp_posts where id=390

WordPress defines a class called wpdb, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database. So it is not necessary to check using isset() function


问:
How to accept an out parameter in Ajax?
I have a static function in the aspx page with this signature:

```<code>   public static bool UserNeedsToBeAlertedPwdReset(out DateTime dtExpires)
   {
        DateTime dt = DateTime.MivValue;

        return true;
   }
</code>```

So I want to call this function from the client side, using the jQuery Ajax. How do I get a hold of the out value?

Edit
Alternatevly I could check for nulls if this is possible with Ajax + jQuery like that:

```<code>   public static DateTime? UserNeedsToBeAlertedPwdReset()
   {
        if(blah)
           return null;
        return DateTime.Now;
   }
</code>```

答:
Why not create a function that returns a JSON response which you could include all the data you need.

I prefer to create .ashx handlers for these types of things and return a JSON response that is very to easy call and and handle client side.

Title: How to accept an out parameter in Ajax?

Body:
I have a static function in the aspx page with this signature:

   public static bool UserNeedsToBeAlertedPwdReset(out DateTime dtExpires)
   {
        DateTime dt = DateTime.MivValue;

        return true;
   }

So I want to call this function from the client side, using the jQuery Ajax. How do I get a hold of the out value?

Edit
Alternatevly I could check for nulls if this is possible with Ajax + jQuery like that:

   public static DateTime? UserNeedsToBeAlertedPwdReset()
   {
        if(blah)
           return null;
        return DateTime.Now;
   }


问:
how to use a onkeyup function in javaScript to get the value using ajax with spring
How to use the on key up event with timeout option. The values typed should return the data that matched in the data base

here my Jquery code is

```<code>function searchUserId() {
  var userId = $('#userId').val();
  //var moduleID = $('#moduleIdList').val();

  $.ajax({
    url: "controlpanel/SearchUserData",
    type: "POST",
    data: "userId=" + userId,
      //+ "&roleName=" + roleName,
      //For Progress Bar
    success: function(response) {
      alert(userId);
      $('#page-wrapper').html(response);
    }
  });
}
</code>```

<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
   onkeyup="searchUserId();"data-validation-engine="validate[required]"/>
```

答:
By 'timeout option' I assume that you mean to use this to only trigger the function when the user has finished typing.

First you should remove the onkeyup attribute from the HTML.

Then add the following to your JS:

```<code>var timer;

$('#userId').on('keyup', function() {
  if (timer) clearTimeout(timer);
  timer = setTimeout(searchUserId,300);
});
</code>```

This will reset the timer if another keyup event is triggered within 300ms, so the function will not get triggered when the user is still typing. Of course you can set this to any value you like.

Body:
How to use the on key up event with timeout option. The values typed should return the data that matched in the data base

here my Jquery code is

function searchUserId() {
  var userId = $('#userId').val();
  //var moduleID = $('#moduleIdList').val();

  $.ajax({
    url: "controlpanel/SearchUserData",
    type: "POST",
    data: "userId=" + userId,
      //+ "&roleName=" + roleName,
      //For Progress Bar
    success: function(response) {
      alert(userId);
      $('#page-wrapper').html(response);
    }
  });
}

<input type="text" tabindex="1" class="form-control" name="userId" id="userId" maxlength="20"
   onkeyup="searchUserId();"data-validation-engine="validate[required]"/>

Body:
By 'timeout option' I assume that you mean to use this to only trigger the function when the user has finished typing.

First you should remove the onkeyup attribute from the HTML.

Then add the following to your JS:

var timer;

$('#userId').on('keyup', function() {
  if (timer) clearTimeout(timer);
  timer = setTimeout(searchUserId,300);
});

This will reset the timer if another keyup event is triggered within 300ms, so the function will not get triggered when the user is still typing. Of course you can set this to any value you like.


问:
Javascript function remove from position in array
I have an array:

```<code>var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
</code>```

I need to remove each 3rd item from the array and add it to another array.

The final result should be:

```<code>var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];
</code>```

How can i do that?

答:
iterate over the array and splice every 3rd element and push to the second array.

var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];
var secondArray = [];
for (var i = 2; i < myArray.length; i += 2) {
  secondArray.push(myArray[i]);
  myArray.splice(i, 1);
}

console.info('myArray', myArray)
console.info('secondArray', secondArray)```

Body:
I have an array:

var myArray = [12, 11, 13, 18, 30, 51, 21, 18, 20];

I need to remove each 3rd item from the array and add it to another array.

The final result should be:

var myArray = [12, 11 18, 30, 21, 18];

var secondArray = [13, 51, 20];

How can i do that?