问:
React Native and lodash: Node has not been attached to a view?
I'm getting this error "Node has not been attached to a view" when I'm trying to open a page in my application.

I've found out what the problem is related to, but I can't seem to find a solution...
This is the code that makes the error appear:

```<code>const mapStateToProps = state => {
    console.log("XXXXXXXXXXXXXXXXXXXXX");
    const adventures = state.adventures.localSavedAdventures;

    return {
        loading: state.adventures.loading,
        localSavedAdventures: _.map(adventures, (val, key) => { return { ...val, key } })
    };
}
</code>```

The "adventures" object is not empty, so that should not be a problem. I got this code to work on an other page, so I really don't get what's wrong here. Lodash is installed and imported correctly. Does anyone see the problem?

Here is a screenshot of the error

答: Okay so I found the error with some debugging (yes I should have done that earlier...). My object is in fact not always an object, but can also be a string. Thus lodash throws an error.</p>

Body:
I'm getting this error "Node has not been attached to a view" when I'm trying to open a page in my application.

I've found out what the problem is related to, but I can't seem to find a solution...
This is the code that makes the error appear:

const mapStateToProps = state => {
    console.log("XXXXXXXXXXXXXXXXXXXXX");
    const adventures = state.adventures.localSavedAdventures;

    return {
        loading: state.adventures.loading,
        localSavedAdventures: _.map(adventures, (val, key) => { return { ...val, key } })
    };
}

The "adventures" object is not empty, so that should not be a problem. I got this code to work on an other page, so I really don't get what's wrong here. Lodash is installed and imported correctly. Does anyone see the problem?

Here is a screenshot of the error


来源: stackexchange

问:
Trying to read a JSON file into a Map using Jackson
I have a JSON file with this structure...

```<code>{"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"}
{"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}
</code>```

which doesn't have a key or commas separating each object.  So when I use this code...

```<code>    File input = new File("test.json");
    ObjectMapper mapper = new ObjectMapper();
    Map obj = mapper.readValue(input, Map.class);
</code>```

the obj variable only has the first line in the json file which makes sense as it doesn't know what the key is.

I tried adding one by wrapping the objects like so...

```<code>{ "Key": [

    {"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"},
    {"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}
] }
</code>```

including adding the commas to separate each as the file did not have any commas to separate them.

While this works...

I have multiple json files that I have to work with

The file sizes are a bit big so it takes a long time to add they "Key" wrap like I did in the example.

I'm hoping to avoid this altogether but not sure if I can.  Is there a way to read the json file using the original format into a Map so I can then filter the data as needed?

答:
There is a simple solution that doesn't require file modification. Read your file line by line and then feed a single line to your ObjectMapper. You will get Many instances of Maps that you can store in a List, JsonArray or another map that you will need to create in your code. your code make look like:

```<code>ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object> list = new ArrayList<>()
try (
BufferedReader br = new BufferedReader(new FileReader(new File("test.json")))) {
String line;
while((line = br.readLine()) != null) {
  Map obj = mapper.readValue(line, Map.class);
  list.add(obj)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a JSON file with this structure...

{"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"}
{"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}

which doesn't have a key or commas separating each object.  So when I use this code...

    File input = new File("test.json");
    ObjectMapper mapper = new ObjectMapper();
    Map obj = mapper.readValue(input, Map.class);

the obj variable only has the first line in the json file which makes sense as it doesn't know what the key is.

I tried adding one by wrapping the objects like so...

{ "Key": [

    {"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"},
    {"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}
] }

including adding the commas to separate each as the file did not have any commas to separate them.

While this works...

I have multiple json files that I have to work with

The file sizes are a bit big so it takes a long time to add they "Key" wrap like I did in the example.

I'm hoping to avoid this altogether but not sure if I can.  Is there a way to read the json file using the original format into a Map so I can then filter the data as needed?

Body:
There is a simple solution that doesn't require file modification. Read your file line by line and then feed a single line to your ObjectMapper. You will get Many instances of Maps that you can store in a List, JsonArray or another map that you will need to create in your code. your code make look like:

ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object> list = new ArrayList<>()
try (
BufferedReader br = new BufferedReader(new FileReader(new File("test.json")))) {
String line;
while((line = br.readLine()) != null) {
  Map obj = mapper.readValue(line, Map.class);
  list.add(obj)
}


问:
Why is the first argument of reduce() returning undefined?
I'm trying to write a function that takes in an array as an input. If the integer is positive, it counts it. If the integer is negative, it sums it.

I figured that that the reduce() helper in js would be the best way to go about this, but I keep returning undefined for my first argument when it runs.

Here's my code:

```<code>function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0

    if (input === null || input === []){
      return [];
    } else {
      return input.reduce(function(prev,num){
      if (num > 0) {
      countPositive++;
      }else{
      sumNegative = prev + num};
      }, 0);
    }
    return [countPositive, sumNegative];
}
</code>```

It throws me a TypeError that says:

TypeError: Cannot read property '0' of undefined

When I log 'prev' to the console inside of the reduce function, it logs undefined for all inputs except the first one. The first one, as expected, is 0. But for each following input it logs undefined. Why is this happening?

Thanks in advance.

答:
Well sorry but this is not a good implementation of this function. But we can correct your function as follows;

function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0;

    if (input === null || input === []){
      return [];
    } else {
        sumNegative = input.reduce(function(prev,num){
                                     if (num > 0) {
                                       countPositive++;
                                     } else {
                                         prev += num;
                                       }
                                     return prev; // <---- THE MISSING PART
                                   }, 0);
      }
    return [countPositive, sumNegative];
}
var data = [1,2,3,4,5,-4,7,-3];
console.log(countPositivesSumNegatives(data));```
</div>
</div>
</p>

<p>However while the code works just fine it still involves many issues. When getting into functors like <code>.reduce()</code> you should be able to keep everthing contained within itself and should not refer to variables at the outer scope. Accordingly one can simply rephrase this code as follows;</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [1,2,3,4,5,-4,7,-3],
    cpsn = a => a.reduce((p,c) => c > 0 ? (p[0]++,p) : (p[1]+=c,p) ,[0,0]);
console.log(cpsn(data))</code>```

Body:
I'm trying to write a function that takes in an array as an input. If the integer is positive, it counts it. If the integer is negative, it sums it.

I figured that that the reduce() helper in js would be the best way to go about this, but I keep returning undefined for my first argument when it runs.

Here's my code:

function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0

    if (input === null || input === []){
      return [];
    } else {
      return input.reduce(function(prev,num){
      if (num > 0) {
      countPositive++;
      }else{
      sumNegative = prev + num};
      }, 0);
    }
    return [countPositive, sumNegative];
}

It throws me a TypeError that says:

TypeError: Cannot read property '0' of undefined

When I log 'prev' to the console inside of the reduce function, it logs undefined for all inputs except the first one. The first one, as expected, is 0. But for each following input it logs undefined. Why is this happening?

Thanks in advance.

Body:
Well sorry but this is not a good implementation of this function. But we can correct your function as follows;

function countPositivesSumNegatives(input) {
    let countPositive = 0;
    let sumNegative = 0;

    if (input === null || input === []){
      return [];
    } else {
        sumNegative = input.reduce(function(prev,num){
                                     if (num > 0) {
                                       countPositive++;
                                     } else {
                                         prev += num;
                                       }
                                     return prev; // <---- THE MISSING PART
                                   }, 0);
      }
    return [countPositive, sumNegative];
}
var data = [1,2,3,4,5,-4,7,-3];
console.log(countPositivesSumNegatives(data));

However while the code works just fine it still involves many issues. When getting into functors like .reduce() you should be able to keep everthing contained within itself and should not refer to variables at the outer scope. Accordingly one can simply rephrase this code as follows;

var data = [1,2,3,4,5,-4,7,-3],
    cpsn = a => a.reduce((p,c) => c > 0 ? (p[0]++,p) : (p[1]+=c,p) ,[0,0]);
console.log(cpsn(data))


问:
Dynamic Laravel Queue Connection
I have a 'proposal' table on my database, each proposal's row will generate a photo album (for all users) on certain time.

I set a queue to generate per photo album, so there's a thousand jobs in my jobs table at database.

to generate 1 photo album takes 4-10 seconds because there's an algorythm process.

I create 8 proposals, so the last photo album will take a long time to be generated, could someone have a solution for me?

Is there a way to create a multiple queue connection that run in the same time? lets say i have 5 proposal, so there's 5 queue connection, so each proposal has it's queue connection so the generate process will be done on time.

Thank you.

答:
The documentation mentions the Supervisor Configuration, and the example configuration has numprocs=8.

In this example, the numprocs directive will instruct Supervisor to run 8 queue:work processes [...]

It sounds like you're running with numprocs=1 which will only run one queue worker, thus only processing one job at a time.

Title: Dynamic Laravel Queue Connection


问:
How to make "gtk.gdk.pixbuf_new_from_file()" use a relative path?
In gtk.gdk.pixbuf_new_from_file(image), if "image" is not an absolute path, I get:

```<code>glib.GError: Failed to open file 'image.png': No such file or directory
</code>```

That's unless I'm in the directory where the image lives.

note1: I'm running Debian Squeeze, which uses Python 2.6 by default.

note2: The image and the script live in one directory.

答:
This is not specific to pixbuf_new_from_file, relative paths are always resolved relative to the current directory, which initially is the directory the script is started from.

You can get the directory the script is actually in with os.path.dirname(__file__). Then you can either make it your script's current directory with os.chdir, or you can use os.path.join to combine it with image.png.

ContentLicense: CC BY-SA 2.5

Body:
In gtk.gdk.pixbuf_new_from_file(image), if "image" is not an absolute path, I get:

glib.GError: Failed to open file 'image.png': No such file or directory

That's unless I'm in the directory where the image lives.

note1: I'm running Debian Squeeze, which uses Python 2.6 by default.

note2: The image and the script live in one directory.


问:
Explicit conversion from data type date to int is not allowed
I am trying to calculate AGE of contracts, however I am getting the error

Explicit conversion from data type date to int is not allowed

This is my code:

```<code>SELECT
    Contract_hist.*,
    IB.*,
    CAST((CASE
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT))/365 <= 0
                THEN 0
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365 > 0
                THEN (CAST(CONVERT(INT, Setup.[Start]) CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365
          END) AS INT) AS AGE
FROM
    Setup, Contract_hist
INNER JOIN
    IB ON Contract_hist.[System No] = IB.System_ID
</code>```

Where "Setup.[Start]" & "[IB].[Install_Date]" are datetime2 values.

答:
You could convert those datetime2 fields first to datetime, then to an int.

```<code>(convert(int, convert(datetime, Setup.[Start])) - convert(int,convert(datetime, [IB].[Install_Date])))/365
</code>```

But that can be shortened to:

```<code>cast(convert(datetime, Setup.[Start]) - convert(datetime, IB.[Install_Date]) as int)/365
</code>```

Or you could simplify it even more and calculate the difference in years directly with datediff:

```<code>datediff(year, [IB].[Install_Date], Setup.[Start])
</code>```

And that CASE can also be simplified:

```<code>case
when datediff(year, [IB].[Install_Date], Setup.[Start]) > 0
then datediff(year, [IB].[Install_Date], Setup.[Start])
else 0
end as AGE
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to calculate AGE of contracts, however I am getting the error

Explicit conversion from data type date to int is not allowed

This is my code:

SELECT
    Contract_hist.*,
    IB.*,
    CAST((CASE
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT))/365 <= 0
                THEN 0
             WHEN (CAST(CONVERT(INT, Setup.[Start]) - CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365 > 0
                THEN (CAST(CONVERT(INT, Setup.[Start]) CONVERT(INT,[IB].[Install_Date])) AS INT)) / 365
          END) AS INT) AS AGE
FROM
    Setup, Contract_hist
INNER JOIN
    IB ON Contract_hist.[System No] = IB.System_ID

Where "Setup.[Start]" & "[IB].[Install_Date]" are datetime2 values.

Body:
You could convert those datetime2 fields first to datetime, then to an int.

(convert(int, convert(datetime, Setup.[Start])) - convert(int,convert(datetime, [IB].[Install_Date])))/365

But that can be shortened to:

cast(convert(datetime, Setup.[Start]) - convert(datetime, IB.[Install_Date]) as int)/365

Or you could simplify it even more and calculate the difference in years directly with datediff:

datediff(year, [IB].[Install_Date], Setup.[Start])

And that CASE can also be simplified:

case
when datediff(year, [IB].[Install_Date], Setup.[Start]) > 0
then datediff(year, [IB].[Install_Date], Setup.[Start])
else 0
end as AGE


问:
Converting a byte array to a string back to a byte array
I'm currently doing an assignment and I have a byte array that I write onto a file.
I want to be able to get the byte array back out of the file by doing the reverse of what I did but I don't think I'm getting the right value back.

This is the code to write to the text file

```<code>PrintWriter fw = new PrintWriter(new BufferedWriter(new FileWriter("tc.txt",true)));
KeyPair keyPair = generateKeyPair();
byte[] publicKey = keyPair.getPublic().getEncoded();
byte[] privateKey = keyPair.getPrivate().getEncoded();
fw.println(email +" " + publicKey + " " + privateKey); //adds the site into the text file whcih contains all the blacklisted sites
fw.flush();
</code>```

And I try to get information back as a string and use .getBytes() to convert it back to a byte array like this

```<code>tempPublicKey = (blScanner.next()).getBytes();
</code>```

It doesn't seem to be right, does something happen in-between that is wrong?

答:
As you are writing arbitrary byte sequence to a text file, consider encoding your bytes to base64 format upon writing and decoding when you read this text file.

Text files are not suitable to store and retrieve arbitrary byte sequences, because some bytes may be recognized as formatting characters, etc, etc.

Encoding your bytes to base64 and decoding it back will preserve your byte sequence upon writing and reading to/from text file.

Body:
I'm currently doing an assignment and I have a byte array that I write onto a file.
I want to be able to get the byte array back out of the file by doing the reverse of what I did but I don't think I'm getting the right value back.

This is the code to write to the text file

PrintWriter fw = new PrintWriter(new BufferedWriter(new FileWriter("tc.txt",true)));
KeyPair keyPair = generateKeyPair();
byte[] publicKey = keyPair.getPublic().getEncoded();
byte[] privateKey = keyPair.getPrivate().getEncoded();
fw.println(email +" " + publicKey + " " + privateKey); //adds the site into the text file whcih contains all the blacklisted sites
fw.flush();

And I try to get information back as a string and use .getBytes() to convert it back to a byte array like this

tempPublicKey = (blScanner.next()).getBytes();

It doesn't seem to be right, does something happen in-between that is wrong?


问:
Telnet to a specific port on my ec2 instance
I need to telnet to my ec2 instance on port 2222. I have included it in the security groups with source as Anywhere and Custom TCP Rule. It is a 64 bit Linux Machine. I am able to connect via port 22 but when I try with 2222, it shows telnet: Unable to connect to remote host: Connection refused. Also I need to skip the login/password prompt if connected successfully.

答: Try changing the port the Telnet server is listening on in it's configuration file.</p>


问:
Image is not responsive inside carousel using ng2-bootstrap
Anybody know why is the image inside first carousel not responsive?
And how to make it responsive like the second one (Normal Bootstrap version) below. First one was created using ng2-bootstrap

Here is the html I have:

```<code><h1>ng2-bootstrap carousel</h1>
<carousel>
    <slide>
        <img class="first-slide" src="http://placehold.it/800x400" alt="First slide" class="center-block">
        <div class="container">
            <div class="carousel-caption">
                <h1>Example headline.</h1>
                <p>Descr1</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p>
            </div>
        </div>
    </slide>
    <slide>
        <img class="second-slide" src="http://placehold.it/800x400" alt="Second slide" class="center-block">
        <div class="container">
            <div class="carousel-caption">
                <h1>Another example headline.</h1>
                <p>Descr2.</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p>
            </div>
        </div>
    </slide>
</carousel>

<h1>Normal Bootstrap carousel</h1>

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner">
        <div class="item active">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
        <div class="item">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
        <div class="item">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
      </div>

      <!-- Controls -->
      <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
      </a>
      <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
      </a>
    </div>
</code>```

答:
For image response, Please add class img-responsive or add below code

```<code>display: block;
max-width: 100%;
height: auto;
</code>```

Body:
Anybody know why is the image inside first carousel not responsive?
And how to make it responsive like the second one (Normal Bootstrap version) below. First one was created using ng2-bootstrap

Here is the html I have:

ng2-bootstrap carousel

<carousel>
    <slide>

Example headline.

Descr1

Sign up today

    </slide>
    <slide>

Another example headline.

Descr2.

Learn more

    </slide>
</carousel>

Normal Bootstrap carousel

Heading

Heading

Heading

Body:
For image response, Please add class img-responsive or add below code

display: block;
max-width: 100%;
height: auto;


问:
Form submit add domain to username field if missing
I have a login form that includes a username and password field.

Users will be able to login using:

Domain\username
And
Username@domain.org.uk

However many users attempt to login using just 'username'

I want to help users by adding domain\ or @domain.org.uk to there username when they enter just 'username', when they click the login button I want to add the domain part of the username.

How can I do this in pure JavaScript?

答:
```<code>function insertDomain (){
 var txtBox = document.getElementById('Your_Textbox');

if(txtBox.value.indexOf("@") == -1)
{
   txtBox.value += "@domain.org.uk";
}

}
</code>```

On Submit: http://alexking.org/blog/2003/10/01/javascript-onsubmit-handler

Body:
function insertDomain (){
 var txtBox = document.getElementById('Your_Textbox');

if(txtBox.value.indexOf("@") == -1)
{
   txtBox.value += "@domain.org.uk";
}

}

On Submit: http://alexking.org/blog/2003/10/01/javascript-onsubmit-handler


问:
ImageButton inside of GridView not clickable
Here is my code for dynamically creating ImageButtons inside of gridviews. When I run the activity, the ImageButtons are not clickable. I tried adding
 android:descendantFocusability="blocksDescendants"
to the xml file but this did not fix the problem.

EDIT: I updated the adapter to be for ImageViews, not ImageButtons, but the problem persists.

Here is my custom adapter:

```<code>    package com.example.myname.myproject;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;

/**
 * Created by myname on 3/31/17.
 */

public class ImageArrayAdapter extends BaseAdapter {
    Context context;
    int[] currentResources;
    String[] currentIcons;

    public ImageArrayAdapter(Context context, String[] currentIcons, int[] currentResources){
        ImageArrayAdapter.this.context = context;
        ImageArrayAdapter.this.currentIcons = currentIcons;
        ImageArrayAdapter.this.currentResources = currentResources;
    }

    @Override
    public int getCount() {
        return currentResources.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setBackgroundColor(Color.TRANSPARENT);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setClickable(true);
        imageView.setImageResource(currentResources[position]);
        return imageView;
    }

}
</code>```

Here is my xml file for the GridView.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myname.myproject.AdminControlTabbed$PlaceholderFragment">

<GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:clickable="true"
    android:descendantFocusability="blocksDescendants"
    />
</code>```

Thanks for the help.

答: Activity.dispatchTouchEvent(MotionEvent) dispach it to other listeners

Body:
Here is my code for dynamically creating ImageButtons inside of gridviews. When I run the activity, the ImageButtons are not clickable. I tried adding
 android:descendantFocusability="blocksDescendants"
to the xml file but this did not fix the problem.

EDIT: I updated the adapter to be for ImageViews, not ImageButtons, but the problem persists.

Here is my custom adapter:

    package com.example.myname.myproject;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;

/**
 * Created by myname on 3/31/17.
 */

public class ImageArrayAdapter extends BaseAdapter {
    Context context;
    int[] currentResources;
    String[] currentIcons;

    public ImageArrayAdapter(Context context, String[] currentIcons, int[] currentResources){
        ImageArrayAdapter.this.context = context;
        ImageArrayAdapter.this.currentIcons = currentIcons;
        ImageArrayAdapter.this.currentResources = currentResources;
    }

    @Override
    public int getCount() {
        return currentResources.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setBackgroundColor(Color.TRANSPARENT);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setClickable(true);
        imageView.setImageResource(currentResources[position]);
        return imageView;
    }

}

Here is my xml file for the GridView.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myname.myproject.AdminControlTabbed$PlaceholderFragment">

<GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:clickable="true"
    android:descendantFocusability="blocksDescendants"
    />

Thanks for the help.


问:
Pushing five object pointers in one scope, then checking if the bool of the object is false, gives an error
I am working on a game for my University project and came across a problem with pointers. I have a vector of bullets that has every bullet checked for collisions. But, when I try to spawn 5 bullets at once (shotgun shot), it spawns everything correctly, then I go through the vector and check if the bullet is alive. For some reason it finds a NULL pointer or a corrupted data of a pointer. Would be really appreciated if someone knew how to fix this. Thanks!

Bullet check:

```<code>void Bullet::checkOutOfRange()
{
    if(type == "enemy_bullet")
    {
        if(body->GetPosition().x <= -10.0f)
        {
            alive = false;
        }
    }
    // checks if the body is out of the window size
    else if (body->GetPosition().x > 510.0f || body->GetPosition().x < -10.0f || body->GetPosition().y > 291.0f || body->GetPosition().y < -10)
    {
        alive = false;
    }
}
</code>```

Bullet collision detection:

```<code>class MyContactListener : public b2ContactListener
{
    void BeginContact(b2Contact* contact) override
    {
        if (contact && contact->IsTouching())
        {
            Entity* A = static_cast<Entity*>(contact->GetFixtureA()->GetBody()->GetUserData());
            Entity* B = static_cast<Entity*>(contact->GetFixtureB()->GetBody()->GetUserData());

            //------
            if((A->type == "player_bullet" && B->type == "enemy") || (A->type == "enemy" && B->type == "player_bullet"))
            {
                Bullet *bullet = nullptr;
                Enemy *other = nullptr;
                if (A->type == "player_bullet" && B->type == "enemy")
                {
                    bullet = dynamic_cast<Bullet*>(A);
                    other = dynamic_cast<Enemy*>(B);
                }
                else if (A->type == "enemy" && B->type == "player_bullet")
                {
                    bullet = dynamic_cast<Bullet*>(B);
                    other = dynamic_cast<Enemy*>(A);
                }
                if ((A && B) || (B&&A))
                {
                    other->bodySprite.set_animation("death");
                    bullet->alive = false;
                    other->alive = false;
                }
            }
        }
    }
}
</code>```

Bullet check in game:

```<code>    for (auto itr = player_bullets.begin(), itrEnd = player_bullets.end(); itr != itrEnd; ++itr)
    {
        (*itr)->checkOutOfRange(); // go to declaration to see where the bullets stop
        (*itr)->bodySprite.set_position((*itr)->body->GetPosition().x, (*itr)->body->GetPosition().y);
        (*itr)->bodySprite.set_rotation((*itr)->bulletDir * 180 / PI);
        (*itr)->moveBullet(20.0f);
        if ((*itr)->alive == false)
        {
            input_world->DestroyBody((*itr)->body);
            delete *itr;
            itr = player_bullets.erase(itr);
        }
    }
</code>```

Shotgun shot spawn:

```<code>void spawnShotgunShot(float x, float y, float dir, b2World *world)
{
    // maybe bad pointer management?
    Bullet *bullet_ptr1 = new Bullet(x, y, dir, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr1);
    Bullet *bullet_ptr2 = new Bullet(x, y, dir + 0.5, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr2);
    Bullet *bullet_ptr3 = new Bullet(x, y, dir + 0.25, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr3);
    Bullet *bullet_ptr4 = new Bullet(x, y, dir - 0.5, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr4);
    Bullet *bullet_ptr5 = new Bullet(x, y, dir - 0.25, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr5);
}
</code>```

And here is a testbuild with the sln in it:
Link to testbuild

答:
Your problem is your itrEnd variable in the loop that checks the bullets.  You initialize it to player_bullets.end() at the beginning of the loop, then then check itr != itrEnd as the loop condition.  But when you erase a bullet from the vector, that invalidates iterators after the one that was erased, including the end iterator.  You're continuing to use the vector's original end iterator, instead of its new one based on its smaller size.

Remove the itrEnd variable and just check itr != player_bullets.end() as the loop condition.  That'll ensure that you're always using the "current" end iterator, even when it changes due to elements being erased.

On a related note, when you erase an element from the vector, the iterator that you get back from the erase call is for the element after the one that was erased.  At the beginning of the next iteration, the loop's ++itr will advance past that element before checking the loop condition again.  That means that whenever you remove a bullet from the vector, your loop will "skip" the bullet after it.  If the last bullet gets removed, the loop will "skip" the end iterator and continue iterating past the end of the vector.

See this SO question for information on how to fix that.

Body:
I am working on a game for my University project and came across a problem with pointers. I have a vector of bullets that has every bullet checked for collisions. But, when I try to spawn 5 bullets at once (shotgun shot), it spawns everything correctly, then I go through the vector and check if the bullet is alive. For some reason it finds a NULL pointer or a corrupted data of a pointer. Would be really appreciated if someone knew how to fix this. Thanks!

Bullet check:

void Bullet::checkOutOfRange()
{
    if(type == "enemy_bullet")
    {
        if(body->GetPosition().x <= -10.0f)
        {
            alive = false;
        }
    }
    // checks if the body is out of the window size
    else if (body->GetPosition().x > 510.0f || body->GetPosition().x < -10.0f || body->GetPosition().y > 291.0f || body->GetPosition().y < -10)
    {
        alive = false;
    }
}

Bullet collision detection:

class MyContactListener : public b2ContactListener
{
    void BeginContact(b2Contact* contact) override
    {
        if (contact && contact->IsTouching())
        {
            Entity* A = static_cast<Entity*>(contact->GetFixtureA()->GetBody()->GetUserData());
            Entity* B = static_cast<Entity*>(contact->GetFixtureB()->GetBody()->GetUserData());

            //------
            if((A->type == "player_bullet" && B->type == "enemy") || (A->type == "enemy" && B->type == "player_bullet"))
            {
                Bullet *bullet = nullptr;
                Enemy *other = nullptr;
                if (A->type == "player_bullet" && B->type == "enemy")
                {
                    bullet = dynamic_cast<Bullet*>(A);
                    other = dynamic_cast<Enemy*>(B);
                }
                else if (A->type == "enemy" && B->type == "player_bullet")
                {
                    bullet = dynamic_cast<Bullet*>(B);
                    other = dynamic_cast<Enemy*>(A);
                }
                if ((A && B) || (B&&A))
                {
                    other->bodySprite.set_animation("death");
                    bullet->alive = false;
                    other->alive = false;
                }
            }
        }
    }
}

Bullet check in game:

    for (auto itr = player_bullets.begin(), itrEnd = player_bullets.end(); itr != itrEnd; ++itr)
    {
        (*itr)->checkOutOfRange(); // go to declaration to see where the bullets stop
        (*itr)->bodySprite.set_position((*itr)->body->GetPosition().x, (*itr)->body->GetPosition().y);
        (*itr)->bodySprite.set_rotation((*itr)->bulletDir * 180 / PI);
        (*itr)->moveBullet(20.0f);
        if ((*itr)->alive == false)
        {
            input_world->DestroyBody((*itr)->body);
            delete *itr;
            itr = player_bullets.erase(itr);
        }
    }

Shotgun shot spawn:

void spawnShotgunShot(float x, float y, float dir, b2World *world)
{
    // maybe bad pointer management?
    Bullet *bullet_ptr1 = new Bullet(x, y, dir, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr1);
    Bullet *bullet_ptr2 = new Bullet(x, y, dir + 0.5, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr2);
    Bullet *bullet_ptr3 = new Bullet(x, y, dir + 0.25, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr3);
    Bullet *bullet_ptr4 = new Bullet(x, y, dir - 0.5, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr4);
    Bullet *bullet_ptr5 = new Bullet(x, y, dir - 0.25, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr5);
}

And here is a testbuild with the sln in it:
Link to testbuild


问:
How do I initialize a collection of a record set, when each property for a record set is in separate .txt file C#
I apologize for a confusing title, that's the only way I knew to explain the situation I'm dealing in a title.

I have a record set which contains properties for sesmic activity data. To give an example, it contains fields like iris ID, longitude, latitude, magnitude and many others. I'm given separate .txt files for these fields which contain 600 entries of that particular data.

Now, what I have done so far is created another class which will be basically collection of the recordSet in a form of a list.

Where I have trouble is basically figuring out how to go about a method which will allow me to initialize the list of the record sets with data from files that are each separate.

This is how my method looks so far:

答:
You can do it in this manner...</p>

```<code>public void iniSets(int dataSet)
{
  DirectoryInfo dataColumns = new DirectoryInfo(@"SesmicData\");//Assuming Test is your Folder
  FileInfo[] Files = dataColumns.GetFiles($"*{dataSet}.txt"); //Getting Text files
  foreach (FileInfo file in Files)
  {
    using (StreamReader sr = new StreamReader(file.FullName))
    {
      string line;
      while ((line = sr.ReadLine()) != null)
      {
        if (file.Name.StartsWith("column_a"))
        {
          // parse column A data per data type and store where it needs to be stored
        }
        else if (file.Name.StartsWith("column_b"))
        {
          // parse column B data per data type and store where it needs to be stored
        }
      }
    }
  }
}
</code>```

Body:
You can do it in this manner...

public void iniSets(int dataSet)
{
  DirectoryInfo dataColumns = new DirectoryInfo(@"SesmicData\");//Assuming Test is your Folder
  FileInfo[] Files = dataColumns.GetFiles($"*{dataSet}.txt"); //Getting Text files
  foreach (FileInfo file in Files)
  {
    using (StreamReader sr = new StreamReader(file.FullName))
    {
      string line;
      while ((line = sr.ReadLine()) != null)
      {
        if (file.Name.StartsWith("column_a"))
        {
          // parse column A data per data type and store where it needs to be stored
        }
        else if (file.Name.StartsWith("column_b"))
        {
          // parse column B data per data type and store where it needs to be stored
        }
      }
    }
  }
}


问:
xaml how center text in a templated button
I am not able to center text in the templated button. "OK" stays at bottom center or even goes bellow the button border.</p>

```<code> <Window.Resources>
    <ControlTemplate x:Key="BT_Kids" TargetType="{x:Type Button}">
        <Grid>
            <Ellipse HorizontalAlignment="Left" Height="44.8" Stroke="Black" VerticalAlignment="Top" Width="71.2">
                <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="#FF4363EA" Offset="1"/>
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
            <Viewbox>
                <ContentControl Margin="10" Content="{TemplateBinding Content}"/>
            </Viewbox>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<Grid Margin="0,0,0,2.4">

    <Button
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Width="75" Margin="189.6,24.6,0,0"
            Template="{DynamicResource BT_Kids}"  FontSize="15">OK</Button>

</Grid>
</code>```

答:
Remove the ViewBox, adjust the FontSize of the Button and set the HorizontalAlignment and VerticalAlignment properties of the ContentPresenter to Center:

```<code><ControlTemplate x:Key="BT_Kids" TargetType="{x:Type Button}">
    <Grid>
        <Ellipse HorizontalAlignment="Left" Height="44.8" Stroke="Black" VerticalAlignment="Top" Width="71.2">
            <Ellipse.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="#FF4363EA" Offset="1"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
        </Ellipse>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>

<Button
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Width="75" Margin="189.6,24.6,0,0"
        HorizontalContentAlignment="Center"
        VerticalContentAlignment="Center"
        Template="{DynamicResource BT_Kids}" FontSize="30">OK</Button>
</code>```

It makes no sense to put the content in a ViewBox when the Ellipse has a fixed size.

Body:
I am not able to center text in the templated button. "OK" stays at bottom center or even goes bellow the button border.

 <Window.Resources>
    <ControlTemplate x:Key="BT_Kids" TargetType="{x:Type Button}">
        <Grid>
            <Ellipse HorizontalAlignment="Left" Height="44.8" Stroke="Black" VerticalAlignment="Top" Width="71.2">
                <Ellipse.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="#FF4363EA" Offset="1"/>
                    </LinearGradientBrush>
                </Ellipse.Fill>
            </Ellipse>
            <Viewbox>
                <ContentControl Margin="10" Content="{TemplateBinding Content}"/>
            </Viewbox>
        </Grid>
    </ControlTemplate>
</Window.Resources>
<Grid Margin="0,0,0,2.4">

    <Button
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Width="75" Margin="189.6,24.6,0,0"
            Template="{DynamicResource BT_Kids}"  FontSize="15">OK</Button>

</Grid>

Body:
Remove the ViewBox, adjust the FontSize of the Button and set the HorizontalAlignment and VerticalAlignment properties of the ContentPresenter to Center:

<ControlTemplate x:Key="BT_Kids" TargetType="{x:Type Button}">
    <Grid>
        <Ellipse HorizontalAlignment="Left" Height="44.8" Stroke="Black" VerticalAlignment="Top" Width="71.2">
            <Ellipse.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="#FF4363EA" Offset="1"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
        </Ellipse>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</ControlTemplate>

<Button
        HorizontalAlignment="Left"
        VerticalAlignment="Top"
        Width="75" Margin="189.6,24.6,0,0"
        HorizontalContentAlignment="Center"
        VerticalContentAlignment="Center"
        Template="{DynamicResource BT_Kids}" FontSize="30">OK</Button>

It makes no sense to put the content in a ViewBox when the Ellipse has a fixed size.


问:
javax.persistence.NoResultException: No entity found for query JPQL Query
```<code>@Entity
@Table(name = "ways", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "gid"))
public class Ways implements java.io.Serializable {
private WaysId id;

public Ways() {
}

public Ways(WaysId id) {
    this.id = id;
}

@EmbeddedId
@AttributeOverrides({
        @AttributeOverride(name = "gid", column = @Column(name = "gid", unique = true)),
        @AttributeOverride(name = "classId", column = @Column(name = "class_id", nullable = false)),
        @AttributeOverride(name = "length", column = @Column(name = "length", precision = 17, scale = 17)),
        @AttributeOverride(name = "name", column = @Column(name = "name")),
        @AttributeOverride(name = "x1", column = @Column(name = "x1", precision = 17, scale = 17)),
        @AttributeOverride(name = "y1", column = @Column(name = "y1", precision = 17, scale = 17)),
        @AttributeOverride(name = "x2", column = @Column(name = "x2", precision = 17, scale = 17)),
        @AttributeOverride(name = "y2", column = @Column(name = "y2", precision = 17, scale = 17)),
        @AttributeOverride(name = "reverseCost", column = @Column(name = "reverse_cost", precision = 17, scale = 17)),
        @AttributeOverride(name = "rule", column = @Column(name = "rule")),
        @AttributeOverride(name = "toCost", column = @Column(name = "to_cost", precision = 17, scale = 17)),
        @AttributeOverride(name = "maxspeedForward", column = @Column(name = "maxspeed_forward")),
        @AttributeOverride(name = "maxspeedBackward", column = @Column(name = "maxspeed_backward")),
        @AttributeOverride(name = "osmId", column = @Column(name = "osm_id")),
        @AttributeOverride(name = "priority", column = @Column(name = "priority", precision = 17, scale = 17)),
        @AttributeOverride(name = "theGeom", column = @Column(name = "the_geom")),
        @AttributeOverride(name = "source", column = @Column(name = "source")),
        @AttributeOverride(name = "target", column = @Column(name = "target"))})
        //@AttributeOverride(name = "vitesse", column = @Column(name = "vitesse", precision = 17, scale = 17))})
public WaysId getId() {
    return this.id;
}

public void setId(WaysId id) {
    this.id = id;
}

}
@Embeddable
public class WaysId implements java.io.Serializable {

private Integer gid;
private int classId;
private Double length;
private String name;
private Double x1;
private Double y1;
private Double x2;
private Double y2;
private Double reverseCost;
private String rule;
private Double toCost;
private Integer maxspeedForward;
private Integer maxspeedBackward;
private Long osmId;
private Double priority;
private Serializable theGeom;
private Integer source;
private Integer target;
}

public double convertidTolat1(Integer id) {
    Double lat = null;
    Query query = entityManager
            .createQuery("select n.id.x1 from Ways n where n.id.gid=:id");
    query.setParameter("id", id);
    lat = (Double) query.getSingleResult();
    return lat;
}

@GET
@Path("lat/{id}")
@Produces(MediaType.APPLICATION_JSON)
public BigDecimal getlat(@PathParam(value = "id") long id) {
    BigDecimal d = iservices.getLat(id);
    return d;
}
</code>```

Hi every body, here is my code, i want to know what's wrong with my query?

答:
I prefer to do this

```<code>public class BwJpaResultHelper {
public static Object getSingleResultOrNull(Query query){
    List results = query.getResultList();
    if (results.isEmpty()) return null;
    else if (results.size() == 1) return results.get(0);
    throw new NonUniqueResultException(results.size());
}
</code>```

}

Body:
@Entity
@Table(name = "ways", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = "gid"))
public class Ways implements java.io.Serializable {
private WaysId id;

public Ways() {
}

public Ways(WaysId id) {
    this.id = id;
}

@EmbeddedId
@AttributeOverrides({
        @AttributeOverride(name = "gid", column = @Column(name = "gid", unique = true)),
        @AttributeOverride(name = "classId", column = @Column(name = "class_id", nullable = false)),
        @AttributeOverride(name = "length", column = @Column(name = "length", precision = 17, scale = 17)),
        @AttributeOverride(name = "name", column = @Column(name = "name")),
        @AttributeOverride(name = "x1", column = @Column(name = "x1", precision = 17, scale = 17)),
        @AttributeOverride(name = "y1", column = @Column(name = "y1", precision = 17, scale = 17)),
        @AttributeOverride(name = "x2", column = @Column(name = "x2", precision = 17, scale = 17)),
        @AttributeOverride(name = "y2", column = @Column(name = "y2", precision = 17, scale = 17)),
        @AttributeOverride(name = "reverseCost", column = @Column(name = "reverse_cost", precision = 17, scale = 17)),
        @AttributeOverride(name = "rule", column = @Column(name = "rule")),
        @AttributeOverride(name = "toCost", column = @Column(name = "to_cost", precision = 17, scale = 17)),
        @AttributeOverride(name = "maxspeedForward", column = @Column(name = "maxspeed_forward")),
        @AttributeOverride(name = "maxspeedBackward", column = @Column(name = "maxspeed_backward")),
        @AttributeOverride(name = "osmId", column = @Column(name = "osm_id")),
        @AttributeOverride(name = "priority", column = @Column(name = "priority", precision = 17, scale = 17)),
        @AttributeOverride(name = "theGeom", column = @Column(name = "the_geom")),
        @AttributeOverride(name = "source", column = @Column(name = "source")),
        @AttributeOverride(name = "target", column = @Column(name = "target"))})
        //@AttributeOverride(name = "vitesse", column = @Column(name = "vitesse", precision = 17, scale = 17))})
public WaysId getId() {
    return this.id;
}

public void setId(WaysId id) {
    this.id = id;
}

}
@Embeddable
public class WaysId implements java.io.Serializable {

private Integer gid;
private int classId;
private Double length;
private String name;
private Double x1;
private Double y1;
private Double x2;
private Double y2;
private Double reverseCost;
private String rule;
private Double toCost;
private Integer maxspeedForward;
private Integer maxspeedBackward;
private Long osmId;
private Double priority;
private Serializable theGeom;
private Integer source;
private Integer target;
}

public double convertidTolat1(Integer id) {
    Double lat = null;
    Query query = entityManager
            .createQuery("select n.id.x1 from Ways n where n.id.gid=:id");
    query.setParameter("id", id);
    lat = (Double) query.getSingleResult();
    return lat;
}

@GET
@Path("lat/{id}")
@Produces(MediaType.APPLICATION_JSON)
public BigDecimal getlat(@PathParam(value = "id") long id) {
    BigDecimal d = iservices.getLat(id);
    return d;
}

Hi every body, here is my code, i want to know what's wrong with my query?

Body:
I prefer to do this

public class BwJpaResultHelper {
public static Object getSingleResultOrNull(Query query){
    List results = query.getResultList();
    if (results.isEmpty()) return null;
    else if (results.size() == 1) return results.get(0);
    throw new NonUniqueResultException(results.size());
}

}


问:
How to get the two pop up windows at a time using jquery?
How to create two pop up windows at the same time after clicking the anchor tag

```<code>$("body").on("click", ".tasks_link", function() {

  var file_number = $(this).attr("file_number");

  var pop_up_link = 'file_history.php?file_number=' + file_number;

  var pop_up_link1 = 'change_file.php?file_number=' + file_number;

  window.open(pop_up_link, "_target", "toolbar=no, resizable=yes, top=100, left=150, width=1100, height=500");

  window.open(pop_up_link1, "_target", "toolbar=no, resizable=yes, top=100, left=150, width=1100, height=500");

});
</code>```

I tried this , but I am getting only one pop up window that is change_file.php . I'm not getting the first pop up window. How to get the two pop up windows at a time?

答:
Your code is fine.

What is happening is your browser blocking the second pop-up. In Chrome, look at the right of the address bar, there should be a "popups blocked" icon/notification

The problem is the second argument for window.open- It has to be a unique name otherwise it reopens the new page in the existing popup. See this quote from MDN docs:

If a window with the name already exists, then strUrl is loaded into
  the existing window. In this case the return value of the method is
  the existing window and strWindowFeatures is ignored. Providing an
  empty string for strUrl is a way to get a reference to an open window
  by its name without changing the window's location. To open a new
  window on every call of window.open(), use the special value _blank
  for strWindowName.

Body:
How to create two pop up windows at the same time after clicking the anchor tag

$("body").on("click", ".tasks_link", function() {

  var file_number = $(this).attr("file_number");

  var pop_up_link = 'file_history.php?file_number=' + file_number;

  var pop_up_link1 = 'change_file.php?file_number=' + file_number;

  window.open(pop_up_link, "_target", "toolbar=no, resizable=yes, top=100, left=150, width=1100, height=500");

  window.open(pop_up_link1, "_target", "toolbar=no, resizable=yes, top=100, left=150, width=1100, height=500");

});

I tried this , but I am getting only one pop up window that is change_file.php . I'm not getting the first pop up window. How to get the two pop up windows at a time?


问:
Regex in Python?
I have a string:

```<code>line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
</code>```

I want to get this result:

```<code>[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]
</code>```

I tried this:

```<code>match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)
</code>```

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

答:
You can use the following regex:

```<code>([fh]t*ps?|file):[\\/]*(.*?)(?=:|)(\d+|(?=[\\\/]))
</code>```

Tested on Regex101:

https://regex101.com/r/hCprgS/3

Try this code:

```<code>import re

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,\file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
match = re.findall("([fh]t*ps?|file):[\\/]*(.*?)(?=:|)(\d+|(?=[\\\/]))", line)

print(match)
</code>```

Results:

```<code>[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('http', 'v2-dbwebb.se', '')]
</code>```

Title: Regex in Python?

Body:
I have a string:

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg, file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"

I want to get this result:

[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('file', 'localhost', '8585'), ('http', 'v2-dbwebb.se', '')]

I tried this:

match = re.findall("(^[a-z]+[^://](^[a-z]+\d))", line)

I'm a beginner in Python.  If there is somebody who can explain, it would be very nice :D

Body:
You can use the following regex:

([fh]t*ps?|file):[\\/]*(.*?)(?=:|)(\d+|(?=[\\\/]))

Tested on Regex101:

https://regex101.com/r/hCprgS/3

Try this code:

import re

line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,\file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack"
match = re.findall("([fh]t*ps?|file):[\\/]*(.*?)(?=:|)(\d+|(?=[\\\/]))", line)

print(match)

Results:

[('https', 'dbwebb.se', ''), ('ftp', 'bth.com', '32'), ('http', 'v2-dbwebb.se', '')]


问:
Why does std::apply fail with a generic function?
Taken from cppreference, why does the call to std::apply(add_generic, ...) fail to compile? Is there a way to fix it?

```<code>#include <iostream>
#include <tuple>

int add(int first, int second)
{
    return first + second;
}

template<typename T>
T add_generic(T first, T second)
{
    return first + second;
}

int main()
{
    std::cout << std::apply(add, std::make_tuple(1,2)) << '\n';

    // template argument deduction/substitution fails
    std::cout << std::apply(add_generic, std::make_tuple(2.0f,3.0f)) << '\n';
}
</code>```

It fails with error:

[x86-64 gcc 7 (snapshot)] error: no matching function for call to
  'apply(, std::tuple)' [x86-64 gcc 7 (snapshot)] note:   couldn't deduce template
  parameter '_Fn'

答:
This is not new in C++17. Just from the signature of std::apply, there is no telling whether you want to pass add_generic<int>, add_generic<float>, add_generic<std::string>, or anything else. Knowing that requires more context (specifically: it requires knowing how std::apply is going to invoke it), but that information isn't available at the call site and so cannot be used for template argument deduction.

It's possible to work around that by passing one object, and making that one object capable of calling whichever instantiation of add_generic is needed:

```<code>std::cout << std::apply(
    [](auto first, auto second) { return add_generic(first, second); },
    std::make_tuple(2.0f,3.0f)) << '\n';
</code>```

Body:
Taken from cppreference, why does the call to std::apply(add_generic, ...) fail to compile? Is there a way to fix it?

#include <iostream>
#include <tuple>

int add(int first, int second)
{
    return first + second;
}

template<typename T>
T add_generic(T first, T second)
{
    return first + second;
}

int main()
{
    std::cout << std::apply(add, std::make_tuple(1,2)) << '\n';

    // template argument deduction/substitution fails
    std::cout << std::apply(add_generic, std::make_tuple(2.0f,3.0f)) << '\n';
}

It fails with error:

[x86-64 gcc 7 (snapshot)] error: no matching function for call to
  'apply(, std::tuple)' [x86-64 gcc 7 (snapshot)] note:   couldn't deduce template
  parameter '_Fn'

Body:
This is not new in C++17. Just from the signature of std::apply, there is no telling whether you want to pass add_generic<int>, add_generic<float>, add_generic<std::string>, or anything else. Knowing that requires more context (specifically: it requires knowing how std::apply is going to invoke it), but that information isn't available at the call site and so cannot be used for template argument deduction.

It's possible to work around that by passing one object, and making that one object capable of calling whichever instantiation of add_generic is needed:

std::cout << std::apply(
    [](auto first, auto second) { return add_generic(first, second); },
    std::make_tuple(2.0f,3.0f)) << '\n';


问:
Python pandas rolling mean while retaining index and column
I have a pandas DataFrame of statistics for NBA games.  Here's a sample of the data for away teams:

```<code>                                  away_team  away_efg  away_drb  away_score
date
2000-10-31 19:00:00    Los Angeles Clippers     0.522      74.4          94
2000-10-31 19:00:00         Milwaukee Bucks     0.434      63.0          93
2000-10-31 19:30:00  Minnesota Timberwolves     0.523      73.8         106
2000-10-31 19:30:00       Charlotte Hornets     0.605      77.1         106
2000-10-31 19:30:00     Seattle SuperSonics     0.429      73.1          88
</code>```

There are many more numeric columns other than the away_score column, and also analogous columns for the home team.

What I would like is, for each row, replace the numeric columns (other than score) with the mean of the previous three observations, partitioned by team.  I can almost get what I want by doing the following:

```<code>home_df.groupby("team").apply(lambda x: x.rolling(window=3).mean())
</code>```

This returns, for example,

```<code>>>> home_avg[home_avg["team"]=="Utah Jazz"].head()
         3par        ast   blk        drb       efg       ftr        orb
0         NaN        NaN   NaN        NaN       NaN       NaN        NaN
50        NaN        NaN   NaN        NaN       NaN       NaN        NaN
81   0.146667  71.600000   9.4  74.666667  0.512000  0.347667  25.833333
</code>```

Taking this, along with

```<code>>>> home_df[home_df["team"]=="Utah Jazz"].head()
      3par   ast   blk   drb    efg    ftr   orb   stl       team   tov   trb
0    0.118  76.7   7.1  64.7  0.535  0.365  25.6  11.5  Utah Jazz  10.8  42.9
50   0.100  63.9   9.1  80.5  0.536  0.414  27.6   2.2  Utah Jazz  20.2  58.6
81   0.222  74.2  12.0  78.8  0.465  0.264  24.3   7.3  Utah Jazz  13.9  50.0
122  0.119  81.8  11.3  75.0  0.515  0.642  25.0  12.2  Utah Jazz  21.8  52.5
135  0.129  76.7  17.8  75.9  0.650  0.400  37.9   5.7  Utah Jazz  18.8  62.7
</code>```

demonstrates that it is including the current row in the calculation of the mean.  I want to avoid this.  More specifically, the desired output for row 81 would be all NaNs (because there haven't been three games yet), and the entry in the 3par column for row 122 would be .146667 (the average of the values in that column for rows 0, 50, and 81).

So, my question is, how can I exclude the current row in the rolling mean calculation?

答:
You can use shift here which shifts the index for a given amount to make your rolling window use the last three values excluding the current value:

```<code># create dummy data frame with numeric values
df = pd.DataFrame({"numeric_col": np.random.randint(0, 100, size=5)})
print(df)

    numeric_col
0   66
1   60
2   74
3   41
4   83

df["mean"] = df["numeric_col"].shift(1).rolling(window=3).mean()
print(df)

    numeric_col     mean
0   66              NaN
1   60              NaN
2   74              NaN
3   41              66.666667
4   83              58.333333
</code>```

Accordingly, change your apply function to lambda x: x.shift(1).rolling(window=3).mean() to make it work in your specific example.

Body:
I have a pandas DataFrame of statistics for NBA games.  Here's a sample of the data for away teams:

                                  away_team  away_efg  away_drb  away_score
date
2000-10-31 19:00:00    Los Angeles Clippers     0.522      74.4          94
2000-10-31 19:00:00         Milwaukee Bucks     0.434      63.0          93
2000-10-31 19:30:00  Minnesota Timberwolves     0.523      73.8         106
2000-10-31 19:30:00       Charlotte Hornets     0.605      77.1         106
2000-10-31 19:30:00     Seattle SuperSonics     0.429      73.1          88

There are many more numeric columns other than the away_score column, and also analogous columns for the home team.

What I would like is, for each row, replace the numeric columns (other than score) with the mean of the previous three observations, partitioned by team.  I can almost get what I want by doing the following:

home_df.groupby("team").apply(lambda x: x.rolling(window=3).mean())

This returns, for example,

>>> home_avg[home_avg["team"]=="Utah Jazz"].head()
         3par        ast   blk        drb       efg       ftr        orb
0         NaN        NaN   NaN        NaN       NaN       NaN        NaN
50        NaN        NaN   NaN        NaN       NaN       NaN        NaN
81   0.146667  71.600000   9.4  74.666667  0.512000  0.347667  25.833333

Taking this, along with

>>> home_df[home_df["team"]=="Utah Jazz"].head()
      3par   ast   blk   drb    efg    ftr   orb   stl       team   tov   trb
0    0.118  76.7   7.1  64.7  0.535  0.365  25.6  11.5  Utah Jazz  10.8  42.9
50   0.100  63.9   9.1  80.5  0.536  0.414  27.6   2.2  Utah Jazz  20.2  58.6
81   0.222  74.2  12.0  78.8  0.465  0.264  24.3   7.3  Utah Jazz  13.9  50.0
122  0.119  81.8  11.3  75.0  0.515  0.642  25.0  12.2  Utah Jazz  21.8  52.5
135  0.129  76.7  17.8  75.9  0.650  0.400  37.9   5.7  Utah Jazz  18.8  62.7

demonstrates that it is including the current row in the calculation of the mean.  I want to avoid this.  More specifically, the desired output for row 81 would be all NaNs (because there haven't been three games yet), and the entry in the 3par column for row 122 would be .146667 (the average of the values in that column for rows 0, 50, and 81).

So, my question is, how can I exclude the current row in the rolling mean calculation?

Body:
You can use shift here which shifts the index for a given amount to make your rolling window use the last three values excluding the current value:

# create dummy data frame with numeric values
df = pd.DataFrame({"numeric_col": np.random.randint(0, 100, size=5)})
print(df)

    numeric_col
0   66
1   60
2   74
3   41
4   83

df["mean"] = df["numeric_col"].shift(1).rolling(window=3).mean()
print(df)

    numeric_col     mean
0   66              NaN
1   60              NaN
2   74              NaN
3   41              66.666667
4   83              58.333333

Accordingly, change your apply function to lambda x: x.shift(1).rolling(window=3).mean() to make it work in your specific example.


问:
RSpec documentation...where is it hiding?
Having a terrible time finding RSpec-2 (and rspec-rails) documentation. Specifically I want to look up all available Matchers... but how?

I've tried:

RSpec.info : outdated - RSpec 1.x

rdoc.info : seems useless, to me anyway. (incomplete?)

RSpec-Relish : confusing. incomplete? how would one look up available Matchers?

GitHub Wiki : scattered info. unorganized. incomplete?

Yes, I'm aware of The Book...but, seriously, isn't this stuff online?

Even tried rake doc:plugins but it didn't work. Too green to know why...

apparently there used to be some decent 1.x docs on rspec.rubyforge.org. but they're appear to be long gone...

Where are these docs hiding?

答:
Not sure why you feel rdoc.info isn't useful - here's the matcher docs there:

http://rubydoc.info/gems/rspec-expectations/2.0.1/RSpec/Matchers

It may be that you're looking in the wrong spot; these were in the RSpec::Expectations gem, which is split out from the core in Rspec 2.


问:
Re-classifying a random matrix
I am brand new to R and in some desperate need of help. I have created a random matrix and need to re-classify it. Each pixel is randomly generated from 0-255 and I need to able to classify the 0-255 digits into 8 classifications. How would I do this? Any help would be greatly appreciated and I have placed my code below. I know I could use a raster but I am unsure on how to use them.

Thanks

par(mar=rep(0,4))

m=matrix(runif(100),10,10)

image(m,axes=FALSE,col=grey(seq(0,1,length=255)))

答:
I didn't think your example adequately fit your description of the problem (since runif only ranges from 0-1 if the limits are not specified) so I modified it to fit the natural language features:

```<code>m=matrix(runif(100, 0, 255),10,10)
m[] <- findInterval(m, seq(0, 256, length=8) )

image(m,axes=FALSE,col=grey(seq(0,1,length=255)))
</code>```

The "[]" with no indices preserves the matrix structure of the m object. The findInterval function lets you do the same sort of binning as cut, but it returns a numeric vector rather than the factor that cut would give.

Title: Re-classifying a random matrix

Body:
I didn't think your example adequately fit your description of the problem (since runif only ranges from 0-1 if the limits are not specified) so I modified it to fit the natural language features:

m=matrix(runif(100, 0, 255),10,10)
m[] <- findInterval(m, seq(0, 256, length=8) )

image(m,axes=FALSE,col=grey(seq(0,1,length=255)))

The "[]" with no indices preserves the matrix structure of the m object. The findInterval function lets you do the same sort of binning as cut, but it returns a numeric vector rather than the factor that cut would give.


问:
Draw a separator line in conjunction with Auto Layout
I'm reimplementig some kind of UISplitViewController. Now I need to draw a separator line between the master and the detail view. Now I have some questions for this:

Should the separator line be on the view controller itself or should it be a separate view?

What about Auto Layout? Setting a frame is not allowed.

I saw solutions for CALayer/CAShapeLayer, drawRect (CoreGraphics) or using the background color of an UIView/UILabel. The last one should cost too much performance according to the folks there.

On the one side it is comfortable to draw the line in the UITableViewController itself. Or should a separate UIView be created? If I embed a separate UIView there will be much more constraints and it will complicate things (would have to set separate widths) ... Also it should adapt to orientation changes (e.g. the size of the UITableViewController changes -> the separation line should also resize).

How can I add such a dividing rule? Such a dividing rule can be seen here:

答:
Updating the @mharper answer to Swift 3.x</p>

```<code>import UIKit

@IBDesignable
class LineView: UIView {

    @IBInspectable var lineWidth: CGFloat = 1.0
    @IBInspectable var lineColor: UIColor? {
        didSet {
            lineCGColor = lineColor?.cgColor
        }
    }
    var lineCGColor: CGColor?

    override func draw(_ rect: CGRect) {
        // Draw a line from the left to the right at the midpoint of the view's rect height.
        let midpoint = self.bounds.size.height / 2.0
        if let context = UIGraphicsGetCurrentContext() {
            context.setLineWidth(lineWidth)
            if let lineCGColor = self.lineCGColor {
                context.setStrokeColor(lineCGColor)
            }
            else {
                context.setStrokeColor(UIColor.black.cgColor)
            }
            context.move(to: CGPoint(x: 0.0, y: midpoint))
            context.addLine(to: CGPoint(x: self.bounds.size.width, y: midpoint))
            context.strokePath()
        }
    }
}
</code>```

Body:
Updating the @mharper answer to Swift 3.x

import UIKit

@IBDesignable
class LineView: UIView {

    @IBInspectable var lineWidth: CGFloat = 1.0
    @IBInspectable var lineColor: UIColor? {
        didSet {
            lineCGColor = lineColor?.cgColor
        }
    }
    var lineCGColor: CGColor?

    override func draw(_ rect: CGRect) {
        // Draw a line from the left to the right at the midpoint of the view's rect height.
        let midpoint = self.bounds.size.height / 2.0
        if let context = UIGraphicsGetCurrentContext() {
            context.setLineWidth(lineWidth)
            if let lineCGColor = self.lineCGColor {
                context.setStrokeColor(lineCGColor)
            }
            else {
                context.setStrokeColor(UIColor.black.cgColor)
            }
            context.move(to: CGPoint(x: 0.0, y: midpoint))
            context.addLine(to: CGPoint(x: self.bounds.size.width, y: midpoint))
            context.strokePath()
        }
    }
}


问:
Can I tune IndexOf selection?
I have performance profiled the application for a long time

It turns out that the most of the CPU is used by the IndexOf function

Here the function

```<code>public static string func_Fix_Google_Source(string srSource)
{
    int irIndex = srSource.IndexOf("<div id=\"gt-form-c\">");
    return srSource.Substring(irIndex);
}
</code>```

The length of the string would matter? I may shorten the seek string length i believe

答:
If substring searching becomes a bottleneck, you can switch to an advanced algorithm, such as KMP.

The default string search may be very expensive when you have lots of "false positives", e.g. lots of

```<code><div id="...
</code>```

in the text being searched.

Every time the prefix above is discovered at a position where a match does not start, the default algorithm follows it for as much as it takes to confirm the absence of match, and then it goes to the next position. In contrast, KMP skips many characters that it has already seen, improving the efficiency.

Title: Can I tune IndexOf selection?

Body:
I have performance profiled the application for a long time

It turns out that the most of the CPU is used by the IndexOf function

Here the function

public static string func_Fix_Google_Source(string srSource)
{
    int irIndex = srSource.IndexOf("
");
    return srSource.Substring(irIndex);
}

The length of the string would matter? I may shorten the seek string length i believe

Body:
If substring searching becomes a bottleneck, you can switch to an advanced algorithm, such as KMP.

The default string search may be very expensive when you have lots of "false positives", e.g. lots of

<div id="...

in the text being searched.

Every time the prefix above is discovered at a position where a match does not start, the default algorithm follows it for as much as it takes to confirm the absence of match, and then it goes to the next position. In contrast, KMP skips many characters that it has already seen, improving the efficiency.


问:
What separates a content management system from just a bunch of web pages?
I have a website that has related pages.  They have links that point back and forth to one another but I have no integrated system, nor do I know what that would mean.

What is the minimum code that a group of web pages must have to be considered a Content Management System (CMS).  Is it that all the settings are in the database and the pages are generated somehow?  Is there some small snippet that all my pages could share that makes them a CMS, database or not?

Thanks.  I was also hoping not to have to study a giant CMS to see what makes it a CMS .  After maybe a basic understanding I would know what I was looking for.

edit:  here's why I ask about code.  Whenever I have looked at a CMS, and maybe they aren't all the same, I saw that to develop a module you always had to inherit from certain classes and had some necessary code.  I didn't know if there was some magic model that I just don't get that all cms makers understand.

edit:  perhaps my question is more about being extendable or pluggable.  What would a minimum look like?  Is it possible to show that here?

edit:  how about this?  Is something a CMS if it is not extendable and/or pluggable?

答:
Ultimately, a CMS is a system that lets you manage content, so it needs an user interface that is dedicated to letting you easily create, edit and delete pages on your website.

However, it's fairly usual to expect from a CMS to provide a browser-based WYSIWYG page editor, file uploading, image resizing, url rewriting, page categories and tags, user accounts (editor, moderator, administrator), and some kind of templae system.


问:
SQL error: Invalid parameter number: parameter was not defined
This is my code. I believe it does not bind the value's to the parameters.. But I don't know why:

```<code>public function create($fields)
    {
        $keys = array_keys($fields);
        $values = null;
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';
            if ($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

        if(!$this->db->prepare($sql)->execute($fields)) {
            return true;
        }
        return false;
    }
</code>```

And on index.php:

```<code>$user = new User();
$user->create(array(
                'name' => 'test',
                'username' => 'test2',
                'email' => 'test@gmail.com'
            ));
</code>```

Why are my values not bound to the parameters? This is the full error:

An exception occurred while executing 'INSERT INTO users (name,
  username, email) VALUES (?, ?, ?)' with params ["test", "test2",
  "test@gmail.com"]:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

答:
Try This

```

    public function create($fields)
        {
            $keys ='';
            $values = '';
            foreach($fields as $k=>$field) {
                $keys[] = $k;
                $values[] = $field;
            }
            $sql = "INSERT INTO users (".implode(',',$keys).") VALUES ("'".implode ("','",$values)."'")";
            if(!$this->db->prepare($sql)->execute($fields)) {
                return true;
            }
            return false;
        }

```

Body:
This is my code. I believe it does not bind the value's to the parameters.. But I don't know why:

public function create($fields)
    {
        $keys = array_keys($fields);
        $values = null;
        $x = 1;

        foreach($fields as $field) {
            $values .= '?';
            if ($x < count($fields)) {
                $values .= ', ';
            }
            $x++;
        }

        $sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES ({$values})";

        if(!$this->db->prepare($sql)->execute($fields)) {
            return true;
        }
        return false;
    }

And on index.php:

$user = new User();
$user->create(array(
                'name' => 'test',
                'username' => 'test2',
                'email' => 'test@gmail.com'
            ));

Why are my values not bound to the parameters? This is the full error:

An exception occurred while executing 'INSERT INTO users (name,
  username, email) VALUES (?, ?, ?)' with params ["test", "test2",
  "test@gmail.com"]:

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Body:
Try This

    public function create($fields)
        {
            $keys ='';
            $values = '';
            foreach($fields as $k=>$field) {
                $keys[] = $k;
                $values[] = $field;
            }
            $sql = "INSERT INTO users (".implode(',',$keys).") VALUES ("'".implode ("','",$values)."'")";
            if(!$this->db->prepare($sql)->execute($fields)) {
                return true;
            }
            return false;
        }


问:
Invalid Regular Expression: Nothing to Repeat Error
I am trying to make an app that counts how many times each character occurs in a given string. So for example, in the string "hello 12355" it should match with all the numbers past 1, and not with the "hello" part. However, when I try to run the code, I get this in the console:

"Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
    at new RegExp ()"

When I change xy to anything past 92, however, the code runs fine. From what I've read about this error, it means that you have to double backslash some characters because they mean something in Regexp. However, I can't double backslash the Unicode variable without affecting all of the Unicode values. Can anyone help?

Here is my code:

```<code>var occArray = [];
var occChars = [];

var xy = 50;

for (i = xy; i < 100; i++) {
    var unicodeChar = String.fromCharCode(i);
    var counter = new RegExp(unicodeChar, 'g');
    var occurence = "hello 12355";
    var occ = (occurence.match(counter) || []).length;

    occArray.push(occ);
    occChars.push(unicodeChar);
}
    alert(occArray);
    alert(occChars);
</code>```

答:
I think it happens because some character you pass for unicodeChar is special character in Regex(In your error, it's ? which is 63). Please consider to detect whether it's special character or not, if it is, you can add backslash infront of it before you pass it to Regex.

May this helps you.

Body:
I am trying to make an app that counts how many times each character occurs in a given string. So for example, in the string "hello 12355" it should match with all the numbers past 1, and not with the "hello" part. However, when I try to run the code, I get this in the console:

"Uncaught SyntaxError: Invalid regular expression: /?/: Nothing to repeat
    at new RegExp ()"

When I change xy to anything past 92, however, the code runs fine. From what I've read about this error, it means that you have to double backslash some characters because they mean something in Regexp. However, I can't double backslash the Unicode variable without affecting all of the Unicode values. Can anyone help?

Here is my code:

var occArray = [];
var occChars = [];

var xy = 50;

for (i = xy; i < 100; i++) {
    var unicodeChar = String.fromCharCode(i);
    var counter = new RegExp(unicodeChar, 'g');
    var occurence = "hello 12355";
    var occ = (occurence.match(counter) || []).length;

    occArray.push(occ);
    occChars.push(unicodeChar);
}
    alert(occArray);
    alert(occChars);


问:
How to remove devise password resetting during email confirmation?
My email confirmation works with devise, however I want to remove this automatic password resetting. I don't manage to find in which file devise orders this action. Thank you in advance !</p>

答:
Presuming your devise model is User:

Remove :recoverable module in app/models/user.rb

If you once had your devise views generated, remove Forgot your password? link in app/views/devise/shared/_links.html.erb

Create a migration dropping reset_password_token and reset_password_sent_at of your users table:

First run:

```<code>rails g migration RemoveRecoverableFromUsers
</code>```

Edit migration:

```<code>class RemoveRecoverableFromUsers < ActiveRecord::Migration[5.0]
  def up
    remove_column :users, :reset_password_token
    remove_column :users, :reset_password_sent_at
  end

  def down
    add_column :users, :reset_password_token, :string
    add_column :users, :reset_password_sent_at, :datetime
  end
end
</code>```

Body:
Presuming your devise model is User:

Remove :recoverable module in app/models/user.rb

If you once had your devise views generated, remove Forgot your password? link in app/views/devise/shared/_links.html.erb

Create a migration dropping reset_password_token and reset_password_sent_at of your users table:

First run:

rails g migration RemoveRecoverableFromUsers

Edit migration:

class RemoveRecoverableFromUsers < ActiveRecord::Migration[5.0]
  def up
    remove_column :users, :reset_password_token
    remove_column :users, :reset_password_sent_at
  end

  def down
    add_column :users, :reset_password_token, :string
    add_column :users, :reset_password_sent_at, :datetime
  end
end


问:
Link two computers with Socket in Java
I have a server and a client in Java, both work in localhost or with my machine IP, but when I tells a IP from another computer in my local network, it tells "Exception occurred: Connection refused: connect"! Here is my code:

ChatClient.java

```<code>package programmingchat;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {

    private Socket socket;
    private Scanner console;
    private DataOutputStream output;
    private BufferedReader reader;

    public ChatClient(String serverName, int serverPort) {
        try {
            System.out.println("LiveChat Client 1.1 start.");
            System.out.println("Trying to connect to " + serverName + " on port " + serverPort + "...");
            socket = new Socket(serverName, serverPort);
            System.out.println("Success!");

            console = new Scanner(System.in);
            output = new DataOutputStream(socket.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Thread t1 = new Thread(){
                @Override
                public void run() {
                    String line = "";

                    while(!line.equals(".bye")) {
                        try {
                            System.out.print("me: ");
                            line = console.nextLine();
                            output.writeUTF(line);
                            output.flush();
                        } catch(IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };

            Thread t2 = new Thread(){
                @Override
                public void run() {
                    String line = "";

                    try {
                        while(!(line = reader.readLine()).equals(".bye")) {
                            System.out.print("\nhe: " + line + "\nme: ");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            t1.start();
            t2.start();
        } catch(UnknownHostException e) {
            System.err.println("Unknown host: " + e.getMessage());
        } catch(IOException e) {
            System.err.println("Exception ocurred: " + e.getMessage());
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @SuppressWarnings({ "unused", "resource" })
    public static void main(String[] args) throws IOException {
        File hostsFile = new File("hosts.dat");

        if(!hostsFile.exists()) {
            hostsFile.createNewFile();
            FileController.writeFile(hostsFile.getPath(), "localhost\n");
        }

        String hosts = FileController.loadFile("hosts.dat");
        String[] h = hosts.split("\n");

        System.out.println("Select host by it number, or insert a new one.");
        System.out.println("Currently avaliable hosts: ");

        for(int i = 0; i < h.length; i++) {
            System.out.println(i + ": " + h[i]);
        }

        System.out.print("Please provide the IP Address of the server: ");
        Scanner s = new Scanner(System.in);
        String hostName = s.nextLine();

        if(isInteger(hostName)) {
            int i = Integer.parseInt(hostName);
            hostName = h[i];
        } else {
            FileController.writeFile(hostsFile.getPath(), hostName + "\n");
        }

        ChatClient client = new ChatClient("localhost", 9081);
    }

    private static boolean isInteger(String str) {
        boolean is = false;

        try {
            Integer.parseInt(str);
            is = true;
        } catch(Exception e) {
            is = false;
        }

        return is;
    }
}
</code>```

ChatServer.java

```<code>package programmingchat;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

    private Socket[] sockets;
    private ServerSocket server;
    private DataInputStream[] ins;
    private PrintStream[] outs;

    private String ln1;
    private String ln2;

    public ChatServer(int port) {
        try {
            System.out.println("LiveChat Server 0.9 start.");
            System.out.println("Trying to open port " + port + "...");
            server = new ServerSocket(port);
            System.out.println("Server " + server.getInetAddress().getHostName() + " successfully started!");
            System.out.println("Instantiating input and output streams...");
            ins = new DataInputStream[2];
            outs = new PrintStream[2];
            System.out.println("Success!");
            System.out.println("Instantiating sockets...");
            sockets = new Socket[2];
            System.out.println("Success!");
            System.out.println("Waiting socket 1 to connect...");
            sockets[0] = server.accept();
            System.out.println("Success!");
            System.out.println("Waiting socket 2 to connect...");
            sockets[1] = server.accept();
            System.out.println("Success!");
            System.out.println("Opening input and output streams...");
            open();
            System.out.println("Success!");
            System.out.println("Initializing input strings...");
            ln1 = "";
            ln2 = "";
            System.out.println("Success!");

            Thread r1 = new Thread() {
                @Override
                public void run() {
                    try {
                        while(!ln1.equals(".bye")) {
                            ln1 = ins[0].readUTF();
                            System.out.println("1: " +ln1);
                            outs[1].println(ln1);
                        }

                        System.out.println("Socket 1 disconnect!");
                        sockets[0].close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            Thread r2 = new Thread() {
                @Override
                public void run() {
                    try {
                        while(!ln2.equals(".bye")) {
                            ln2 = ins[1].readUTF();
                            System.out.println("2: " + ln2);
                            outs[0].println(ln2);
                        }

                        System.out.println("Socket 2 disconnect!");
                        sockets[1].close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            r1.start();
            r2.start();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void open() throws IOException {
        ins[0] = new DataInputStream(new BufferedInputStream(sockets[0].getInputStream()));
        ins[1] = new DataInputStream(new BufferedInputStream(sockets[1].getInputStream()));
        outs[0] = new PrintStream(sockets[0].getOutputStream());
        outs[1] = new PrintStream(sockets[1].getOutputStream());
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        ChatServer chat = new ChatServer(9081);
    }
}
</code>```

Please, someone can help me?

答:
Use server's local IP address instead of "localhost"

```<code>ChatClient client = new ChatClient("localhost", 9081);
</code>```

your server is on different machine, it works if both server and client are on one machine.

(How do I find my local (internal) IP address?)

Edit:

Not configuring router to accept this connection between client and server by forwarding port number on router definitely could cause this error, so you should do this.

(How to Set Up Port Forwarding on a Router, it differs according to router type)

(You could check also this video)

Title: Link two computers with Socket in Java

Body:
I have a server and a client in Java, both work in localhost or with my machine IP, but when I tells a IP from another computer in my local network, it tells "Exception occurred: Connection refused: connect"! Here is my code:

ChatClient.java

package programmingchat;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ChatClient {

    private Socket socket;
    private Scanner console;
    private DataOutputStream output;
    private BufferedReader reader;

    public ChatClient(String serverName, int serverPort) {
        try {
            System.out.println("LiveChat Client 1.1 start.");
            System.out.println("Trying to connect to " + serverName + " on port " + serverPort + "...");
            socket = new Socket(serverName, serverPort);
            System.out.println("Success!");

            console = new Scanner(System.in);
            output = new DataOutputStream(socket.getOutputStream());
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            Thread t1 = new Thread(){
                @Override
                public void run() {
                    String line = "";

                    while(!line.equals(".bye")) {
                        try {
                            System.out.print("me: ");
                            line = console.nextLine();
                            output.writeUTF(line);
                            output.flush();
                        } catch(IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };

            Thread t2 = new Thread(){
                @Override
                public void run() {
                    String line = "";

                    try {
                        while(!(line = reader.readLine()).equals(".bye")) {
                            System.out.print("\nhe: " + line + "\nme: ");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            t1.start();
            t2.start();
        } catch(UnknownHostException e) {
            System.err.println("Unknown host: " + e.getMessage());
        } catch(IOException e) {
            System.err.println("Exception ocurred: " + e.getMessage());
        } catch(Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @SuppressWarnings({ "unused", "resource" })
    public static void main(String[] args) throws IOException {
        File hostsFile = new File("hosts.dat");

        if(!hostsFile.exists()) {
            hostsFile.createNewFile();
            FileController.writeFile(hostsFile.getPath(), "localhost\n");
        }

        String hosts = FileController.loadFile("hosts.dat");
        String[] h = hosts.split("\n");

        System.out.println("Select host by it number, or insert a new one.");
        System.out.println("Currently avaliable hosts: ");

        for(int i = 0; i < h.length; i++) {
            System.out.println(i + ": " + h[i]);
        }

        System.out.print("Please provide the IP Address of the server: ");
        Scanner s = new Scanner(System.in);
        String hostName = s.nextLine();

        if(isInteger(hostName)) {
            int i = Integer.parseInt(hostName);
            hostName = h[i];
        } else {
            FileController.writeFile(hostsFile.getPath(), hostName + "\n");
        }

        ChatClient client = new ChatClient("localhost", 9081);
    }

    private static boolean isInteger(String str) {
        boolean is = false;

        try {
            Integer.parseInt(str);
            is = true;
        } catch(Exception e) {
            is = false;
        }

        return is;
    }
}

ChatServer.java

package programmingchat;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

    private Socket[] sockets;
    private ServerSocket server;
    private DataInputStream[] ins;
    private PrintStream[] outs;

    private String ln1;
    private String ln2;

    public ChatServer(int port) {
        try {
            System.out.println("LiveChat Server 0.9 start.");
            System.out.println("Trying to open port " + port + "...");
            server = new ServerSocket(port);
            System.out.println("Server " + server.getInetAddress().getHostName() + " successfully started!");
            System.out.println("Instantiating input and output streams...");
            ins = new DataInputStream[2];
            outs = new PrintStream[2];
            System.out.println("Success!");
            System.out.println("Instantiating sockets...");
            sockets = new Socket[2];
            System.out.println("Success!");
            System.out.println("Waiting socket 1 to connect...");
            sockets[0] = server.accept();
            System.out.println("Success!");
            System.out.println("Waiting socket 2 to connect...");
            sockets[1] = server.accept();
            System.out.println("Success!");
            System.out.println("Opening input and output streams...");
            open();
            System.out.println("Success!");
            System.out.println("Initializing input strings...");
            ln1 = "";
            ln2 = "";
            System.out.println("Success!");

            Thread r1 = new Thread() {
                @Override
                public void run() {
                    try {
                        while(!ln1.equals(".bye")) {
                            ln1 = ins[0].readUTF();
                            System.out.println("1: " +ln1);
                            outs[1].println(ln1);
                        }

                        System.out.println("Socket 1 disconnect!");
                        sockets[0].close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            Thread r2 = new Thread() {
                @Override
                public void run() {
                    try {
                        while(!ln2.equals(".bye")) {
                            ln2 = ins[1].readUTF();
                            System.out.println("2: " + ln2);
                            outs[0].println(ln2);
                        }

                        System.out.println("Socket 2 disconnect!");
                        sockets[1].close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            r1.start();
            r2.start();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void open() throws IOException {
        ins[0] = new DataInputStream(new BufferedInputStream(sockets[0].getInputStream()));
        ins[1] = new DataInputStream(new BufferedInputStream(sockets[1].getInputStream()));
        outs[0] = new PrintStream(sockets[0].getOutputStream());
        outs[1] = new PrintStream(sockets[1].getOutputStream());
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        ChatServer chat = new ChatServer(9081);
    }
}

Please, someone can help me?

Body:
Use server's local IP address instead of "localhost"

ChatClient client = new ChatClient("localhost", 9081);

your server is on different machine, it works if both server and client are on one machine.

(How do I find my local (internal) IP address?)

Edit:

Not configuring router to accept this connection between client and server by forwarding port number on router definitely could cause this error, so you should do this.

(How to Set Up Port Forwarding on a Router, it differs according to router type)

(You could check also this video)