问:
How to get the result of the confirm popup in to a variable in spring MVC?
This is my jsp page

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function getChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    return k;
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<center><form method="POST" action="saveagain">
<h3>${message} </h3>
            <br> <br>
<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}"> <br><br>
 <input type="button" value="Overwrite ?" onclick="choice=getChoice()"/>
<input type="submit" value="Submit ?"></form></center>
<br>
<br>
<center><b>${m}</b></center>
<br><br>
<center><a href="toupload">Click me to upload a file</a>  <br><br>
</center>
</body>
</html>
</code>```

In the above code, i want to get the result of confirm popup in to a variable "choice". How to do that ?

Modified code :

bean class :

```<code>package com.fss;

public class Choice {
 private String choice;
private String fname;
private String fcontent;

public String getChoice() {
    return choice;
}

public void setChoice(String choice) {
    this.choice = choice;
}

public String getFname() {
    return fname;
}

public void setFname(String fname) {
    this.fname = fname;
}

public String getFcontent() {
    return fcontent;
}

public void setFcontent(String fcontent) {
    this.fcontent = fcontent;
}

}
</code>```

this is my jsp page :

```<code><html>
<head>
<script>
function getUserChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    $('#choice').val(k);
    return k;
}
</script>
</head>
<body>
<center><h3>${message} </h3></center>
            <br>
  <center><form method="POST" action="saveagain">
    <input type="hidden" name="fname" value="${filename}">
    <input type="hidden" name="fcontent" value="${filecontent}">
    <input type="hidden" name="choice" id="choice"> <br><br>
    <input type="submit" value="Overwrite ?" onclick="getUserChoice()"/></form></center>
<center><a href="toupload">Click me to upload a file</a>  </center>
</body>
</html>
</code>```

This is my Controller class:

```<code> @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@ModelAttribute("ch") Choice ch) throws IOException{

     String ch1;
     String message="";
     ch1=ch.getChoice();
     System.out.println("popup result "+ch1);
     return new ModelAndView("fileUpload","message",message);
 }
</code>```

fname and fcontent values are reflecting in controller. why is choice value not reflecting in "ch1" ?

答:
You can create a variable such as cofirmstatus in the form.

```<code><input type="hidden" name="cofirmstatus" id="cofirmstatus">
</code>```

And set the value as below

```<code>function getChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    $('#cofirmstatus').val(k);
    return k;
}
</code>```

So, once the form is submitted, this value will be available on the server side

EDIT:

I created the JSP as follows. No changes required on server side.

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function submitForm(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    document.myform.choice.value=k;
    document.myform.submit();
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<center><form method="POST" action="saveagain" name="myform">
<h3>${message} </h3>
            <br> <br>
<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}"> <br><br>
<input type="hidden" name="choice" id="choice"> <br><br>
 <input type="button" value="Overwrite ?" onclick="javascript:submitForm()"/>
<input type="submit" value="Submit ?"></form></center>
<br>
<br>
<center><b>${m}</b></center>
<br><br>
<center><a href="toupload">Click me to upload a file</a>  <br><br>
</center>
</body>
</html>
</code>```

Output on server for both the actions:

```<code>popup result true
popup result false
</code>```

Body:
This is my jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<form method="POST" action="saveagain">

${message}

<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}">

 <input type="button" value="Overwrite ?" onclick="choice=getChoice()"/>
<input type="submit" value="Submit ?"></form>

${m}

Click me to upload a file

In the above code, i want to get the result of confirm popup in to a variable "choice". How to do that ?

Modified code :

bean class :

package com.fss;

public class Choice {
 private String choice;
private String fname;
private String fcontent;

public String getChoice() {
    return choice;
}

public void setChoice(String choice) {
    this.choice = choice;
}

public String getFname() {
    return fname;
}

public void setFname(String fname) {
    this.fname = fname;
}

public String getFcontent() {
    return fcontent;
}

public void setFcontent(String fcontent) {
    this.fcontent = fcontent;
}

}

this is my jsp page :

${message}

  <form method="POST" action="saveagain">
    <input type="hidden" name="fname" value="${filename}">
    <input type="hidden" name="fcontent" value="${filecontent}">
    <input type="hidden" name="choice" id="choice">

    <input type="submit" value="Overwrite ?" onclick="getUserChoice()"/></form>
Click me to upload a file

This is my Controller class:

 @RequestMapping(value="/saveagain",method = RequestMethod.POST)
 public ModelAndView fileUploading2(@ModelAttribute("ch") Choice ch) throws IOException{

     String ch1;
     String message="";
     ch1=ch.getChoice();
     System.out.println("popup result "+ch1);
     return new ModelAndView("fileUpload","message",message);
 }

fname and fcontent values are reflecting in controller. why is choice value not reflecting in "ch1" ?

Body:
You can create a variable such as cofirmstatus in the form.

<input type="hidden" name="cofirmstatus" id="cofirmstatus">

And set the value as below

function getChoice(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    $('#cofirmstatus').val(k);
    return k;
}

So, once the form is submitted, this value will be available on the server side

EDIT:

I created the JSP as follows. No changes required on server side.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function submitForm(){
    var k=confirm("Do you want me to overwrite the existing file ?");
    document.myform.choice.value=k;
    document.myform.submit();
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<center><form method="POST" action="saveagain" name="myform">
<h3>${message} </h3>
            <br> <br>
<input type="hidden" name="fname" value="${filename}">
<input type="hidden" name="fcontent" value="${filecontent}"> <br><br>
<input type="hidden" name="choice" id="choice"> <br><br>
 <input type="button" value="Overwrite ?" onclick="javascript:submitForm()"/>
<input type="submit" value="Submit ?"></form></center>
<br>
<br>
<center><b>${m}</b></center>
<br><br>
<center><a href="toupload">Click me to upload a file</a>  <br><br>
</center>
</body>
</html>

Output on server for both the actions:

popup result true
popup result false


来源: stackexchange

问:
Restrict length of log output in Rails
I have an API that accepts base64 encoded images. The requests come in looking like:

```<code>{
  image: "ijt41ig8ahbha8oij4j1tjletc"
}
</code>```

The base64 encoded strings can be very large, sometimes 10k - 100k characters. When a request is sent with improperly formatted JSON, Active Dispatch correctly raises an error and logs the request:

```<code>ActionDispatch::ParamsParser::ParseError (765: unexpected token at '{
    "image": "iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ"
}'):
actionpack (5.0.5) lib/action_dispatch/http/parameters.rb:88:in `rescue in parse_formatted_parameters'
actionpack (5.0.5) lib/action_dispatch/http/parameters.rb:82:in `parse_formatted_parameters'
actionpack (5.0.5) lib/action_dispatch/http/request.rb:354:in `block in POST'

etc
</code>```

In this case the error is caused by new lines in the encoding.

My question is, what is a good way to restrict the logging to not display the sometimes 50k char long image string? This is filling up my log files and making looking through logs difficult. I do want the error logged, I just want to slice the string to maybe show the first 255 chars instead of the massive image.

I know that ActionDispatch has some nice ways of filtering attributes (for instance passwords), but that assumes that the parameters have been parsed into a hash, which in the case of a JSON error they have not.

答:
I ended up creating a custom formatter and just manipulating the string directly

```<code>class CustomFormatter < Logger::Formatter

  def call(severity, time, program_name, message)
    if message =~ /"image": /
      message.gsub!(/(?<="image": )".+"/m) { |image| image[0..255]  + "_TRUNCATED_" }
    end

    super
  end

end
</code>```

Then just use that formatter in your config file

```<code>  config.logger = Logger.new(STDOUT).tap do |logger|
    logger.formatter = CustomFormatter.new
  end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Restrict length of log output in Rails

Body:
I have an API that accepts base64 encoded images. The requests come in looking like:

{
  image: "ijt41ig8ahbha8oij4j1tjletc"
}

The base64 encoded strings can be very large, sometimes 10k - 100k characters. When a request is sent with improperly formatted JSON, Active Dispatch correctly raises an error and logs the request:

ActionDispatch::ParamsParser::ParseError (765: unexpected token at '{
    "image": "iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ
    iVlBWsBo4OQT1Mm7AZbIBV3h8mwtvLdakElJ6U1ksbQsl3URJ"
}'):
actionpack (5.0.5) lib/action_dispatch/http/parameters.rb:88:in `rescue in parse_formatted_parameters'
actionpack (5.0.5) lib/action_dispatch/http/parameters.rb:82:in `parse_formatted_parameters'
actionpack (5.0.5) lib/action_dispatch/http/request.rb:354:in `block in POST'

etc

In this case the error is caused by new lines in the encoding.

My question is, what is a good way to restrict the logging to not display the sometimes 50k char long image string? This is filling up my log files and making looking through logs difficult. I do want the error logged, I just want to slice the string to maybe show the first 255 chars instead of the massive image.

I know that ActionDispatch has some nice ways of filtering attributes (for instance passwords), but that assumes that the parameters have been parsed into a hash, which in the case of a JSON error they have not.

Body:
I ended up creating a custom formatter and just manipulating the string directly

class CustomFormatter < Logger::Formatter

  def call(severity, time, program_name, message)
    if message =~ /"image": /
      message.gsub!(/(?<="image": )".+"/m) { |image| image[0..255]  + "_TRUNCATED_" }
    end

    super
  end

end

Then just use that formatter in your config file

  config.logger = Logger.new(STDOUT).tap do |logger|
    logger.formatter = CustomFormatter.new
  end


问:
UPDATE table SET with multi values
I have spent a lot of time online trying to look for an answer but no success so I decided to post the following.
I have the following tables:

```<code>TABLE_1
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             4 |
|          2 |             3 |
|          3 |             2 |
|          4 |             1 |
+------------+---------------+

TABLE_2
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             0 |
|          2 |             0 |
|          3 |             0 |
|          4 |             0 |
+------------+---------------+
</code>```

I would like to update the values of mother_id in my table 2 with the values of of mother_id located in my table 1.
Of course the example above could be solved doing manually:

```<code>UPDATE table2 SET mother_id = 1 where child_id = 4;
UPDATE table2 SET mother_id = 2 where child_id = 3;
UPDATE table2 SET mother_id = 3 where child_id = 2;
UPDATE table2 SET mother_id = 4 where child_id = 1;
</code>```

But let's imagine I have thousand of lines to update. Is there any way to do this using select join queries (on child_id) mixed with update in order to have only a few lines of code?

Thank you.

答:
It is done through the inner join effectively </p>

```<code>update table_2
inner join table_1
on table_2.child_id = table_1.child_id
set table_2.mother_id = table_1.mother_id;
</code>```

Title: UPDATE table SET with multi values

Body:
I have spent a lot of time online trying to look for an answer but no success so I decided to post the following.
I have the following tables:

TABLE_1
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             4 |
|          2 |             3 |
|          3 |             2 |
|          4 |             1 |
+------------+---------------+

TABLE_2
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             0 |
|          2 |             0 |
|          3 |             0 |
|          4 |             0 |
+------------+---------------+

I would like to update the values of mother_id in my table 2 with the values of of mother_id located in my table 1.
Of course the example above could be solved doing manually:

UPDATE table2 SET mother_id = 1 where child_id = 4;
UPDATE table2 SET mother_id = 2 where child_id = 3;
UPDATE table2 SET mother_id = 3 where child_id = 2;
UPDATE table2 SET mother_id = 4 where child_id = 1;

But let's imagine I have thousand of lines to update. Is there any way to do this using select join queries (on child_id) mixed with update in order to have only a few lines of code?

Thank you.

Body:
It is done through the inner join effectively

update table_2
inner join table_1
on table_2.child_id = table_1.child_id
set table_2.mother_id = table_1.mother_id;


问:
The procedure to matching words from a list to words in a line
The following are two examples of many lines that I need to analyze and extract specific words from.

```<code>[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.
</code>```

The coordinates and numbers are ignored

The case is to find how many of the words in each tweet line are present in this keywords list:

```<code>['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]
</code>```

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.

For example, for the sentence

```<code>'I hate to feel lonely at times'
</code>```

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.

I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.

What I want to find out is the sum of sentiment values of the keywords found in each line and how many words there were in each line

Appreciate your insight in advance!! :)

My Code:

```<code>try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()
</code>```

答:
If your tweets are in a .txt like this file and pattern of lines of tweets are same as you described in the question then you can try this approach:

```<code>import re
import json
pattern=r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)'
sentiment_dict={'hate' :1,'hurt':1,'hurting':1,'like':5,'lonely':1,'love':10}

final=[]
with open('senti.txt','r+') as f:
    for line in f:
        data = []

        match=re.finditer(pattern,line)
        for find in match:
            if find.group(1).split():
                final.append(find.group(1).split())

line=[]

for item in final:
    final_dict = {}

    for sub_item in item:
        if sub_item in sentiment_dict:
            if sub_item not in final_dict:
                final_dict[sub_item]=[sentiment_dict.get(sub_item)]
            else:
                final_dict[sub_item].append(sentiment_dict.get(sub_item))

    line.append((item,len(item),{key: sum(value) for key,value in final_dict.items()}))

result=json.dumps(line,indent=2)

print(result)
</code>```

output:

```<code>[
  [
    [
      "Sometimes",       #tweets line or all words
      "I",
      "wish",
      "my",
      "life",
      "was",
      "a",
      "movie;",
      "#unreal",
      "I",
      "hate",
      "the",
      "fact",
      "I",
      "feel",
      "lonely",
      "surrounded",
      "by",
      "so",
      "many",
      "ppl"
    ],
    21,                   #count of words in tweets
    {
      "lonely": 1,        #sentiment count
      "hate": 1
    }
  ],
  [
    [
      "I",
      "wish",
      "I",
      "could",
      "lay",
      "up",
      "with",
      "the",
      "love",
      "of",
      "my",
      "life",
      "And",
      "watch",
      "cartoons",
      "all",
      "day."
    ],
    17,
    {
      "love": 10
    }
  ],
  [
    [
      "I",
      "hate",
      "to",
      "feel",
      "lonely",
      "at",
      "times"
    ],
    7,
    {
      "lonely": 1,
      "hate": 1
    }
  ]
]
</code>```

Options for regex if one pattern doesn't work for your file:

r'[a-zA-Z].+'   #if you use this change find.group(1) to find.group()

r'(?<=\d.\s)[a-zA-Z].+'   #if you use this change find.group(1) to find.group()

r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)'

r'\b\d{2}:\d{2}:\d{2} (.+)'  #group(1)

Body:
The following are two examples of many lines that I need to analyze and extract specific words from.

[40.748330000000003, -73.878609999999995] 6 2011-08-28 19:52:47 Sometimes I wish my life was a movie; #unreal I hate the fact I feel lonely surrounded by so many ppl

[37.786221300000001, -122.1965002] 6 2011-08-28 19:55:26 I wish I could lay up with the love of my life And watch cartoons all day.

The coordinates and numbers are ignored

The case is to find how many of the words in each tweet line are present in this keywords list:

['hate', 1]
['hurt', 1]
['hurting', 1]
['like', 5]
['lonely', 1]
['love', 10]

And also, find the sum of the values (e.g ['love', 10]) of the keywords found in each tweet line.

For example, for the sentence

'I hate to feel lonely at times'

The sum of sentiments values for hate=1 and lonely=1 is equal to 2.
And the no. of words in the line is 7.

I've tried to use list into lists method and even trying to go through each sentence and keywords, but those haven't worked because the no. of tweets and keywords are several and I need to use loop format to find the values.

What I want to find out is the sum of sentiment values of the keywords found in each line and how many words there were in each line

Appreciate your insight in advance!! :)

My Code:

try:
    KeywordFileName=input('Input keyword file name: ')
    KeywordFile = open(KeywordFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()
KeyLine = KeywordFile.readline()
while KeyLine != '':
    if list != []:
        KeyLine = KeywordFile.readline()
        KeyLine = KeyLine.rstrip()
        list = KeyLine.split(',')
        list[1] = int(list[1])
        print(list)
    else:
        break

try:
    TweetFileName = input('Input Tweet file name: ')
    TweetFile = open(TweetFileName, 'r')
except FileNotFoundError:
    print('The file you entered does not exist or is not in the directory')
    exit()

TweetLine = TweetFile.readline()
while TweetLine != '':
    TweetLine = TweetFile.readline()
    TweetLine = TweetLine.rstrip()

Body:
If your tweets are in a .txt like this file and pattern of lines of tweets are same as you described in the question then you can try this approach:

import re
import json
pattern=r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)'
sentiment_dict={'hate' :1,'hurt':1,'hurting':1,'like':5,'lonely':1,'love':10}

final=[]
with open('senti.txt','r+') as f:
    for line in f:
        data = []

        match=re.finditer(pattern,line)
        for find in match:
            if find.group(1).split():
                final.append(find.group(1).split())

line=[]

for item in final:
    final_dict = {}

    for sub_item in item:
        if sub_item in sentiment_dict:
            if sub_item not in final_dict:
                final_dict[sub_item]=[sentiment_dict.get(sub_item)]
            else:
                final_dict[sub_item].append(sentiment_dict.get(sub_item))

    line.append((item,len(item),{key: sum(value) for key,value in final_dict.items()}))

result=json.dumps(line,indent=2)

print(result)

output:

[
  [
    [
      "Sometimes",       #tweets line or all words
      "I",
      "wish",
      "my",
      "life",
      "was",
      "a",
      "movie;",
      "#unreal",
      "I",
      "hate",
      "the",
      "fact",
      "I",
      "feel",
      "lonely",
      "surrounded",
      "by",
      "so",
      "many",
      "ppl"
    ],
    21,                   #count of words in tweets
    {
      "lonely": 1,        #sentiment count
      "hate": 1
    }
  ],
  [
    [
      "I",
      "wish",
      "I",
      "could",
      "lay",
      "up",
      "with",
      "the",
      "love",
      "of",
      "my",
      "life",
      "And",
      "watch",
      "cartoons",
      "all",
      "day."
    ],
    17,
    {
      "love": 10
    }
  ],
  [
    [
      "I",
      "hate",
      "to",
      "feel",
      "lonely",
      "at",
      "times"
    ],
    7,
    {
      "lonely": 1,
      "hate": 1
    }
  ]
]

Options for regex if one pattern doesn't work for your file:

r'[a-zA-Z].+'   #if you use this change find.group(1) to find.group()

r'(?<=\d.\s)[a-zA-Z].+'   #if you use this change find.group(1) to find.group()

r'\d{2}:\d{2}:\d{2}\s([a-zA-Z].+)'

r'\b\d{2}:\d{2}:\d{2} (.+)'  #group(1)


问:
swig no module named _example
I cannot reproduce the basic SWIG example on windows.
My error is stated in the SWIG docs and I am sure that I do the 2 fixes they mention. For this error:

```<code>>>> import example
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "example.py", line 2, in ?
    import _example
ImportError: No module named _example
</code>```

the SWIG documentation clearly states:

forget the leading underscore (_).

forget the leading underscore (_).> If you get this message, it means that

you either forgot to compile the
  wrapper code into an extension module
  or you didn't give the extension
  module the right name. Make sure that
  you compiled the wrappers into a
  module called example.so. And don't
  forget the leading underscore ().forget the leading underscore (_).

and I am sure that I link with the latest wrap object build and I have tryied: "_example", "_example.so", "example.dll", "example.so", "example.dll", even all at once, and that the generated "example.py" is in the same folder as the shared library, and that the python path contains this directoryforget the leading underscore ().

THE EXAMPLE:

```<code>//example.h
int foo_sum(int a, int b);
</code>```

.

```<code>//example.cpp
int foo_sum(int a, int b) {
    return a + b;
}
</code>```

.

```<code>//example.i
%module example
%{
#include "example.h"
%}

#include "example.h
</code>```

and the build commands:

```<code>gcc -IV:\temp\example\external\include\Python -O3 -Wall -c -fmessage-length=0 -oexample_wrap.o ..\example_wrap.c
g++ -IV:\temp\example\external\include\Python -O3 -Wall -c -fmessage-length=0 -oexample.o ..\example.cpp
g++ -LV:\temp\example\external\lib -shared -oexample.dll example_wrap.o example.o -lpython26
</code>```

even if I don't use -O3 it still doesn't work (I pasted the build commands from a Release configuration)

I also tried this and to no success:

```<code>>>> import sys
>>> sys.path.append("/your/module/path")
>>> import example
</code>```

EDIT:

apparently it loads the dll if you rename it to "_example.pyd", BUT the module loaded does not contain my "foo_sum" function

EDIT:
it works now, I am using extern "C" and not including headers in the .i file

答:
I found that (in windows), if you make a dll it has to be called _modulename.pyd
This library (_modulename.pyd), the original c++ module myapp.dll and the resulting modulename.py have to be in the path as well as pythonxx.exe</p>

ContentLicense: CC BY-SA 2.5

Title: swig no module named _example

Body:
I cannot reproduce the basic SWIG example on windows.
My error is stated in the SWIG docs and I am sure that I do the 2 fixes they mention. For this error:

>>> import example
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "example.py", line 2, in ?
    import _example
ImportError: No module named _example

the SWIG documentation clearly states:

forget the leading underscore (_).

forget the leading underscore (_).> If you get this message, it means that

you either forgot to compile the
  wrapper code into an extension module
  or you didn't give the extension
  module the right name. Make sure that
  you compiled the wrappers into a
  module called example.so. And don't
  forget the leading underscore ().forget the leading underscore (_).

and I am sure that I link with the latest wrap object build and I have tryied: "_example", "_example.so", "example.dll", "example.so", "example.dll", even all at once, and that the generated "example.py" is in the same folder as the shared library, and that the python path contains this directoryforget the leading underscore ().

THE EXAMPLE:

//example.h
int foo_sum(int a, int b);

.

//example.cpp
int foo_sum(int a, int b) {
    return a + b;
}

.

//example.i
%module example
%{
#include "example.h"
%}

#include "example.h

and the build commands:

gcc -IV:\temp\example\external\include\Python -O3 -Wall -c -fmessage-length=0 -oexample_wrap.o ..\example_wrap.c
g++ -IV:\temp\example\external\include\Python -O3 -Wall -c -fmessage-length=0 -oexample.o ..\example.cpp
g++ -LV:\temp\example\external\lib -shared -oexample.dll example_wrap.o example.o -lpython26

even if I don't use -O3 it still doesn't work (I pasted the build commands from a Release configuration)

I also tried this and to no success:

>>> import sys
>>> sys.path.append("/your/module/path")
>>> import example

EDIT:

apparently it loads the dll if you rename it to "_example.pyd", BUT the module loaded does not contain my "foo_sum" function

EDIT:
it works now, I am using extern "C" and not including headers in the .i file


问:
how to set secure flag on cookies in laravel
I want to set secure flag for cookies data when accessing content over HTTPS.

The cookies is used on entire application so need to global configuration to secure all the cookies.

答:
You need to override the default setting using session_set_cookie_params, set the $secure flag to true,

```<code>void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
</code>```

more info at php.net

In laravel you need to alter the config/session.php configuration,set the secure flag to true

```<code>/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => true,
</code>```

In newer versions of laravel you can simply set the SESSION_SECURE_COOKIE=true in the .env file

ContentLicense: CC BY-SA 4.0

Body:
You need to override the default setting using session_set_cookie_params, set the $secure flag to true,

void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )

more info at php.net

In laravel you need to alter the config/session.php configuration,set the secure flag to true

/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/

'secure' => true,

In newer versions of laravel you can simply set the SESSION_SECURE_COOKIE=true in the .env file


问:
Magento 1.9 categories not loading after import
I'm currently stuck at my magento shop and I can't find a solution. I want to import almost 600.000 products. The process of it is really slow. The more product are in the system, the slower the import of new products works. I also can't open some category pages. Its simply not loading.

Any idea what could be the problem?

答:
For Faster import, you can use Magmi : http://wiki.magmi.org/index.php?title=Main_Page

once you upload products through, reindex through system > Index Management....


问:
Need solution for automated testing of web application
There are testing solutions like selenium and webdriver for testing web applications. However those would be sort of overkill for me as I'm looking for a simple testing solution that sends the data using get/post and analyzes the received html code. So I'm definitely not looking something that requires browser integration etc. Got some pointers?</p>

答: Try cron jobs automating a script to do that</p>


问:
Convert a string value '21.45E02' to integer in Python
How to convert a string value such as '21.45E02', which has been raised to power to a normal integer?</p>

答:
Convert to a float first. Which can handle this format. Then if you want an integer use int to do the conversion, bearing in mind that this will result in a loss of precision which would cause rounding of the number if it did not have a zero fractional part.

```<code>>>> int(float('21.45E02'))
2145
</code>```

Body:
Convert to a float first. Which can handle this format. Then if you want an integer use int to do the conversion, bearing in mind that this will result in a loss of precision which would cause rounding of the number if it did not have a zero fractional part.

>>> int(float('21.45E02'))
2145


问:
I can't load images from Firebase - MeteorJS
I am trying to display the data as follows (doesn't work):

```<code>{{#each request}}
<div class="col-sm-4 col-lg-4 col-md-4">
        <div class="thumbnail" style="padding:0;border:0px;height:300px;overflow-y:auto">

            <img src="{{URLs[0]}}" alt="">

                <div class="container">
                <h4><a href="#">{{title}}</a>
                    <h4 style="color:red;">{{status}}</h4>
                </h4>
                </div>
        </div>
    </div>
    {{/each}}
</code>```

and I get the following error printed in the console:

Exception from Tracker recompute function: debug.js:41 Error: Can't
  call non-function:
  https://firebasestorage.googleapis.com/v0/b/omantourplacesapp.appspot.com/o/TourPlacesImages%2FIMG_0005.JPG?alt=media&token=22ab7965-3b03-4e7f-9798-99617b82dd9b

When I replace the following line:

```<code><img src="{{URLs[0]}}" alt="">
</code>```

With:

```<code><img src="https://upload.wikimedia.org/wikipedia/commons/0/0f/2010-02-19_3000x2000_chicago_skyline.jpg" alt="">
</code>```

It works and I can see the image showing in the browser.

Why Firebase images are not working?

NOTE: I am building native IOS application and I could retrieve the same image using the same Firebase URL there.

答: Don't use brackets use {{URLs.0}}</p>

Body:
I am trying to display the data as follows (doesn't work):

{{#each request}}

{{title}}

{{status}}

    {{/each}}

and I get the following error printed in the console:

Exception from Tracker recompute function: debug.js:41 Error: Can't
  call non-function:
  https://firebasestorage.googleapis.com/v0/b/omantourplacesapp.appspot.com/o/TourPlacesImages%2FIMG_0005.JPG?alt=media&token=22ab7965-3b03-4e7f-9798-99617b82dd9b

When I replace the following line:

With:

It works and I can see the image showing in the browser.

Why Firebase images are not working?

NOTE: I am building native IOS application and I could retrieve the same image using the same Firebase URL there.

Body: Don't use brackets use {{URLs.0}}


问:
how to send multiple dropdown list value into database
i tried to insert multiple dropdownlist value into one table in the database. But it only send the last entry. Newbies here. Need help

This is my code

```<code> <tr>
    <td><select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
  </tr>
  <tr>
    <td><select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
</code>```

As i mention when i run this it only send the second entry into the database. Some suggest me to use an array. but i dont know exactly how.

答:
Try to use this :

PHP

```<code><?php
if(isset($_POST['subjekSPM']))
{
foreach($_POST['subjekSPM'] as $selectedvalue)
{
    echo $selectedvalue;
}

}

?>
</code>```

HTML

```<code><tr>
    <td><select name="subjekSPM[]">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
  </tr>
  <tr>
    <td><select name="subjekSPM[]">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
</code>```

Body:
i tried to insert multiple dropdownlist value into one table in the database. But it only send the last entry. Newbies here. Need help

This is my code

    <select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select>
    <select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select>

    <select name="subjekSPM">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select>
    <select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select>

As i mention when i run this it only send the second entry into the database. Some suggest me to use an array. but i dont know exactly how.

Body:
Try to use this :

PHP

<?php
if(isset($_POST['subjekSPM']))
{
foreach($_POST['subjekSPM'] as $selectedvalue)
{
    echo $selectedvalue;
}

}

?>

HTML

<tr>
    <td><select name="subjekSPM[]">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>
  </tr>
  <tr>
    <td><select name="subjekSPM[]">
      <option value="bi">Bahasa Inggeris</option>
      <option value="math">Matematik</option>
      <option value="mTamb">Matematik Tambahan</option>
      <option value="tm">Teknologi Maklumat</option>
      <option value="kimia">Kimia</option>
      <option value="biologi">Biologi</option>
      <option value="akaun">Prinsip Akaun</option>
      <option value="lk">Lukisan Kejuruteraan</option>
      <option value="lukisan">Lukisan</option>
      <option value="seni">Pendidikan Seni</option>
      <option value="visual">Komunikasi Visual</option>
    </select></td>
    <td><select name="gred">
      <option value="10">A+</option>
      <option value="9">A</option>
      <option value="8">A-</option>
      <option value="7">B+</option>
      <option value="6">B</option>
      <option value="5">C+</option>
      <option value="4">C</option>
      <option value="3">D</option>
      <option value="2">E</option>
      <option value="1">F</option>
      <option value="0">G</option>
    </select></td>


问:
Datetime in C# - why doesn't milliseconds show and get subsequently stored in SQL Server?
Why doesn't milliseconds show in the datetime and get subsequently stored in SQL Server?

It shows as 11/14/2017 3:46:14 PM. The milliseconds are there - 323 but not part of the datetime.

So I want it stored in the SQL Server table as 11/14/2017 3:46:14.323 PM.

However, it stores it as 11/14/2017 3:46:14 PM.

The table column is dateTime.

Here's a debug shot of the date in the C# code.

Here's the table;

答:
It's just a display format problem.You can use this code in SSMS:

```<code>SELECT CAST ('11/14/2017 3:46:14.323 PM' AS DATETIME)
</code>```

You will see millseconds. In fact,the data stored is the same.

Body:
It's just a display format problem.You can use this code in SSMS:

SELECT CAST ('11/14/2017 3:46:14.323 PM' AS DATETIME)

You will see millseconds. In fact,the data stored is the same.


问:
oracle apex trigger mouse click over region using jquery
I have 3 regions in my apex page. R1,R2 and R3. R1 is a tabular region. R2 and R3 are sub regions of R1. I  want to trigger a fake mouse click event on region R3 when a button is clicked, using javascript. so to trigger mouse click on region R3 ( static id: R3 ) I used the code

```<code> $('#R3').trigger("click");
</code>```

But that doesn't work. When I inspected the page, I found the region id as 'SR_R3_tab'. So I changed the code to

```<code>$('#SR_R3_tab').trigger("click");
</code>```

That didn't made any progress . How can I do this ?

答:
Not sure what APEX version you are using. But I tried to reproduce your flow here.

What I basically did:

Parent child has a button 'Trigger Click'

Added dynamic action on click on that button, where the action is execute javascript: $('#R35171256286597705402').trigger("click");

List item R35171256286597705402 is the id of the child region. Not sure why yours is not following this format, because usually APEX generates these ids. But I fetched from inspecting

To validate, I added another dynamic action, but this time on click on the child region. It basically displays the alert

Body:
I have 3 regions in my apex page. R1,R2 and R3. R1 is a tabular region. R2 and R3 are sub regions of R1. I  want to trigger a fake mouse click event on region R3 when a button is clicked, using javascript. so to trigger mouse click on region R3 ( static id: R3 ) I used the code

 $('#R3').trigger("click");

But that doesn't work. When I inspected the page, I found the region id as 'SR_R3_tab'. So I changed the code to

$('#SR_R3_tab').trigger("click");

That didn't made any progress . How can I do this ?


问:
WPF graphics card problem
I recently bought a new laptop - a Toshiba Satellite A660, which has an ATI mobility Radeon HD 5650.  To save power it disables the Radeon when on battery power and uses integrated graphics.

I have some WPF apps which have common controls like buttons and checkboxes mapped onto 3D surfaces which can be rotated and moved.   With the Radeon running sometimes when I press a button or check a box and it only partially repaints or a button will press in and not pop back out again.  It looks terrible!  If I switch to battery power everything works fine.

I feel totally stuck.  I suspect a driver problem or flaw in DirectX on the card but the Radeon's drivers are up to date.

Any suggestions for fixes?    Is WPF really that sensitive to the graphics card and driver on modern PC's?   How do developers test and deploy WPF apps to minimize things like this?

(one example - from a textbook -  is pure XAML, basically no code behind, so I put the XAML file on a server:  http://pnart.com/temp/WPF_XAML_Example.xaml  - it works fine on 4 computers plus the Toshiba when it's on battery)

答: Yes, WPF depends on DirectX and therefore the graphics drivers. Try turning hardware acceleration off. If that fixes the problem, you know for sure it's a driver issue.</p>

Title: WPF graphics card problem


问:
Creating a Node NPM module in 9.2.0 to support older versions of Node
Now that Node 9.2.0 has all the new features of the language, how do I go about creating a node module that is backwards compatible with older versions?

If I have a small module that Node 9 supports out of the box, like this.

```<code>const {map} = require('lodash')

async function test (...args) {
    return map(args, (item) => {
        return `${item} yeah`
    })
}

module.exports = test
</code>```

Are there any was to use babel to transpile this for the specific backward version that I would need to support using babel env? Is there any way I can conditionally load those babel development dependencies, say installing this via Node 4 using post-install scripts?

答:
It seems like this is one solution one downside of which is it requires babel-runtime as a dep just in case, even if the current version of node doesn't need it. But in 9.2.0 the code above is the built code, it's simply moved by babel.

Here's an example package.json and on install it will build the src.

```<code>{
  "name": "example",
  "version": "1.0.0",
  "main": "lib/index.js",
  "scripts": {
    "build": "babel src -d lib",
    "postinstall": "npm run build"
  },
  "dependencies": {
    "babel-runtime": "^6.26.0",
    "lodash": "^4.17.4"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1"
  },
  "babel": {
    "plugins": [
      "transform-runtime"
    ],
    "presets": [
      [
        "env",
        {
          "targets": {
            "node": "current"
          }
        }
      ]
    ]
  }
}
</code>```

Body:
Now that Node 9.2.0 has all the new features of the language, how do I go about creating a node module that is backwards compatible with older versions?

If I have a small module that Node 9 supports out of the box, like this.

const {map} = require('lodash')

async function test (...args) {
    return map(args, (item) => {
        return `${item} yeah`
    })
}

module.exports = test

Are there any was to use babel to transpile this for the specific backward version that I would need to support using babel env? Is there any way I can conditionally load those babel development dependencies, say installing this via Node 4 using post-install scripts?

Body:
It seems like this is one solution one downside of which is it requires babel-runtime as a dep just in case, even if the current version of node doesn't need it. But in 9.2.0 the code above is the built code, it's simply moved by babel.

Here's an example package.json and on install it will build the src.

{
  "name": "example",
  "version": "1.0.0",
  "main": "lib/index.js",
  "scripts": {
    "build": "babel src -d lib",
    "postinstall": "npm run build"
  },
  "dependencies": {
    "babel-runtime": "^6.26.0",
    "lodash": "^4.17.4"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1"
  },
  "babel": {
    "plugins": [
      "transform-runtime"
    ],
    "presets": [
      [
        "env",
        {
          "targets": {
            "node": "current"
          }
        }
      ]
    ]
  }
}


问:
Error when run android app - ionic
I have a problem when I run the app... I want to test the location with GPS in my android phone but I can`t, ... it´s only that.

this is my ionic info

```<code>cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node  : v7.0.0
    npm   : 3.10.8
    OS    : macOS Sierra
    Xcode : Xcode 8.3.2 Build version 8E2002

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro
</code>```

l

```<code>ionic cordova run android --prod
</code>```

This is the error:

Error:

```<code>./src/app/main.ts
Module not found: Error: Can't resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
  using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app/app.module.ngfactory)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
      .ts
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json doesn't exist
      as directory
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
 @ ./src/app/main.ts 2:0-60
    at new BuildError (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:365:9)
</code>```

app.module.ts, I want to test the location but I can`t, there is the library for location and the service to call the webservice

```<code>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TestPage } from '../pages/test/test';

import { Geolocation } from '@ionic-native/geolocation';

import { MessageServiceProvider } from '../providers/message-service/message-service';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TestPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TestPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    MessageServiceProvider,
    Geolocation
  ]
})
export class AppModule {}
</code>```

So, I need your help ... what is the wrong? thanks a lot!

答:
Similiar issue is reported in angular CLI. Please try the following steps

Upgrade the angular CLI to latest version npm install @angular/cli and take the build

if it's still not working run npm i enhanced-resolve@3.3.0

Title: Error when run android app - ionic

Body:
I have a problem when I run the app... I want to test the location with GPS in my android phone but I can`t, ... it´s only that.

this is my ionic info

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.2
    Cordova Platforms  : android 6.2.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node  : v7.0.0
    npm   : 3.10.8
    OS    : macOS Sierra
    Xcode : Xcode 8.3.2 Build version 8E2002

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro

l

ionic cordova run android --prod

This is the error:

Error:

./src/app/main.ts
Module not found: Error: Can't resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
resolve './app.module.ngfactory' in '/Users/eliascanaza/Documents/www/ionic/yofood/src/app'
  using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app)
    using description file: /Users/eliascanaza/Documents/www/ionic/yofood/package.json (relative path: ./src/app/app.module.ngfactory)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
      .ts
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json doesn't exist
      as directory
        /Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory doesn't exist
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.ts]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.js]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory.json]
[/Users/eliascanaza/Documents/www/ionic/yofood/src/app/app.module.ngfactory]
 @ ./src/app/main.ts 2:0-60
    at new BuildError (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/eliascanaza/Documents/www/ionic/yofood/node_modules/webpack/lib/Compiler.js:365:9)

app.module.ts, I want to test the location but I can`t, there is the library for location and the service to call the webservice

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TestPage } from '../pages/test/test';

import { Geolocation } from '@ionic-native/geolocation';

import { MessageServiceProvider } from '../providers/message-service/message-service';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TestPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TestPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    MessageServiceProvider,
    Geolocation
  ]
})
export class AppModule {}

So, I need your help ... what is the wrong? thanks a lot!


问:
cannot find pthread.c in linux folder
I have downloaded kernel and the kernel resides in folder called Linux-2.6.32.28 in which I can find /Kernel/Kthread.c
I found Kthread.c but I cannot find pthread.c in Linux-2.6.32.28
I found Kthread.c in Linux-3.13/Kernel and Linux-4.7.2/Kernel

locate pthread.c finds file pthread.c in Computer/usr folder that comes when I install Ubuntu but pthread.c is not available in downloaded folders Linux-2.6.32.28, Linux-3.13, Linux-4.7.2

MORE: There are two sets of function calls. 1. System Calls 2. Library Calls.

For a computer to do any task it has to use hardware resources. So, how library calls differ from system calls?

System calls always use kernel which means hardware.
Library calls means no usage of kernel or hardware?

I know that library calls sometimes may resolve to system call.

What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources when compared with library calls and vice-versa.

Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?

答:
pthread is POSIX thread. It is a library that helps application to create threads in OS. Kthread in kernel source code is for kernel threads in linux.

POSIX is a standard defined by IEEE to maintain the compatibility between different OS.

So pthread source code cannot be seen in linux kernel source code.

you may refer this link for pthread source code http://www.gnu.org/software/hurd/libpthread.html

Title: cannot find pthread.c in linux folder


问:
Entity Framework - can't enable code first migration
I am having some trouble enabling code first migration following the Microsoft Data Developer procedure at http://msdn.microsoft.com/en-us/data/jj591621.aspx

I am using Visual Studio 2010 and targeting .NET Framework 4.0

I can run the following steps without error:

Create a new MigrationsDemo Console application

Add the latest version of the EntityFramework NuGet package to the project.

Tools –> Library Package Manager –> Package Manager Console

Run the Install-Package EntityFramework command (This installs Entity Framework 5)

However I receive an error when attempting to run the "Enable-Migrations" command in Package Manager Console:

Type is not resolved for member 'System.Data.Entity.Migrations.Design.ToolingFacade+GetContextTypeRunner,EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I would greatly appreciate any suggestions on what I can do to resolve this issue.

答:
<Private>True</Private>

For me, the above was missing from the assembly reference in the csproj file.

This means on build it isn't copied, and so cannot be seen.

```<code><Reference Include="Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=MSIL">
      <HintPath>..\packages\Oracle.ManagedDataAccess.12.2.1100\lib\net40\Oracle.ManagedDataAccess.dll</HintPath>
      <Private>True</Private>
</Reference>
</code>```

Body:
<Private>True</Private>

For me, the above was missing from the assembly reference in the csproj file.

This means on build it isn't copied, and so cannot be seen.

<Reference Include="Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=MSIL">
      <HintPath>..\packages\Oracle.ManagedDataAccess.12.2.1100\lib\net40\Oracle.ManagedDataAccess.dll</HintPath>
      <Private>True</Private>
</Reference>


问:
Understanding Numpy datatypes
While reading PyCUDA documentation, I found out i did  not understand how this code works

```<code>numpy.getbuffer(numpy.intp(int(self.data)))
</code>```

in theory it should return a pointer to float, while it receives self.data which is a pointer to an array of floats.

I am sure the question is simple, but after looking at more information about numpy.intp in books i did not find anything  that was of help.

答:
This is the source

https://documen.tician.de/pycuda/tutorial.html?highlight=getbuffer

```<code>class DoubleOpStruct:
    mem_size = 8 + numpy.intp(0).nbytes
    def __init__(self, array, struct_arr_ptr):
        self.data = cuda.to_device(array)
        self.shape, self.dtype = array.shape, array.dtype
        cuda.memcpy_htod(int(struct_arr_ptr), numpy.getbuffer(numpy.int32(array.size)))
        cuda.memcpy_htod(int(struct_arr_ptr) + 8, numpy.getbuffer(numpy.intp(int(self.data))))
    def __str__(self):
        return str(cuda.from_device(self.data, self.shape, self.dtype))

array1 = DoubleOpStruct(numpy.array([1, 2, 3], dtype=numpy.float32), struct_arr)
array2 = DoubleOpStruct(numpy.array([0, 4], dtype=numpy.float32), do2_ptr)
print("original arrays", array1, array2)
</code>```

While the inputs to the class at np.float32, it isn't obvious what cuda.to_device returns.  It can't be an array, otherwise int(self.data) wouldn't work. (and contrary to my first read of your question self.data is not the data buffer of self.  It may be related but it isn't a buffer object).

So the expression must be doing something like:

```<code>>>> np.intp(2432353)
2432353
>>> np.getbuffer(np.intp(2432353))
<read-only buffer for 0xb74d1150, size -1, offset 0 at 0xb71dfba0>

>>> np.arange(4.).data
<read-write buffer for 0xb71dda98, size 32, offset 0 at 0xb71df1c0>
</code>```

cuda.to_device maybe generating a number like the 'data' value of __array_interface__:

```<code>>>> np.arange(4.).__array_interface__['data']
(148454560, False)
>>> np.arange(4.).__array_interface__['data'][0]
148454560
>>> np.getbuffer(np.intp(int(_)))
<read-only buffer for 0xb74d1150, size -1, offset 0 at 0xb3a0c800>
</code>```

(as a side note, np.getbuffer does not exist in Py3 versions of numpy).

In any case I don't see any datatype games here.

Title: Understanding Numpy datatypes

Body:
While reading PyCUDA documentation, I found out i did  not understand how this code works

numpy.getbuffer(numpy.intp(int(self.data)))

in theory it should return a pointer to float, while it receives self.data which is a pointer to an array of floats.

I am sure the question is simple, but after looking at more information about numpy.intp in books i did not find anything  that was of help.

Body:
This is the source

https://documen.tician.de/pycuda/tutorial.html?highlight=getbuffer

class DoubleOpStruct:
    mem_size = 8 + numpy.intp(0).nbytes
    def __init__(self, array, struct_arr_ptr):
        self.data = cuda.to_device(array)
        self.shape, self.dtype = array.shape, array.dtype
        cuda.memcpy_htod(int(struct_arr_ptr), numpy.getbuffer(numpy.int32(array.size)))
        cuda.memcpy_htod(int(struct_arr_ptr) + 8, numpy.getbuffer(numpy.intp(int(self.data))))
    def __str__(self):
        return str(cuda.from_device(self.data, self.shape, self.dtype))

array1 = DoubleOpStruct(numpy.array([1, 2, 3], dtype=numpy.float32), struct_arr)
array2 = DoubleOpStruct(numpy.array([0, 4], dtype=numpy.float32), do2_ptr)
print("original arrays", array1, array2)

While the inputs to the class at np.float32, it isn't obvious what cuda.to_device returns.  It can't be an array, otherwise int(self.data) wouldn't work. (and contrary to my first read of your question self.data is not the data buffer of self.  It may be related but it isn't a buffer object).

So the expression must be doing something like:

>>> np.intp(2432353)
2432353
>>> np.getbuffer(np.intp(2432353))
<read-only buffer for 0xb74d1150, size -1, offset 0 at 0xb71dfba0>

>>> np.arange(4.).data
<read-write buffer for 0xb71dda98, size 32, offset 0 at 0xb71df1c0>

cuda.to_device maybe generating a number like the 'data' value of __array_interface__:

>>> np.arange(4.).__array_interface__['data']
(148454560, False)
>>> np.arange(4.).__array_interface__['data'][0]
148454560
>>> np.getbuffer(np.intp(int(_)))
<read-only buffer for 0xb74d1150, size -1, offset 0 at 0xb3a0c800>

(as a side note, np.getbuffer does not exist in Py3 versions of numpy).

In any case I don't see any datatype games here.


问:
more elegant xpath solution?
I am scraping a forum and am trying to retrieve stats about the post, specifically the number of views a post gets and the number of replies.

The page source for what I am parsing looks like this:

```<code><ul class="ipsDataItem_stats">
<li>
    <span class="ipsDataItem_stats_number">61</span>
    <span class="ipsDataItem_stats_type"> replies</span>
</li>
<li class="ipsType_light">
    <span class="ipsDataItem_stats_number">6,106</span>
    <span class="ipsDataItem_stats_type"> views</span>
</li>
</code>```

And I've hacked together some code that pulls what I'm looking for, but I'm wonder how you xpath experts would have handled this.

```<code>Stats = node.find_elements_by_xpath('.//ul[@class="ipsDataItem_stats"]')
Replies = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[0].text
Views = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[1].text
</code>```

My solution relies on the stats being in a certain order, and I'm wondering if there's a more accurate way to achieve the same result.

eg psuedo code:

```<code>Replies = node.find_elements_by_xpath({get span text where class = "ipsDataItem_stats" and sibling span class = "ipsDataItem_stats_type" and text = "replies"})
</code>```

答:
I'm looking for a way to more accurately obtain the elements I am
  after without relying on their position in a list.

The elements can be distinguished from each other by their class names

```<code><span class="ipsDataItem_stats_number">61</span>
<span class="ipsDataItem_stats_type"> replies</span>
</code>```

so use the bellow xpath expressions for the first element:

```<code>.//span[ contains( @class, 'stats_number')]
</code>```

and for the second element

```<code>.//span[ contains( @class, 'stats_type')]
</code>```

In this way the expressions will resist the change of the element's order.

Title: more elegant xpath solution?

Body:
I am scraping a forum and am trying to retrieve stats about the post, specifically the number of views a post gets and the number of replies.

The page source for what I am parsing looks like this:

    61
     replies

    6,106
     views

And I've hacked together some code that pulls what I'm looking for, but I'm wonder how you xpath experts would have handled this.

Stats = node.find_elements_by_xpath('.//ul[@class="ipsDataItem_stats"]')
Replies = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[0].text
Views = (Stats[0].find_elements_by_xpath('.//span[@class="ipsDataItem_stats_number"]'))[1].text

My solution relies on the stats being in a certain order, and I'm wondering if there's a more accurate way to achieve the same result.

eg psuedo code:

Replies = node.find_elements_by_xpath({get span text where class = "ipsDataItem_stats" and sibling span class = "ipsDataItem_stats_type" and text = "replies"})

Body:
I'm looking for a way to more accurately obtain the elements I am
  after without relying on their position in a list.

The elements can be distinguished from each other by their class names

<span class="ipsDataItem_stats_number">61</span>
<span class="ipsDataItem_stats_type"> replies</span>

so use the bellow xpath expressions for the first element:

.//span[ contains( @class, 'stats_number')]

and for the second element

.//span[ contains( @class, 'stats_type')]

In this way the expressions will resist the change of the element's order.


问:
App Getting Crash while Continuous open and close Activity between 2 activities
My Android App having multiple activities, now my problem is unable to findable.

A Activity have one recyclerView it get data from local database, If I click the items it will open B Activity, this same flow continuously then app getting crash(like open B Activity come back to A Activity and open again B activity- up to 5 to 6 time do same action then app getting crash)

The Crash message is related to SQLite DATABASE but unable to find where it occurs. Please help me... already spend more time for this...

Note: open DB on Oncreate and Close DB on OnDestroy in both activities

Error Message

```<code>E/SQLiteQuery: exception: unable to open database file (code 14); query: SELECT DISTINCT * FROM parameters WHERE inspection_no LIKE '%TEST-123%'
E/InputChannel-JNI: Error 24 dup channel fd 1023.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.testapp.testprocess, PID: 13078
                  java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
                      at android.view.InputChannel.nativeReadFromParcel(Native Method)
                      at android.view.InputChannel.readFromParcel(InputChannel.java:148)
                      at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:841)
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:640)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3518)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2733)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6121)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

答:
Try using Singleton pattern and access using db=DatabaseHelper.getInstance(context).It guarantees that only one database helper will exist across the entire application lifecycle.</p>

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

 private static DatabaseHelper sInstance;

 private static final String DATABASE_NAME = "database_name";
 private static final String DATABASE_TABLE = "table_name";
 private static final int DATABASE_VERSION = 1;

 public static synchronized DatabaseHelper getInstance(Context context) {

  // Use the application context, which will ensure that you
  // don't accidentally leak an Activity's context.
  if (sInstance == null) {
     sInstance = new DatabaseHelper(context.getApplicationContext());
  }
    return sInstance;
  }

  /**
    * Constructor should be private to prevent direct instantiation.
    * make call to static method "getInstance()" instead.
    */
     private DatabaseHelper(Context context) {
           super(context, DATABASE_NAME, null, DATABASE_VERSION);
     }
  }
</code>```

Body:
My Android App having multiple activities, now my problem is unable to findable.

A Activity have one recyclerView it get data from local database, If I click the items it will open B Activity, this same flow continuously then app getting crash(like open B Activity come back to A Activity and open again B activity- up to 5 to 6 time do same action then app getting crash)

The Crash message is related to SQLite DATABASE but unable to find where it occurs. Please help me... already spend more time for this...

Note: open DB on Oncreate and Close DB on OnDestroy in both activities

Error Message

E/SQLiteQuery: exception: unable to open database file (code 14); query: SELECT DISTINCT * FROM parameters WHERE inspection_no LIKE '%TEST-123%'
E/InputChannel-JNI: Error 24 dup channel fd 1023.
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.testapp.testprocess, PID: 13078
                  java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
                      at android.view.InputChannel.nativeReadFromParcel(Native Method)
                      at android.view.InputChannel.readFromParcel(InputChannel.java:148)
                      at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:841)
                      at android.view.ViewRootImpl.setView(ViewRootImpl.java:640)
                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3518)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2733)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6121)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Body:
Try using Singleton pattern and access using db=DatabaseHelper.getInstance(context).It guarantees that only one database helper will exist across the entire application lifecycle.

 public class DatabaseHelper extends SQLiteOpenHelper {

 private static DatabaseHelper sInstance;

 private static final String DATABASE_NAME = "database_name";
 private static final String DATABASE_TABLE = "table_name";
 private static final int DATABASE_VERSION = 1;

 public static synchronized DatabaseHelper getInstance(Context context) {

  // Use the application context, which will ensure that you
  // don't accidentally leak an Activity's context.
  if (sInstance == null) {
     sInstance = new DatabaseHelper(context.getApplicationContext());
  }
    return sInstance;
  }

  /**
    * Constructor should be private to prevent direct instantiation.
    * make call to static method "getInstance()" instead.
    */
     private DatabaseHelper(Context context) {
           super(context, DATABASE_NAME, null, DATABASE_VERSION);
     }
  }


问:
Angular http get no response from api
I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the  details of the object):

```<code>  0
 id "1"
 name   "Company-A21"
 address    "Gany-A11"
</code>```

If I want to see RAW data I get this:

```<code>[{"id":"1","name":"Company-A21","address":"Gany-A11"}]
</code>```

On the "other side" I am running apache2 and this HTML file:

```<code>    <!doctype html>
<html >
    <head>
        <title>Hello AngularJS</title>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello">
            <p>The ID is {{company.id}}</p>
            <p>The content is {{company.name}}</p>
        </div>
    </body>
</html>
</code>```

And the hello.js:

```<code>angular.module('demo', [])
.controller('Hello', function($scope, $http){

    $http.get('http://localhost:4567/api/v1/companies/2').
    then(function(response) {
            $scope.company = response.data;
    });
 });
</code>```

Why I can not see response?
I just started to practice Angular and I stuck here...

答:
Use ng-init to execute your get request. Implement your api call under a method:

```<code>angular.module('demo', [])
.controller('Hello', function($scope, $http){
    $scope.getCompany = function(){
       $http.get('http://localhost:4567/api/v1/companies/2').
         then(function(response) {
            $scope.company = response.data;
         });
       }
 });
</code>```

and use it in ng-init:

```<code>  <!doctype html>
<html >
    <head>
        <title>Hello AngularJS</title>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello" ng-init="getCompany()">
            <p>The ID is {{company.id}}</p>
            <p>The content is {{company.name}}</p>
        </div>
    </body>
</html>
</code>```

Title: Angular http get no response from api

Body:
I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the  details of the object):

  0
 id "1"
 name   "Company-A21"
 address    "Gany-A11"

If I want to see RAW data I get this:

[{"id":"1","name":"Company-A21","address":"Gany-A11"}]

On the "other side" I am running apache2 and this HTML file:

    <!doctype html>

        <title>Hello AngularJS</title>

The ID is {{company.id}}

The content is {{company.name}}

And the hello.js:

angular.module('demo', [])
.controller('Hello', function($scope, $http){

    $http.get('http://localhost:4567/api/v1/companies/2').
    then(function(response) {
            $scope.company = response.data;
    });
 });

Why I can not see response?
I just started to practice Angular and I stuck here...

Body:
Use ng-init to execute your get request. Implement your api call under a method:

angular.module('demo', [])
.controller('Hello', function($scope, $http){
    $scope.getCompany = function(){
       $http.get('http://localhost:4567/api/v1/companies/2').
         then(function(response) {
            $scope.company = response.data;
         });
       }
 });

and use it in ng-init:

  <!doctype html>
<html >
    <head>
        <title>Hello AngularJS</title>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello" ng-init="getCompany()">
            <p>The ID is {{company.id}}</p>
            <p>The content is {{company.name}}</p>
        </div>
    </body>
</html>


问:
$.getJSON returns undefined then returns requested data
I got myself stuck in a situation. I was coding a Wikipedia search tool for a personal practice project, but I've ran into a small error. When a user enters a word into the search bar, the input will be store into the data parameter of $.getJSON, then the response will return a array of title and description objects based on the word entered in the search bar. The $.getJSON function will display 5 sets of a title and it's description in a list format in the designated HTML. Simple enough, but the issue is the $.getJSON function will display the wording "undefined", then continue to display the required set of titles and descriptions. Below I have listed my JS coding for your viewing. Also, the full code can be viewed at my codepen.

Can anyone give me a heads up of what might be the issue. As $.getJSON is asynchronous, that might be the issue, but I can't quite put my finger on it. Thanks in advance!

```<code>$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
  event.preventDefault();
  var input = {search: $(this).val()};
  getWikiInfo(input);
}
});//search end

function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
  console.log(response);
  var wikipHtml;
  for(var i = 1; i < 6; i++) {
    wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
  }
  $("#list-container").html(wikipHtml);
  }
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end
</code>```

答:
This is happening because you are not initializing wikipHtml before appending to it, but I would strongly advise that you use proper DOM manipulation instead of building your HTML using string concatenation:

$("#search-word").on("keydown", function(event) {
  if (event.keyCode == 13) {
    event.preventDefault();
    var input = {
      search: $(this).val()
    };
    getWikiInfo(input);
  }
}); //search end

function getWikiInfo(input) {
  var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
  var getWikipHtml = function(response) {
    var content = [0, 1, 2, 3, 4, 5].map(function(i) {
      return $('
')
        .append($('
').text(response[1][i]))
        .append($('
').text(response[2][i]));
    });

    $("#list-container").html(content);
  }
  $.getJSON(wikipApi, input, getWikipHtml);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search-word' type='text' />
<div id='list-container'></div></code>```

Body:
I got myself stuck in a situation. I was coding a Wikipedia search tool for a personal practice project, but I've ran into a small error. When a user enters a word into the search bar, the input will be store into the data parameter of $.getJSON, then the response will return a array of title and description objects based on the word entered in the search bar. The $.getJSON function will display 5 sets of a title and it's description in a list format in the designated HTML. Simple enough, but the issue is the $.getJSON function will display the wording "undefined", then continue to display the required set of titles and descriptions. Below I have listed my JS coding for your viewing. Also, the full code can be viewed at my codepen.

Can anyone give me a heads up of what might be the issue. As $.getJSON is asynchronous, that might be the issue, but I can't quite put my finger on it. Thanks in advance!

$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
  event.preventDefault();
  var input = {search: $(this).val()};
  getWikiInfo(input);
}
});//search end

function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
  console.log(response);
  var wikipHtml;
  for(var i = 1; i < 6; i++) {
    wikipHtml += '

' + response[1][i] + '

' + response[2][i] + '

';
  }
  $("#list-container").html(wikipHtml);
  }
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end

Body:
This is happening because you are not initializing wikipHtml before appending to it, but I would strongly advise that you use proper DOM manipulation instead of building your HTML using string concatenation:

$("#search-word").on("keydown", function(event) {
  if (event.keyCode == 13) {
    event.preventDefault();
    var input = {
      search: $(this).val()
    };
    getWikiInfo(input);
  }
}); //search end

function getWikiInfo(input) {
  var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
  var getWikipHtml = function(response) {
    var content = [0, 1, 2, 3, 4, 5].map(function(i) {
      return $('<div class="list">')
        .append($('<h3>').text(response[1][i]))
        .append($('<p>').text(response[2][i]));
    });

    $("#list-container").html(content);
  }
  $.getJSON(wikipApi, input, getWikipHtml);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search-word' type='text' />
<div id='list-container'></div>


问:
How to stop motion in a Flatlist in react Native?
I would like to know if there is any possible way to stop the motion of the FlatList even if the user is not touching the screen. I just want to make the implemention like Facebook does in the feed news, I am currently using onEndReach  in order to fetch more data, but if the user scroll really fast the motion keep going and going, that's why I need to stop the motion when the final is reached.

答: There is a property that handle the motion when the user is scrolling and it is pagingEnabled which might help you on iOS version. But in my particular case it was a that in the FlatList there was a wrapper, and cause that weird behavior.


问:
Shutting down audio in a particular website
I tried to use the following mutationObserver to observe for all audio tags to remove them so to totally shut down sound in a particular website. I ran the script with Greasemonkey.

```<code>new MutationObserver(() => {
    document.querySelectorAll('audio').forEach(node=>node.remove())
}).observe(document, {subtree: true, childList: true});
</code>```

This wasn't enough, because some audio tags are loaded before the DOMContentLoaded.

What could I do to remove these audio tags as well (i.e, those loaded before being catched by the mutationObserver)?

I though of using setInterval() each 1 millisecond but this seems to me as something I really need to avoid as it would feel my PC's memory and stuck the browser.

Let me emphasize: It's just a script I ran on whatever website, so there is no HTML or CSS to show in this question.

答:
Not all audio is done with <audio> tags.  Audio can come from media elements not attached to the DOM.  It can also be produced with the Web Audio API, perhaps even in conjunction with the MediaDevice API.  Audio can also be produced by plugins.

You will need to write a browser extension and use the API for the particular browser you're extending to mute the tab.

Body:
I tried to use the following mutationObserver to observe for all audio tags to remove them so to totally shut down sound in a particular website. I ran the script with Greasemonkey.

new MutationObserver(() => {
    document.querySelectorAll('audio').forEach(node=>node.remove())
}).observe(document, {subtree: true, childList: true});

This wasn't enough, because some audio tags are loaded before the DOMContentLoaded.

What could I do to remove these audio tags as well (i.e, those loaded before being catched by the mutationObserver)?

I though of using setInterval() each 1 millisecond but this seems to me as something I really need to avoid as it would feel my PC's memory and stuck the browser.

Let me emphasize: It's just a script I ran on whatever website, so there is no HTML or CSS to show in this question.