问:
Thread limit exceeded replacing blocked worker
I am using AsyncHttpClient, and making many http requests in parallel.
I am getting the following error:

```<code>java.util.concurrent.RejectedExecutionException: Thread limit exceeded replacing blocked worker
</code>```

How can I make a behavior where a new request waits until there is a free thread?

My code:

```<code>public class MyClass {
    private AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();

    public JSONObject jsonFromUrl(String requestUrl) {
        CompletableFuture<Response> futureResponse = asyncHttpClient.prepareGet(requestUrl).
                addHeader("header-name", "header-value").execute().toCompletableFuture();
        try {
            Response response = futureResponse.get();
            ... handling response
        } catch (Exception e) {
            ... handling exception
        }
    }
}
</code>```

答:
You can implement and set a RejectedExecutionHandler for the thread pool that handles rejected tasks by adding them to the work queue of the executor.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/RejectedExecutionHandler.html

```<code>threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
        try {
            executor.getQueue().put(task);
        } catch (InterruptedException e) {
            // handle exception
        }
    }
});
</code>```

Note that in the implementation above put() is a blocking operation, meaning if the queue is full it waits until there's room again to insert the task.

Body:
I am using AsyncHttpClient, and making many http requests in parallel.
I am getting the following error:

java.util.concurrent.RejectedExecutionException: Thread limit exceeded replacing blocked worker

How can I make a behavior where a new request waits until there is a free thread?

My code:

public class MyClass {
    private AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();

    public JSONObject jsonFromUrl(String requestUrl) {
        CompletableFuture<Response> futureResponse = asyncHttpClient.prepareGet(requestUrl).
                addHeader("header-name", "header-value").execute().toCompletableFuture();
        try {
            Response response = futureResponse.get();
            ... handling response
        } catch (Exception e) {
            ... handling exception
        }
    }
}

Body:
You can implement and set a RejectedExecutionHandler for the thread pool that handles rejected tasks by adding them to the work queue of the executor.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/RejectedExecutionHandler.html

threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
        try {
            executor.getQueue().put(task);
        } catch (InterruptedException e) {
            // handle exception
        }
    }
});

Note that in the implementation above put() is a blocking operation, meaning if the queue is full it waits until there's room again to insert the task.


来源: stackexchange

问:
bootstrap@4.0.0-alpha.3 invalid
Installing bootstrap 4 via npm I keep getting the same error:

Any ideas how to successfully install bootstrap 4 with npm? I have tried all options from this answer

答:
To install bootstrap 4.0.0-alpha.6 using your package.json file, you need to add this to the devDependencies:

```<code>"bootstrap": "4.0.0-alpha.6"
</code>```

Hope that helps.

ContentLicense: CC BY-SA 3.0

Title: bootstrap@4.0.0-alpha.3 invalid

Body:
To install bootstrap 4.0.0-alpha.6 using your package.json file, you need to add this to the devDependencies:

"bootstrap": "4.0.0-alpha.6"

Hope that helps.


问:
Parse plain email address into 2 parts
How do I get the username and the domain from an email address of:

```<code>string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";
</code>```

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.

答:
```<code>String[] parts = "hello@example.com".Split(new[]{ '@' });
String username = parts[0]; // "hello"
String domain = parts[1]; // "example.com"
</code>```

Title: Parse plain email address into 2 parts

Body:
How do I get the username and the domain from an email address of:

string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.


问:
extract word from string in sql server
I need to extract part of a string in sql server. Lets say I have this string in a column...

```<code>Name1=Bill Gates&Name2=Microsoft&Address1=The streetadress
</code>```

How can I extract the text that is equal to Name2 eg Microsoft?

答:
One old fashioned way of handling this is to just use basic string functions like CHARINDEX and SUBSTRING.

```<code>SELECT
    SUBSTRING(col,
              CHARINDEX('Name2', col) + 6,
              CHARINDEX('&', col, CHARINDEX('Name2', col)) -
                  CHARINDEX('Name2', col) - 6) AS name
FROM yourTable
</code>```

Note that this solution assumes that the key value pairs are fixed in the order you showed us.  My query uses the ambersand after the second name as a termination marker.  If this be not present, e.g. if Name2 could possibly the last key in the string, then my query would have to be updated.

Demo here:

Rextester

Title: extract word from string in sql server

Body:
I need to extract part of a string in sql server. Lets say I have this string in a column...

Name1=Bill Gates&Name2=Microsoft&Address1=The streetadress

How can I extract the text that is equal to Name2 eg Microsoft?

Body:
One old fashioned way of handling this is to just use basic string functions like CHARINDEX and SUBSTRING.

SELECT
    SUBSTRING(col,
              CHARINDEX('Name2', col) + 6,
              CHARINDEX('&', col, CHARINDEX('Name2', col)) -
                  CHARINDEX('Name2', col) - 6) AS name
FROM yourTable

Note that this solution assumes that the key value pairs are fixed in the order you showed us.  My query uses the ambersand after the second name as a termination marker.  If this be not present, e.g. if Name2 could possibly the last key in the string, then my query would have to be updated.

Demo here:

Rextester


问:
Install Solr 6.5.1 in Ubuntu 14.04.5 LTS into a custom directory
I am trying to install Solr 6.5.1 in Ubuntu 14.04.5 LTS. I have used the following commands to install Java and Solr

```<code>Installing Java

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

Installing Solr
cd /vm/solr
sudo wget http://mirror.fibergrid.in/apache/lucene/solr/6.6.0/solr-6.6.0.tgz
sudo tar xzf solr-6.6.0.tgz solr-6.6.0/bin/install_solr_service.sh --strip-components=2
sudo bash ./install_solr_service.sh solr-6.6.0.tgz
</code>```

Even though I tried to install Solr in /vm/solr i found that Solr was installed in /opt which I believe is the default installation directory.

Is there a way to install Solr in the directory we specify or change the home directory after installation.

答:
just by cd-ing to a directory, where you run the install script WILL NOT make it install into that dir.

The installation script accepts an option for that:

-i     Directory to extract the Solr installation archive; defaults to /opt
         The specified path must exist prior to using this script

So try by running:

```<code>sudo bash ./install_solr_service.sh solr-6.6.0.tgz -i /vm/solr
</code>```

Body:
I am trying to install Solr 6.5.1 in Ubuntu 14.04.5 LTS. I have used the following commands to install Java and Solr

Installing Java

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

Installing Solr
cd /vm/solr
sudo wget http://mirror.fibergrid.in/apache/lucene/solr/6.6.0/solr-6.6.0.tgz
sudo tar xzf solr-6.6.0.tgz solr-6.6.0/bin/install_solr_service.sh --strip-components=2
sudo bash ./install_solr_service.sh solr-6.6.0.tgz

Even though I tried to install Solr in /vm/solr i found that Solr was installed in /opt which I believe is the default installation directory.

Is there a way to install Solr in the directory we specify or change the home directory after installation.

Body:
just by cd-ing to a directory, where you run the install script WILL NOT make it install into that dir.

The installation script accepts an option for that:

-i     Directory to extract the Solr installation archive; defaults to /opt
         The specified path must exist prior to using this script

So try by running:

sudo bash ./install_solr_service.sh solr-6.6.0.tgz -i /vm/solr


问:
Loading Image in Java using JFrame
so i have a very basic java application, there is a panel and inside that is a button. When a user clicks the button, i want a picture to come up in another panel in the same form.

I searched up ways to load images from web/from my folder and this is the code i've come up with:-

```<code>private void buttonActionPerformed(java.awt.event.ActionEvent evt)

{
    ImageIcon icon = new ImageIcon("URL-of-the-image");
    panel2.setIcon(icon);

}
</code>```

~~what panel 2 looks like~~

where am i going wrong?
it says that the method "setIcon()" is causing a problem but i don't know any other method to do this job. Please Guide!

答:
If panel2 is a JPanel, it doesn't have a setIcon method.

Use a JLabel instead , it has such a method.

Title: Loading Image in Java using JFrame

Body:
so i have a very basic java application, there is a panel and inside that is a button. When a user clicks the button, i want a picture to come up in another panel in the same form.

I searched up ways to load images from web/from my folder and this is the code i've come up with:-

private void buttonActionPerformed(java.awt.event.ActionEvent evt)

{
    ImageIcon icon = new ImageIcon("URL-of-the-image");
    panel2.setIcon(icon);

}

~~what panel 2 looks like~~

where am i going wrong?
it says that the method "setIcon()" is causing a problem but i don't know any other method to do this job. Please Guide!


问:
Binding data in href attibute - VueJS
I have problem with binding data in VueJS. In code below, user.name is working but user.id in href attribute is not.

```<code><ul id="message-user-list">
  <li v-for="user in users">
    <a href="chat.php?user={{ user.id }}">{{ user.name }}</a>
  </li>
</ul>
</code>```

I also tried this but it doesn't work:

```<code><ul id="message-user-list">
  <li v-for="user in users">
    <a v-bind:href="chat.php?user={{ user.id }}">{{ user.name }}</a>
  </li>
</ul>
</code>```

What do I do wrong? Help please.

答:
Try it like this {{ user.name }}

If you do v-bind: - vue takes everything in quotes for js

ContentLicense: CC BY-SA 4.0

Title: Binding data in href attibute - VueJS

Body:
I have problem with binding data in VueJS. In code below, user.name is working but user.id in href attribute is not.

    {{ user.name }}

I also tried this but it doesn't work:

    {{ user.name }}

What do I do wrong? Help please.

Body:
Try it like this <a :href="'chat.php?user=' + user.id">{{ user.name }}</a>

If you do v-bind: - vue takes everything in quotes for js


问:
How to run hotstar in ubuntu 14.04
I am using ubuntu 14.04 and running the latest version of chrome still hotstar is not working? how to recover from that
I have tried the methods discussed on the ubuntu forums still hotstar is not working</p>

答:
Here is the solution I have found.

Step  1 : Copy the video url

(Ex. : http://www.hotstar.com/sports/cricket/icc-champions-trophy-2017/m181413/live-streaming/2001702409)

Step 2 : Add sudo before hotstar

Ex. http://www.sudohotstar.com/sports/cricket/icc-champions-trophy-2017/m181413/live-streaming/2001702409

Step 3 : hit enter. It should start playing that video.

Title: How to run hotstar in ubuntu 14.04


问:
How to use lower Elastic search version in Maven when using "spring-boot-starter-parent"
I am using "spring-boot-starter-parent" with version "2.0.0.BUILD-SNAPSHOT" for Webflux. I am using Elasticsearch as datasource. So i have included "spring-boot-starter-data-elasticsearch" in pom.xml. This is by default including ES version of 5.4.0. But my Elasticsearch version is 2.3.1. I cannot upgrade my ES version now. So is there a way to downgrade ES version which is getting included by default (5.4.0) to lower version (2.3.1). I tried specifying lower version in "spring-boot-starter-data-elasticsearch" dependency in pom.xml, but still not working. I am getting "NoNodeAvailalbe Exception". So I downgraded ES by using dependency "org.elasticsearch" with version 2.3.1, but in this case I am not able to bring up my server.</p>

答:
You can use maven dependencyManagement tag to override spring-boot-starter-data-elasticsearch or org.elasticsearch version.

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

See this detailed post from spring.io Overriding Dependency Versions with Spring Boot

Body:
You can use maven dependencyManagement tag to override spring-boot-starter-data-elasticsearch or org.elasticsearch version.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.3.1</version>
        </dependency>
    </dependencies>
</dependencyManagement>

See this detailed post from spring.io Overriding Dependency Versions with Spring Boot


问:
If statement variable returning empty
this is a test code i wrote to get a value set for $rectype to insert into a table. problem I'm having is $rectype is returning 0 or empty. the files do exist since I perform a similar is_file check to start the process that leads up to this section of the coding</p>

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc"; // exist
$dirchk2 = "/temp/files/" . $data[1] . ".doc"; // exist

$file_1 = (is_file($dirchk1));
$file_2 = (is_file($dirchk2));

if ($file_1) {
$rectype == ($file_2 ? '3' : '1');
}

echo $rectype . "\n";
</code>```

答:
As typed everywhere, you are using a comparison $expression == $expression instead of an assignment $variable = $expression;.

They didn't tell you that your code, as exposed would drop a E_NOTICE saying that $rectype is uninitialized.

It is good practice to run your code with error_reporting(E_ALL) while debugging, and that will tell you these errors and the line where they are.

ContentLicense: CC BY-SA 2.5

Title: If statement variable returning empty

Body:
this is a test code i wrote to get a value set for $rectype to insert into a table. problem I'm having is $rectype is returning 0 or empty. the files do exist since I perform a similar is_file check to start the process that leads up to this section of the coding

$dirchk1 = "/temp/files/" . $data[0] . ".doc"; // exist
$dirchk2 = "/temp/files/" . $data[1] . ".doc"; // exist

$file_1 = (is_file($dirchk1));
$file_2 = (is_file($dirchk2));

if ($file_1) {
$rectype == ($file_2 ? '3' : '1');
}

echo $rectype . "\n";


答:
```<code>awk '{ num[NR]=$1 } END { for (i=1;i<=NR;i++) if (substr(num[i+1],length(num[i+1]))=="2") { printf num[i]"\t"num[i+1]"\n";i++ } else { print num[i] } }' nums
</code>```

Where nums is the file with the data. First we put the data in an array called num then we loop through the array checking to see if the next element ends in two (using the substr function along with length to get the last character). If it does then we print both and add one to the counter else we just print the element.

Title: Merge two lines conditionally

Body:
200005251|AAAAAA
200005252|BBBBB
200005261|CCCCCC
200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF
200005302|VVVVVV
200005311|AAAAAA
200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS
200006022|HHHHHH
200006051|OOOOOO
200006052|GGGGGG
200006061|KKKKKK
200006062|FFFFF
200006071|TTTTTT

I have a file in first field as above. I need to merge every two lines if they only end ......1 and ......2. and leave the others as is. Desired output:

200005251|AAAAAA 200005252|BBBBB
200005261|CCCCCC 200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF 200005302|VVVVVV
200005311|AAAAAA 200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS 200006022|HHHHHH
200006051|OOOOOO 200006052|GGGGGG
200006061|KKKKKK 200006062|FFFFF
200006071|TTTTTT

Thanks in advance.

Body:
awk '{ num[NR]=$1 } END { for (i=1;i<=NR;i++) if (substr(num[i+1],length(num[i+1]))=="2") { printf num[i]"\t"num[i+1]"\n";i++ } else { print num[i] } }' nums

Where nums is the file with the data. First we put the data in an array called num then we loop through the array checking to see if the next element ends in two (using the substr function along with length to get the last character). If it does then we print both and add one to the counter else we just print the element.


问:
Expand outer nested div to 100%
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1    <br/> test1
  </div>
  <div>
    test2    <br/> test2
  </div>
</div></code>```

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

答:
There are two aspects to resolve this question:

use clear properties, whether add :after to .outer class or add a real div as the last .outer container element can do;

.outer {
  background-color: #ff00ff;
  width: 100%;
}
.outer:after {
  display: block;
  content: "";
  clear: both;
}
.outer div {
  float: left;
  background-color: #0000ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1
    <br/> test1
    <br/> test1
  </div>
  <div>
    test2
    <br/> test2
    <br/> test2
  </div>
</div></code>```

Establish a new block formatting context. According to CSS2.1 specification, the way to create a new BFC is below:

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

.outer {
  background-color: #ff00ff;
  width: 100%;
  /* float and below overflow peoperties can both establish a new BFC */
  // float: left;
  overflow: auto;
}

.outer div {
  float: left;
  background-color: #0000ff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div>
    test1
    <br/> test1
    <br/> test1
  </div>
  <div>
    test2
    <br/> test2
    <br/> test2
  </div>
</div></code>```

Title: Expand outer nested div to 100%

Body:
I have this code

.outer {
  background-color: #ff00ff;
  width: 100%;
}

.outer div {
  float: left;
  background-color: #0000ff;

}

    test1
 test1

    test2
 test2

https://jsfiddle.net/jcb5mdqa/

It looks like

but I want the outer to have a width of 100% like in .css written.

Expected result

What do I need to change?

Body:
There are two aspects to resolve this question:

use clear properties, whether add :after to .outer class or add a real div as the last .outer container element can do;

.outer {
  background-color: #ff00ff;
  width: 100%;
}
.outer:after {
  display: block;
  content: "";
  clear: both;
}
.outer div {
  float: left;
  background-color: #0000ff;
}

<div class="outer">
  <div>
    test1
    <br/> test1
    <br/> test1
  </div>
  <div>
    test2
    <br/> test2
    <br/> test2
  </div>
</div>

Establish a new block formatting context. According to CSS2.1 specification, the way to create a new BFC is below:

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

.outer {
  background-color: #ff00ff;
  width: 100%;
  /* float and below overflow peoperties can both establish a new BFC */
  // float: left;
  overflow: auto;
}

.outer div {
  float: left;
  background-color: #0000ff;
}

<div class="outer">
  <div>
    test1
    <br/> test1
    <br/> test1
  </div>
  <div>
    test2
    <br/> test2
    <br/> test2
  </div>
</div>


问:
Meteor get blank data from collection
i am using Meteor 1.4 and i'm trying to get data from data base collection but i got blank array .
This is my code

Server side

```<code>import { Mongo } from 'meteor/mongo';
export const Employee = new Mongo.Collection('employee');
</code>```

Client Side

```<code>import { Employee } from '/imports/api/employee/employee.js';
Template.employee.helpers({
employee_list: function() {
    var emp = Employee.find().fetch();
    console.log('emp', emp);
});
</code>```

i successfully insert into same collection but if i try to get data than it's blank.

答: Meteor works with pub/sub model, and, if the client is not subscribed to the collection, updates will not be propagated to it.</p>

Title: Meteor get blank data from collection

Body:
i am using Meteor 1.4 and i'm trying to get data from data base collection but i got blank array .
This is my code

Server side

import { Mongo } from 'meteor/mongo';
export const Employee = new Mongo.Collection('employee');

Client Side

import { Employee } from '/imports/api/employee/employee.js';
Template.employee.helpers({
employee_list: function() {
    var emp = Employee.find().fetch();
    console.log('emp', emp);
});

i successfully insert into same collection but if i try to get data than it's blank.


问:
Iterating object array within object - javascript?
I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

```<code>Object { leaving: object { all: array[10] } }
</code>```

I can quite easily return a single result by returning:

```<code> var html = '<p>' + news.leaving.all[0].departure_time + '</p>';
</code>```

But when I try to loop:

```<code>    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {
        html +=
        '<p>' + news[i].leaving.all.departure_time '</p>';
     }
</code>```

I get nothing…

Any help with this will be great.

Thanks

答:
You have to loop over news.leaving.all:

// Let's say this is our data
var news = {
  leaving: {
    all: [{
      departure_time: '01:00'
    },
    {
      departure_time: '02:00'
    },
    {
      departure_time: '02:00'
    }]
  }
};

var html = "";
var i;
for (i = 0; i < news.leaving.all.length; i++) {
  html += '
' + news.leaving.all[i].departure_time + '
';
 }

console.log(html);     ```

Body:
I know iteration has been covered before - I'm usually pretty ok with it but struggling this time.

I have the following information I'm trying to loop through:

Object { leaving: object { all: array[10] } }

I can quite easily return a single result by returning:

 var html = '
' + news.leaving.all[0].departure_time + '
';

But when I try to loop:

    var html = "";
    var i;
    for (i = 0; i < news.length; i++) {
        html +=
        '
' + news[i].leaving.all.departure_time '
';
     }

I get nothing…

Any help with this will be great.

Thanks

Body:
You have to loop over news.leaving.all:

// Let's say this is our data
var news = {
  leaving: {
    all: [{
      departure_time: '01:00'
    },
    {
      departure_time: '02:00'
    },
    {
      departure_time: '02:00'
    }]
  }
};

var html = "";
var i;
for (i = 0; i < news.leaving.all.length; i++) {
  html += '<p>' + news.leaving.all[i].departure_time + '</p>';
 }

console.log(html);


问:
Delete duplicate rows having minimum column value
I would like to delete the results generated from the below query. Please help.

```<code>(select min([Last_Updated Date]),Ticket from Hosting_Open
where Ticket in
            (select Ticket from Hosting_Open
            group by Ticket
            having count(ticket)>1 )
group by Ticket)
</code>```

The above query gets the minimum update value for those ticket which have more than one value in another column.

答:
You can use something like that:</p>

```<code>Delete Hosting_Open
From Hosting_Open
Left Outer Join (
   Select Min([Last_Updated Date]) as [Last_Updated Date], Ticket
   From Hosting_Open
   Group By Ticket
) As RowsToKeep On
   Hosting_Open.Ticket = RowsToKeep.Ticket And
   Hosting_Open.[Last_Updated Date] = RowsToKeep.[Last_Updated Date]
Where
   RowsToKeep.[Last_Updated Date] Is Null
</code>```

Body:
I would like to delete the results generated from the below query. Please help.

(select min([Last_Updated Date]),Ticket from Hosting_Open
where Ticket in
            (select Ticket from Hosting_Open
            group by Ticket
            having count(ticket)>1 )
group by Ticket)

The above query gets the minimum update value for those ticket which have more than one value in another column.

Body:
You can use something like that:

Delete Hosting_Open
From Hosting_Open
Left Outer Join (
   Select Min([Last_Updated Date]) as [Last_Updated Date], Ticket
   From Hosting_Open
   Group By Ticket
) As RowsToKeep On
   Hosting_Open.Ticket = RowsToKeep.Ticket And
   Hosting_Open.[Last_Updated Date] = RowsToKeep.[Last_Updated Date]
Where
   RowsToKeep.[Last_Updated Date] Is Null


问:
Does funnel stage of datastage need source tables have the same structure?
There are 2 source tables, and I use funnel to union them in datastage. But it reports that "The source and destination have differing nullability. [api/transfer_rep.C:199]", because the source tables have a field with different nullability.
Does funnel stage of datastage need source tables have exactly the same structure? Even if I used NVL function in the source select statement, it still reported the same error. Can somebody help? Thanks!</p>

答: Yes, Metadata of sources should be same for Funnel stage.</p>


问:
AngularJs - Routing does not work
it's the first time I am using AngularJs Routing, and I have a little bit of trouble with it. I read similar question like mine here on stackoverflow, but I can't find my mistake.

I created an self containing example, which I hope will help you find the bug. I published the example on github. But to be complete I also posted the file contents below.

Edit:

To clarifiy what is the problem.
I dont get a specific error message, but clicking on my menu will not change the view. Instead it will always load the default view.

Project Structure:

index.js

package.json

views

manager

dashboard.hbs

green.htm

main.htm

red.htm

public

css

style.css

js

DashboardController.js

index.js:

```<code>const express = require('express')
const path = require('path')
const exphbs = require('express-handlebars')
const app = express()

app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public')))

app.engine('.hbs', exphbs({
    defaultLayout: false,
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views', 'shared'),
    partialsDir: path.join(__dirname, 'views', 'shared')
}))

app.set('view engine', '.hbs')

app.get('/manager/dashboard',  function (req, res) {
    res.render('manager/dashboard')
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})
</code>```

dashboard.hbs:

```<code><!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard
    </title>
    <!-- load bootstrap css -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- Add icon library -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
    <script src="/js/DashboardController.js"></script>
    {{!--
    <style>
        body {
            padding-top: 50px;
        }
    </style>--}}
</head>

<body ng-app="myApp">

    <div class="page language-en" id="welcome-page">
        <header class="clearfix">

        </header>

        <div class="container-fluid" >
            <div class="row">
                <div class="col-sm-1 icon-col">

                    <div class="icon-bar">
                        <a class="active" ng-href="#"><i class="fa fa-dashboard"></i></a>
                        <a ng-href="#orders"><i class="fa fa-shopping-cart"></i></a>
                        <a ng-href="#products"><i class="fa fa-dropbox"></i></a>
                    </div>

                </div>

                <div class="col-sm-11 ng-view">
                    <p> Dashboard </p>
                </div>

            </div>
        </div>

    </div>
</body>

</html>
</code>```

DashboardController.js:

```<code>"use strict"

var app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
    $routeProvider
        .when("/manager/dashboard/", {
            templateUrl: "manager/main.htm"
        })
        .when("/manager/dashboard/orders", {
            templateUrl: "manager/green.htm"
        })
        .when("/manager/dashboard/products", {
            templateUrl: "manager/red.htm"
        }).otherwise({
            template: "<h1>None</h1><p>Nothing has been selected</p>"
        });

});

app.run([
    '$rootScope',
    function ($rootScope) {
        // see what's going on when the route tries to change
        $rootScope.$on('$routeChangeStart', function (event, next, current) {
            // next is an object that is the route that we are starting to go to
            // current is an object that is the route where we are currently
            if (current.originalPath && next.originalPath) {
                var currentPath = current.originalPath;
                var nextPath = next.originalPath;

                console.log('Starting to leave %s to go to %s', currentPath, nextPath);
            }

        });
    }
]);

app.run([
    '$rootScope',
    function ($rootScope) {
        // see what's going on when the route tries to change
        $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {
            // both newUrl and oldUrl are strings
            console.log('Starting to leave %s to go to %s', oldUrl, newUrl);
        });
    }
]);

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeError', function (evt, current, previous, rejection) {
        console.log('Route error', rejection);
    });
});
</code>```

style.css:

```<code>.icon-bar {
    width: 40px; /* Set a specific width */
    background-color: #555; /* Dark-grey background */
    height:100vh;
}

.icon-bar a {
    display: block; /* Make the links appear below each other instead of side-by-side */
    text-align: center; /* Center-align text */
    padding: 10px; /* Add some padding */
    transition: all 0.3s ease; /* Add transition for hover effects */
    color: white; /* White text color */
    font-size: 15px; /* Increased font-size */
}

.icon-bar a:hover {
    background-color: #000; /* Add a hover color */
}

.icon-col{
    padding-left:0px;
}

.active {
    background-color: #4CAF50; /* Add an active/current color */
}

html, body, .container-fluid, .row {
    height: 100%;
}
</code>```

green.htm, red.htm, main.htm

```<code><h1>placeholder-name</h1>
</code>```

答:
As per the AngularJs model All file should be in the static directory.

```<code>$routeProvider
    .when("/manager/dashboard/orders", {
        templateUrl: "manager/main.htm"
    });
</code>```

This code will try to load the path like

```<code>[localhost:port/manager/dashboard/orders]
</code>```

Which is GET request to the NodeJs Server and you haven't define any route for that.

so simply PUT all the files which you want to load through angular in a "PUBLIC" directory as you defined it as a static directory.

```<code>app.use(express.static(path.join(__dirname, 'public')))
</code>```

And pass all the GET request which are not defined in your express Router
like below by redirecting traffic to dashboard OR just create all your website in angularJs ignore handlebar.

```<code>app.get('*', (req, res) => {
   res.render('manager/dashboard');
})
</code>```

Title: AngularJs - Routing does not work

Body:
it's the first time I am using AngularJs Routing, and I have a little bit of trouble with it. I read similar question like mine here on stackoverflow, but I can't find my mistake.

I created an self containing example, which I hope will help you find the bug. I published the example on github. But to be complete I also posted the file contents below.

Edit:

To clarifiy what is the problem.
I dont get a specific error message, but clicking on my menu will not change the view. Instead it will always load the default view.

Project Structure:

index.js

package.json

views

manager

dashboard.hbs

green.htm

main.htm

red.htm

public

css

style.css

js

DashboardController.js

index.js:

const express = require('express')
const path = require('path')
const exphbs = require('express-handlebars')
const app = express()

app.set('views', path.join(__dirname, 'views'))
app.use(express.static(path.join(__dirname, 'public')))

app.engine('.hbs', exphbs({
    defaultLayout: false,
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views', 'shared'),
    partialsDir: path.join(__dirname, 'views', 'shared')
}))

app.set('view engine', '.hbs')

app.get('/manager/dashboard',  function (req, res) {
    res.render('manager/dashboard')
})

app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

dashboard.hbs:

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard
    </title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="/css/style.css">

    {{!--
    --}}

 Dashboard

DashboardController.js:

"use strict"

var app = angular.module("myApp", ["ngRoute"]);
app.config(function ($routeProvider) {
    $routeProvider
        .when("/manager/dashboard/", {
            templateUrl: "manager/main.htm"
        })
        .when("/manager/dashboard/orders", {
            templateUrl: "manager/green.htm"
        })
        .when("/manager/dashboard/products", {
            templateUrl: "manager/red.htm"
        }).otherwise({
            template: "
None

Nothing has been selected
"
        });

});

app.run([
    '$rootScope',
    function ($rootScope) {
        // see what's going on when the route tries to change
        $rootScope.$on('$routeChangeStart', function (event, next, current) {
            // next is an object that is the route that we are starting to go to
            // current is an object that is the route where we are currently
            if (current.originalPath && next.originalPath) {
                var currentPath = current.originalPath;
                var nextPath = next.originalPath;

                console.log('Starting to leave %s to go to %s', currentPath, nextPath);
            }

        });
    }
]);

app.run([
    '$rootScope',
    function ($rootScope) {
        // see what's going on when the route tries to change
        $rootScope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {
            // both newUrl and oldUrl are strings
            console.log('Starting to leave %s to go to %s', oldUrl, newUrl);
        });
    }
]);

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeError', function (evt, current, previous, rejection) {
        console.log('Route error', rejection);
    });
});

style.css:

.icon-bar {
    width: 40px; /* Set a specific width */
    background-color: #555; /* Dark-grey background */
    height:100vh;
}

.icon-bar a {
    display: block; /* Make the links appear below each other instead of side-by-side */
    text-align: center; /* Center-align text */
    padding: 10px; /* Add some padding */
    transition: all 0.3s ease; /* Add transition for hover effects */
    color: white; /* White text color */
    font-size: 15px; /* Increased font-size */
}

.icon-bar a:hover {
    background-color: #000; /* Add a hover color */
}

.icon-col{
    padding-left:0px;
}

.active {
    background-color: #4CAF50; /* Add an active/current color */
}

html, body, .container-fluid, .row {
    height: 100%;
}

green.htm, red.htm, main.htm

placeholder-name

Body:
As per the AngularJs model All file should be in the static directory.

$routeProvider
    .when("/manager/dashboard/orders", {
        templateUrl: "manager/main.htm"
    });

This code will try to load the path like

[localhost:port/manager/dashboard/orders]

Which is GET request to the NodeJs Server and you haven't define any route for that.

so simply PUT all the files which you want to load through angular in a "PUBLIC" directory as you defined it as a static directory.

app.use(express.static(path.join(__dirname, 'public')))

And pass all the GET request which are not defined in your express Router
like below by redirecting traffic to dashboard OR just create all your website in angularJs ignore handlebar.

app.get('*', (req, res) => {
   res.render('manager/dashboard');
})


答:
```<code>string username = email.Split('@')[0];
string domain = email.Split('@')[1];
</code>```

Title: Parse plain email address into 2 parts

Body:
How do I get the username and the domain from an email address of:

string email = "hello@example.com";
//Should parse into:
string username = "hello";
string domain = "example.com";

I'm seeking the shortest code to do this, not necessarily efficient.

Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.


问:
Php Exec with Shell Script
I have a script.sh with the following content:

```<code>#!/bin/bash
    echo You Name:
    read name
    echo You Age:
    read age
    echo Name: $name, Age: $age.
</code>```

Is it possible to pass the name and age variables to the read shell script with php?

答:
Yes you can Pass parameters to bash.

PHP:

```<code>$output = exec("./bashscript $name $age");

#!/bin/bash
</code>```

Bash:

```<code>name=$1
age=$2
</code>```

Reference: passing a variable from php to bash

Title: Php Exec with Shell Script

Body:
I have a script.sh with the following content:

#!/bin/bash
    echo You Name:
    read name
    echo You Age:
    read age
    echo Name: $name, Age: $age.

Is it possible to pass the name and age variables to the read shell script with php?

Body:
Yes you can Pass parameters to bash.

PHP:

$output = exec("./bashscript $name $age");

#!/bin/bash

Bash:

name=$1
age=$2

Reference: passing a variable from php to bash


问:
Creating path-names with variables in Python 2.7
I'd like to create some folders to store results of some simulations in a logical way with a naming system.

My code has 4 main parameters that I'm investigating and I'd like to dynamically create paths with these parameters in the pathnames, example below:

```<code>a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')
</code>```

I'll manually change the values of a-d for now as these are just a few test results. A needs to be a string but b-d are just integers.

I've seen I can do

```<code>os.path.join('./results/', test, '/outputs/'))
</code>```

Where the 'join' command will add a folder of that name in that path directory, but can I use this or a similar command to change the actual folder name with changing variables?

Thanks

答:
You're looking for str.format:</p>

```<code>>>> print("./results/{a}_{b}_{c}_{d}/outputs".format(a=a, b=b, c=c, d=d))
./results/test_2_3_4/outputs
</code>```

Body:
I'd like to create some folders to store results of some simulations in a logical way with a naming system.

My code has 4 main parameters that I'm investigating and I'd like to dynamically create paths with these parameters in the pathnames, example below:

a = 'test'
b = 2
c = 3
d = 4

os.chdir('./results/test_b_c_d/outputs')

I'll manually change the values of a-d for now as these are just a few test results. A needs to be a string but b-d are just integers.

I've seen I can do

os.path.join('./results/', test, '/outputs/'))

Where the 'join' command will add a folder of that name in that path directory, but can I use this or a similar command to change the actual folder name with changing variables?

Thanks

Body:
You're looking for str.format:

>>> print("./results/{a}_{b}_{c}_{d}/outputs".format(a=a, b=b, c=c, d=d))
./results/test_2_3_4/outputs


问:
implementing address http in searchbar
I would need some help. Basically I have a searchbar, in this searchbar I already have to preset a link that will lead to a specific search on google. The user in the search bar will write, for example, "dog" and will be brought directly to the search results on google gif. They own the http address that leads to search results. In the text below, replace the word "lolcats" with the word entered by the user in the searchbar taking into account the spaces that are recognized by% 20

I hope I'm well explained with this poor English

example link ("lolcats" Word to be replaced with the one that inserts the user into the searchbar)

https://www.google.it/search?as_st=y&tbm=isch&hl=it&as_q=lolcats&as_epq=&as_oq=&as_eq=&cr=&as_sitesearch=&safe=images&tbs=itp:animated,ift:gif#imgrc=_

答:
try to create your url string like this:

```<code>var keyWord : String // which you get from user
let part1 = "https://www.google.it/search?as_st=y&tbm=isch&hl=it&as_q="
let part2 = "&as_epq=&as_oq=&as_eq=&cr=&as_sitesearch=&safe=images&tbs=itp:animated,ift:gif#imgrc=_"

var encodedKeyWord = keyWord.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
var finalUrlString = part1 + "\(encodedKeyWord)" + part2
</code>```

hope it works :S

Title: implementing address http in searchbar

Body:
try to create your url string like this:

var keyWord : String // which you get from user
let part1 = "https://www.google.it/search?as_st=y&tbm=isch&hl=it&as_q="
let part2 = "&as_epq=&as_oq=&as_eq=&cr=&as_sitesearch=&safe=images&tbs=itp:animated,ift:gif#imgrc=_"

var encodedKeyWord = keyWord.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
var finalUrlString = part1 + "\(encodedKeyWord)" + part2

hope it works :S


问:
ImportError: cannot import name 'InsecureRequestWarning' (PYTHON3 | RPI3 | gTTS)
I'm having trouble using gTTS (Google Text to Speech) on my raspberry Pi 3. I simply did

```<code>sudo pip3 install gTTS
</code>```

to install it. But when I run my code I find this error :

```<code>File "interface.py", line 7, in <module>

from gtts import *

File "/usr/local/lib/python3.4/dist-packages/gtts/\__init__.py", line 2, in <module>

from .tts import gTTS

File "/usr/local/lib/python3.4/dist-packages/gtts/tts.py", line 4, in <module>
 from requests.packages.urllib3.exceptions import InsecureRequestWarning

ImportError: cannot import name 'InsecureRequestWarning'
</code>```

To try to solve the problem I did

```<code>sudo easy_install --upgrade pip
</code>```

Then I have uninstalled and installed again gtts but the problem persists.

Thank you very much for your help ! :(

PS : I have installed python-vlc and mutagen to make working gTTS (as I did on a windows device)

答:
Try this way.`

```<code>import urllib3`
urllib3.disable_warnings()
</code>```

Though it doesn't remove the entire warning message, still removes the Insecure Request Warning

Body:
I'm having trouble using gTTS (Google Text to Speech) on my raspberry Pi 3. I simply did

sudo pip3 install gTTS

to install it. But when I run my code I find this error :

File "interface.py", line 7, in <module>

from gtts import *

File "/usr/local/lib/python3.4/dist-packages/gtts/\__init__.py", line 2, in <module>

from .tts import gTTS

File "/usr/local/lib/python3.4/dist-packages/gtts/tts.py", line 4, in <module>
 from requests.packages.urllib3.exceptions import InsecureRequestWarning

ImportError: cannot import name 'InsecureRequestWarning'

To try to solve the problem I did

sudo easy_install --upgrade pip

Then I have uninstalled and installed again gtts but the problem persists.

Thank you very much for your help ! :(

PS : I have installed python-vlc and mutagen to make working gTTS (as I did on a windows device)

Body:
Try this way.`

import urllib3`
urllib3.disable_warnings()

Though it doesn't remove the entire warning message, still removes the Insecure Request Warning


问:
Converting a String to a List of Words?
I'm trying to convert a string to a list of words using python. I want to take something like the following:

```<code>string = 'This is a string, with words!'
</code>```

Then convert to something like this :

```<code>list = ['This', 'is', 'a', 'string', 'with', 'words']
</code>```

Notice the omission of punctuation and spaces. What would be the fastest way of going about this?

答:
Inspired by @mtrw's answer, but improved to strip out punctuation at word boundaries only:</p>

```<code>import re
import string

def extract_words(s):
    return [re.sub('^[{0}]+|[{0}]+$'.format(string.punctuation), '', w) for w in s.split()]

>>> str = 'This is a string, with words!'
>>> extract_words(str)
['This', 'is', 'a', 'string', 'with', 'words']

>>> str = '''I'm a custom-built sentence with "tricky" words like https://stackoverflow.com/.'''
>>> extract_words(str)
["I'm", 'a', 'custom-built', 'sentence', 'with', 'tricky', 'words', 'like', 'https://stackoverflow.com']
</code>```

Title: Converting a String to a List of Words?

Body:
I'm trying to convert a string to a list of words using python. I want to take something like the following:

string = 'This is a string, with words!'

Then convert to something like this :

list = ['This', 'is', 'a', 'string', 'with', 'words']

Notice the omission of punctuation and spaces. What would be the fastest way of going about this?

Body:
Inspired by @mtrw's answer, but improved to strip out punctuation at word boundaries only:

import re
import string

def extract_words(s):
    return [re.sub('^[{0}]+|[{0}]+$'.format(string.punctuation), '', w) for w in s.split()]

>>> str = 'This is a string, with words!'
>>> extract_words(str)
['This', 'is', 'a', 'string', 'with', 'words']

>>> str = '''I'm a custom-built sentence with "tricky" words like https://stackoverflow.com/.'''
>>> extract_words(str)
["I'm", 'a', 'custom-built', 'sentence', 'with', 'tricky', 'words', 'like', 'https://stackoverflow.com']


问:
Jquery method stops to works after hide and show with vuejs
I have input filed

```<code><div class="section" v-if="active==1">
    <input type="text"  name="topic" id="topic" class="form-control" autocomplete="off" spellcheck="false">
</div>
</code>```

and i have typeahead

```<code>$('#topic').typeahead({
        hint: true,
        highlight: true,
        minLength: 0
    },
    {
        name: 'topics',
        source: substringMatcher(topics)
    },
);
</code>```

When page load, typeahead works fine, but when i set active with vuejs to 0 and then back to 1 (hide and show .section) then typeahead stops to work

答:
Here's answer along with reason

You are binding the typeAhead handler to the input element using direct
binding which attaches the handler only to the elements that already exists.

That's the reason it works for the first time when the page loads.

You are using v-if which destroys and recreates the element. since the element is getting recreated dynamically
the typehead handler is not bound anymore to the subsequently rendered input elements

if you just want to show/hide the input element using   v-show is better as it just toggles the css display property
and you dont have to worry about binding of the handler as imput element is not getting removed anymore

Body:
I have input filed

    <input type="text"  name="topic" id="topic" class="form-control" autocomplete="off" spellcheck="false">

and i have typeahead

$('#topic').typeahead({
        hint: true,
        highlight: true,
        minLength: 0
    },
    {
        name: 'topics',
        source: substringMatcher(topics)
    },
);

When page load, typeahead works fine, but when i set active with vuejs to 0 and then back to 1 (hide and show .section) then typeahead stops to work


问:
Can HEIF media be streamed?
HEIF (https://en.m.wikipedia.org/wiki/High_Efficiency_Image_File_Format) seems like a great container to replace many image formats. It can use HEVC for video. But, like video formats, can it be streamed or progressively downloaded? For instance, could a cover image or thumbnail be downloaded first and displayed to the user, while waiting for additional larger resolution images, all via one file?</p>

答:
From what I've seen from WWDC session about HEIF & HEVC, it is possible to stream HEVC video via HLS. HEVC can be accessed/consumed using the following methods:

Excerpt from WWDC: (Introducing HEIF and HEVC)

Accessing HEVC

  HEVC movie support

  AVFoundation--supported media source

  PhotoKit--movies, resources and edit

  WebKit--hardware support and macOS desktops

  HTTP Live Streaming (HLS)

  Apple apps

But I am not really sure about the progressive download.

Title: Can HEIF media be streamed?


问:
How to load chat history on top of recycler view android
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.</p>

```<code>                              if (Status.equals("1")) {
                                historyList = resp.getHistory();
                                Log.i("history size",String.valueOf(resp.getHistory().size()));
                                String historysize = String.valueOf(resp.getHistory().size());
                                Message message = new Message();
                                for (int i = 0; i < resp.getHistory().size(); i++) {
                                    String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
                                    String txtmsg = resp.getHistory().get(i).getMessage();
                                    String username = String.valueOf(resp.getHistory().get(i).getFromUserName());

                                    if (fromusertoken.equals(user_token)) {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(true);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);

                                    }
                                    else {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(false);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);
                                    }
                                }

                                messageAdapter.notifyDataSetChanged();
                                onItemsLoadComplete();

                                Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
                }

            }
</code>```

答:
There is a way to set the item on top by editing the adapter class not the activity. We have to add the item list like messagelist.add(0,message). Now only i found. For your regular chat you have to add as normal like messagelist.add(message). This will add the item at bottom. Hope this will be useful for others.

```<code>public void add(Message message) {
    messageList.add(message);
    notifyItemInserted(messageList.size() - 1);
}
public void add(int i,Message message) {
    messageList.add(0,message);
    notifyItemInserted(messageList.size() - 1);
}
</code>```

Body:
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.

                              if (Status.equals("1")) {
                                historyList = resp.getHistory();
                                Log.i("history size",String.valueOf(resp.getHistory().size()));
                                String historysize = String.valueOf(resp.getHistory().size());
                                Message message = new Message();
                                for (int i = 0; i < resp.getHistory().size(); i++) {
                                    String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
                                    String txtmsg = resp.getHistory().get(i).getMessage();
                                    String username = String.valueOf(resp.getHistory().get(i).getFromUserName());

                                    if (fromusertoken.equals(user_token)) {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(true);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);

                                    }
                                    else {
                                        Message messages = new Message();
                                        messages.setUser_token(fromusertoken);
                                        messages.setUsername(username);
                                        messages.setIsMine(false);
                                        messages.setMessage(txtmsg);
                                        messageAdapter.add(messages);
                                    }
                                }

                                messageAdapter.notifyDataSetChanged();
                                onItemsLoadComplete();

                                Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                            }

                        } else {
                            Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
                }

            }

Body:
There is a way to set the item on top by editing the adapter class not the activity. We have to add the item list like messagelist.add(0,message). Now only i found. For your regular chat you have to add as normal like messagelist.add(message). This will add the item at bottom. Hope this will be useful for others.

public void add(Message message) {
    messageList.add(message);
    notifyItemInserted(messageList.size() - 1);
}
public void add(int i,Message message) {
    messageList.add(0,message);
    notifyItemInserted(messageList.size() - 1);
}


问:
How to compress IPV6 address using javascript?
I have seen the code to compress IPV6 in java.
The link specifies the same.
Below is the code in Java . String resultString = subjectString.replaceAll("((?::0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2");

But in Javascript I am confused as how can I get the regex expression to match the same . Can you share some pointers here?

Example : fe80:00:00:00:8e3:a11a:2a49:1148
Result : fe80::8e3:a11a:2a49:1148

答:
You can do it by replacing

```<code>\b(?:0+:){2,}
</code>```

with

```<code>:
</code>```

function compIPV6(input) {
  return input.replace(/\b(?:0+:){2,}/, ':');
}

document.write(compIPV6('2001:db8:0:0:0:0:2:1') + '
');
document.write(compIPV6('fe80:00:00:00:8e3:a11a:2a49:1148' + '
'));```

Check it out at regex101.

Body:
You can do it by replacing

\b(?:0+:){2,}

with

:

function compIPV6(input) {
  return input.replace(/\b(?:0+:){2,}/, ':');
}

document.write(compIPV6('2001:db8:0:0:0:0:2:1') + '<br/>');
document.write(compIPV6('fe80:00:00:00:8e3:a11a:2a49:1148' + '<br/>'));

Check it out at regex101.


问:
Socialite laravel 5.4 Facebook login error (ClientException in RequestException.php line 111)
in past signup with Facebook functionality working fine suddenly when i signup or Login with facebook then i am facing this error

ClientException in RequestException.php line 111: Client error: GET
  https://graph.facebook.com/v2.8/me?access_token=&fields=name,email,gender,verified,link&appsecret_proof=5fb0d218f94cb8024712269c053f0186d360efd82cd3b588eaf621e0c79c
  resulted in a 400 Bad Request response: {"error":{"message":"An active
  access token must be used to query information about the current
  user.","type":"OAuthExce (truncated...)

i am using Socialite Package

Note: For some reasons i can't update composer or complete socialite package

Note: i had some changes in socialite packages for some purpose. if i update whole package then previous changes will be affect.. i did some changes in LinkedInProvider and GoogleProvider files.. i need proper solution for this error

My project is live and users facing this problem. any help will be appreciate..

答: I was facing the same problem. I found that by updating to the latest version, the issue got fixed. Socialite</p>


问:
How to sum cardView item values in recyclerView and display the total sum on a textView outside the recyclerView
I am working on restaurant app wants to display selected items for order, with their price per item and total price (count*price) of each item. I want to add those total price of list of card items and display on text view outside Recycler View that will change dynamically.

Inside each card View, there are two buttons(- and +) that change the count value for each item so that it changes the total price of each item.

Here is My adapter class

```<code>public class MyListsToOrderAdapter extends
    RecyclerView.Adapter<MyListsToOrderAdapter.MyHOldd>{

ArrayList<Element> element;
Context ctx;
TextView textView;
String c;
String db = "Elements";
String dbp = "Prices";
PriceDao priceDao;
ElementDao elementDao;
int count=0;
private LayoutInflater inflater;
float v1,v4,v5,v2,v3,v6;
float x1,x2,x3=0;

public MyListsToOrderAdapter( ArrayList<Element> element,Context ctx,TextView textView) {

    this.textView=textView;
    this.ctx = ctx;
    this.element = element;
    inflater = LayoutInflater.from(ctx);

}

@Override
public MyListsToOrderAdapter.MyHOldd onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.card_lists_to_order,parent,false);
    MyHOldd holder = new MyHOldd(view,ctx,element);

    return holder;

}
@Override
public void onBindViewHolder(final MyListsToOrderAdapter.MyHOldd holder, final int position) {

      priceDao=setUpDBPrice();
  String bs=  element.get(position).getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bs)).list();
    String pricev = priceList.get(0).getPriceValue();
      // Calculating the total price of each
    v1 = Float.parseFloat(pricev);
    v2= Float.parseFloat(element.get(position).getCount());
    v3=v1*v2;

    final String res = String.valueOf(v3);

    holder.listName.setText(element.get(position).getDescription());
    holder.add.setImageResource(R.drawable.add);
    holder.sub.setImageResource(R.drawable.minus);
    holder.pricess.setText(pricev);
    holder.totalPriceT.setText(res);
    holder.status.setText(element.get(position).getCount());

         if(v5==1)v5=v6;
         else if(v5==2) v5=-v6;
          else if(v5==3) v5=0;
         else  v5=v3;
    v4=v4+v5;

    String ch = String.valueOf(v4);
    textView.setText("Total: "+ch);
}

@Override
public int getItemCount() {
    return element.size();
}

 class MyHOldd extends RecyclerView.ViewHolder implements View.OnClickListener {

     public TextView listName;
     public TextView pricess;
     public  TextView status;
     public TextView totalPriceT;
     public ImageView add;
     public ImageView sub;
     int count;

     Context ctx;
     ArrayList<Element> element = new ArrayList<>();
      ElementDao elementDao = setupDbElement();

     public MyHOldd(View itemView, Context ctx, ArrayList<Element> element) {
         super(itemView);
         this.ctx=ctx;
         this.element=element;

         listName = (TextView)itemView.findViewById(R.id.TitemName);
         pricess = (TextView)itemView.findViewById(R.id.TitemPrice);
         status = (TextView)itemView.findViewById(R.id.Tstatus);
         totalPriceT = (TextView)itemView.findViewById(R.id.totalPrice);
         add = (ImageView) itemView.findViewById(R.id.TplusSign);
         sub = (ImageView) itemView.findViewById(R.id.TminusSign);
         add.setOnClickListener(this);
         sub.setOnClickListener(this);
     }
     @Override
     public void onClick(View view) {
         int position = getAdapterPosition();
         Element element = this.element.get(position);
         String bd=  element.getCode();
         List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bd)).list();
         String pricev = priceList.get(0).getPriceValue();
         // Calculating the total price of each
         v6 = Float.parseFloat(pricev);
         x3=v6*count;
             v5=0;
         count= Integer.parseInt(element.getCount());
         if(view.getId()==add.getId()) {
             count = count+1;
             c = String.valueOf(count);
             element.setCount(c);
             elementDao.update(element);
             notifyDataSetChanged();
             v5=1;
         } else if (view.getId()==sub.getId()) {
             if(count==0) {
                 count = 0;
                 c = String.valueOf(count);
                 element.setCount(c);
                 elementDao.update(element);
                 notifyDataSetChanged();
                 v5=3;
             }
             else {
                 count = count-1;
                 c = String.valueOf(count);
                 element.setCount(c);
                 elementDao.update(element);
                 notifyDataSetChanged();
                 v5=2;
             }
         }
         count= Integer.parseInt(element.getCount());

     }
 }
</code>```

答:
@Habatamu
Everytime you click add or sub imageview the textview for totalSum should be updated. In your case, the override method onclick does not seems to be updating the  totalSum.</p>

Body:
I am working on restaurant app wants to display selected items for order, with their price per item and total price (count*price) of each item. I want to add those total price of list of card items and display on text view outside Recycler View that will change dynamically.

Inside each card View, there are two buttons(- and +) that change the count value for each item so that it changes the total price of each item.

Here is My adapter class

public class MyListsToOrderAdapter extends
    RecyclerView.Adapter<MyListsToOrderAdapter.MyHOldd>{

ArrayList<Element> element;
Context ctx;
TextView textView;
String c;
String db = "Elements";
String dbp = "Prices";
PriceDao priceDao;
ElementDao elementDao;
int count=0;
private LayoutInflater inflater;
float v1,v4,v5,v2,v3,v6;
float x1,x2,x3=0;

public MyListsToOrderAdapter( ArrayList<Element> element,Context ctx,TextView textView) {

    this.textView=textView;
    this.ctx = ctx;
    this.element = element;
    inflater = LayoutInflater.from(ctx);

}

@Override
public MyListsToOrderAdapter.MyHOldd onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = inflater.inflate(R.layout.card_lists_to_order,parent,false);
    MyHOldd holder = new MyHOldd(view,ctx,element);

    return holder;

}
@Override
public void onBindViewHolder(final MyListsToOrderAdapter.MyHOldd holder, final int position) {

      priceDao=setUpDBPrice();
  String bs=  element.get(position).getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bs)).list();
    String pricev = priceList.get(0).getPriceValue();
      // Calculating the total price of each
    v1 = Float.parseFloat(pricev);
    v2= Float.parseFloat(element.get(position).getCount());
    v3=v1*v2;

    final String res = String.valueOf(v3);

    holder.listName.setText(element.get(position).getDescription());
    holder.add.setImageResource(R.drawable.add);
    holder.sub.setImageResource(R.drawable.minus);
    holder.pricess.setText(pricev);
    holder.totalPriceT.setText(res);
    holder.status.setText(element.get(position).getCount());

         if(v5==1)v5=v6;
         else if(v5==2) v5=-v6;
          else if(v5==3) v5=0;
         else  v5=v3;
    v4=v4+v5;

    String ch = String.valueOf(v4);
    textView.setText("Total: "+ch);
}

@Override
public int getItemCount() {
    return element.size();
}

 class MyHOldd extends RecyclerView.ViewHolder implements View.OnClickListener {

     public TextView listName;
     public TextView pricess;
     public  TextView status;
     public TextView totalPriceT;
     public ImageView add;
     public ImageView sub;
     int count;

     Context ctx;
     ArrayList<Element> element = new ArrayList<>();
      ElementDao elementDao = setupDbElement();

     public MyHOldd(View itemView, Context ctx, ArrayList<Element> element) {
         super(itemView);
         this.ctx=ctx;
         this.element=element;

         listName = (TextView)itemView.findViewById(R.id.TitemName);
         pricess = (TextView)itemView.findViewById(R.id.TitemPrice);
         status = (TextView)itemView.findViewById(R.id.Tstatus);
         totalPriceT = (TextView)itemView.findViewById(R.id.totalPrice);
         add = (ImageView) itemView.findViewById(R.id.TplusSign);
         sub = (ImageView) itemView.findViewById(R.id.TminusSign);
         add.setOnClickListener(this);
         sub.setOnClickListener(this);
     }
     @Override
     public void onClick(View view) {
         int position = getAdapterPosition();
         Element element = this.element.get(position);
         String bd=  element.getCode();
         List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bd)).list();
         String pricev = priceList.get(0).getPriceValue();
         // Calculating the total price of each
         v6 = Float.parseFloat(pricev);
         x3=v6*count;
             v5=0;
         count= Integer.parseInt(element.getCount());
         if(view.getId()==add.getId()) {
             count = count+1;
             c = String.valueOf(count);
             element.setCount(c);
             elementDao.update(element);
             notifyDataSetChanged();
             v5=1;
         } else if (view.getId()==sub.getId()) {
             if(count==0) {
                 count = 0;
                 c = String.valueOf(count);
                 element.setCount(c);
                 elementDao.update(element);
                 notifyDataSetChanged();
                 v5=3;
             }
             else {
                 count = count-1;
                 c = String.valueOf(count);
                 element.setCount(c);
                 elementDao.update(element);
                 notifyDataSetChanged();
                 v5=2;
             }
         }
         count= Integer.parseInt(element.getCount());

     }
 }


问:
-I/path and -L/path put in code
I use command to compile:

```<code>gcc -o hello hello.c -I/usr/local/include -I/usr/local/include/sphinxbase -I/usr/local/include/pocketsphinx -L/usr/local/lib -lpocketsphinx -lsphinxbase
</code>```

I want compile use only gcc -o hello hello.c

Can I put this path in code?

答:
Some versions of gcc support 'response files', whereby you can put most of those options into a text file, and reference it from the command line:

```<code>response.txt
-I/usr/local/include
-I/usr/local/include/sphinxbase
-I/usr/local/include/pocketsphinx
-L/usr/local/lib
-lpocketsphinx
-lsphinxbase
</code>```

gcc -o hello hello.c @response.txt

But really, I agree with @chris_turner, use a make file.

Title: -I/path and -L/path put in code

Body:
I use command to compile:

gcc -o hello hello.c -I/usr/local/include -I/usr/local/include/sphinxbase -I/usr/local/include/pocketsphinx -L/usr/local/lib -lpocketsphinx -lsphinxbase

I want compile use only gcc -o hello hello.c

Can I put this path in code?

Body:
Some versions of gcc support 'response files', whereby you can put most of those options into a text file, and reference it from the command line:

response.txt
-I/usr/local/include
-I/usr/local/include/sphinxbase
-I/usr/local/include/pocketsphinx
-L/usr/local/lib
-lpocketsphinx
-lsphinxbase

gcc -o hello hello.c @response.txt

But really, I agree with @chris_turner, use a make file.


问:
How to send date from one component to another component by onclick function using observers on Polymer 1.0? (without using local-storage)
I want to send the 'categorylist' from 'submenu-list.html' to the component 'category.html' by the onclick function 'response' using observer. how can I do it (without using local-storage)? (Kindly show by editing the code)

/* submenu-list.html */

```<code><link rel="import" href="../../bower_components/polymer/polymer.html">
 <dom-module id="submenu-list">
  <template>
    <paper-menu>
      <paper-item><a onclick="response">My Menu Items</a></paper-item>
    </paper-menu>
  </template>
  <script>
    Polymer({
     is:'submenu-list',
     properties: {
        categorylist: {
          type: Array,
          value:[]
        }
     },
     response: function() {

     }
})
  </script>
 </dom-module>
</code>```

/* category.html */

```<code><link rel="import" href="../../bower_components/polymer/polymer.html">
 <dom-module id="category">
  <template>

  </template>
  <script>
    Polymer({
     is:'category',
})
  </script>
 </dom-module>
</code>```

答:
well the quick answer is you can`t. At least from the information you gave. Since these components seem not to be connected somehow there is no direct way to communicate between components. Possible Solutions are you write the Information into the Local Storage but as you stated you don´t want to do that. Other solutions might be redux or a rest Service but i guess thats also not an option. The last suggestion is that these both Components are siblings? then you could just use Polymer default databinding? for instance:

```<code><submenu-list categorylist="{{categorylist}}"></submenu-list>
<category categorylist="{{categorylist}}"></category>
</code>```

and then in both components add:

```<code>categorylist: {
      type: Array,
      value:[],
      notify:true,
      observer: '_categorylistChanged'
    }
</code>```

Now you have to implement the _categorylistChanged function which will be called when categorylist was changed.

```<code> _categorylistChanged: function(newValue, oldValue){
 //do something
 }
</code>```

Dont´t forget when you want to change categorylist to call

```<code>this.set('categorylist', //your new value)
</code>```

Otherwise the observers won´t be triggered.

Body:
I want to send the 'categorylist' from 'submenu-list.html' to the component 'category.html' by the onclick function 'response' using observer. how can I do it (without using local-storage)? (Kindly show by editing the code)

/* submenu-list.html */

<link rel="import" href="../../bower_components/polymer/polymer.html">
 <dom-module id="submenu-list">
  <template>
    <paper-menu>
      <paper-item>My Menu Items</paper-item>
    </paper-menu>
  </template>

 </dom-module>

/* category.html */

<link rel="import" href="../../bower_components/polymer/polymer.html">
 <dom-module id="category">
  <template>

  </template>

 </dom-module>

Body:
well the quick answer is you can`t. At least from the information you gave. Since these components seem not to be connected somehow there is no direct way to communicate between components. Possible Solutions are you write the Information into the Local Storage but as you stated you don´t want to do that. Other solutions might be redux or a rest Service but i guess thats also not an option. The last suggestion is that these both Components are siblings? then you could just use Polymer default databinding? for instance:

<submenu-list categorylist="{{categorylist}}"></submenu-list>
<category categorylist="{{categorylist}}"></category>

and then in both components add:

categorylist: {
      type: Array,
      value:[],
      notify:true,
      observer: '_categorylistChanged'
    }

Now you have to implement the _categorylistChanged function which will be called when categorylist was changed.

 _categorylistChanged: function(newValue, oldValue){
 //do something
 }

Dont´t forget when you want to change categorylist to call

this.set('categorylist', //your new value)

Otherwise the observers won´t be triggered.


问:
Android custom notification sound
I have to change notification sound in my app. The sound is downloaded from the server so it is stored in my app storage. Unfortunately, the sound is not played.

```<code>File folder = new File(context.getFilesDir() + File.separator + "sounds");
File sound = new File(folder, "my-sound.mp3");

Notification notification = new Builder(context)
            .setContentText("test")
            .setContentTitle(context.getText(R.string.app_name))
            .setSmallIcon(R.drawable.notification_icon)
            .setSound(Uri.parse(sound.toString()))
            .build();
</code>```

I also tried to get this Uri differently:

```<code>.setSound(Uri.parse(sound.toString()))
</code>```

Or save it in MediaStore:

```<code>ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sound.getAbsolutePath());
Uri soundUri = context.getContentResolver().insert(uri, values);
</code>```

Sound Uri path is now equal content://media/external/audio/media/1265 and still its not working.

If I set default sound then it is working correctly. .setSound(RingtoneManager.getDefaultUri(TYPE_NOTIFICATION))

答:
For Custom Sound Use this

```<code>NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
     mBuilder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));
</code>```

for Default Notification sound use this

```<code>Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
</code>```

Title: Android custom notification sound

Body:
I have to change notification sound in my app. The sound is downloaded from the server so it is stored in my app storage. Unfortunately, the sound is not played.

File folder = new File(context.getFilesDir() + File.separator + "sounds");
File sound = new File(folder, "my-sound.mp3");

Notification notification = new Builder(context)
            .setContentText("test")
            .setContentTitle(context.getText(R.string.app_name))
            .setSmallIcon(R.drawable.notification_icon)
            .setSound(Uri.parse(sound.toString()))
            .build();

I also tried to get this Uri differently:

.setSound(Uri.parse(sound.toString()))

Or save it in MediaStore:

ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, sound.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "My Song title");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
values.put(MediaStore.Audio.Media.ARTIST, "Some Artist");
values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(sound.getAbsolutePath());
Uri soundUri = context.getContentResolver().insert(uri, values);

Sound Uri path is now equal content://media/external/audio/media/1265 and still its not working.

If I set default sound then it is working correctly. .setSound(RingtoneManager.getDefaultUri(TYPE_NOTIFICATION))

Body:
For Custom Sound Use this

NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
     mBuilder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));

for Default Notification sound use this

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);


问:
Entity framework add's new record in one-to-one relation while object has an ID
I'm new to c# and I have a basic problem with saving/updating data.
With two classes :

```<code>public class User
    {
        public int UserId { get; set; }
        public string Email { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        public DateTime RegisteredDate { get; set; }

 public class Task
    {
        public int TaskId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Comment { get; set; }
        public User DeclaredBy { get; set; }

    }
</code>```

I'm trying to save a task object (new or updated) with DeclaredBy field set

```<code>dbContext.Tasks.AddOrUpdate(task);
dbContext.SaveChanges();
</code>```

User set in DeclaredBy field has an ID, but after executing SaveChanges() a new record of User appears in DB.

答:
This is how EF works, if you add entity with other related entity then both will be stored in DB. If you want to store only one then you need to set other navigation properties to null and only set foreign key id, which currently you don't have, you should add property:

```<code>public int DeclatedById { get; set; }
</code>```

Btw. this is very common problem and a lot of projects has duplicate values in db.

Maybe I should add that this will happen only if entity wasn't traced by EF context and was attached to it.

Body:
I'm new to c# and I have a basic problem with saving/updating data.
With two classes :

public class User
    {
        public int UserId { get; set; }
        public string Email { get; set; }
        public string Login { get; set; }
        public string Password { get; set; }
        public DateTime RegisteredDate { get; set; }

 public class Task
    {
        public int TaskId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Comment { get; set; }
        public User DeclaredBy { get; set; }

    }

I'm trying to save a task object (new or updated) with DeclaredBy field set

dbContext.Tasks.AddOrUpdate(task);
dbContext.SaveChanges();

User set in DeclaredBy field has an ID, but after executing SaveChanges() a new record of User appears in DB.

Body:
This is how EF works, if you add entity with other related entity then both will be stored in DB. If you want to store only one then you need to set other navigation properties to null and only set foreign key id, which currently you don't have, you should add property:

public int DeclatedById { get; set; }

Btw. this is very common problem and a lot of projects has duplicate values in db.

Maybe I should add that this will happen only if entity wasn't traced by EF context and was attached to it.


问:
implementing include/sched.h functions
I wanted to study how threads can be assigned manually to specific cores on a multi core machine. I found that include/sched.h defines some macros and functions (sched_setaffinity, etc.)that can help for this. However, the functions are extern'ed and I can't find their definitions. Are those functions implemented anywhere? If yes, where and is it possible to override the default implementation? If no, how can I implement them?

And would adding new implementation imply that I have to recompile my Linux kernel?

答:
Check the code for BFS which should show you how to implement your own CPU scheduler.

//edit yes adding a new scheduler impl means you have to recompile your kernel, however you can always just test it with qemu -kernel /path/to/new/kerenl -initrd something to make sure your code doesn't crash right away before testing it on the real machine.

Title: implementing include/sched.h functions


问:
Concat javascript arrays as array of arrays
I have these arrays:

```<code>arr1 = ['29.5',  32035];
arr2 = ['30.5',  32288];
arr3 = ['31.5',  31982];
arr4 = ['1.6',  31768];
</code>```

As a result I want to have something like this:

```<code>result = [['29.5',  32035], ['30.5',  32288], ['31.5',  31982], ['1.6',  31768]];
</code>```

I means the result is array created by another arrays. The question is, how I can concat the arrays. result.push.apply(result, arr1); etc. give me array made by final values.

Thank you for any advice.

答:
Actually you can just do

```<code>var result = [arr1, arr2, arr3, arr4];
</code>```

Or

```<code>var result = [];
result[0] = arr1;
result[1] = arr2;
result[2] = arr3;
result[3] = arr4;
</code>```

Or

```<code>var result = [];
result.push(arr1);
result.push(arr2);
result.push(arr3);
result.push(arr4);
</code>```

Body:
I have these arrays:

arr1 = ['29.5',  32035];
arr2 = ['30.5',  32288];
arr3 = ['31.5',  31982];
arr4 = ['1.6',  31768];

As a result I want to have something like this:

result = [['29.5',  32035], ['30.5',  32288], ['31.5',  31982], ['1.6',  31768]];

I means the result is array created by another arrays. The question is, how I can concat the arrays. result.push.apply(result, arr1); etc. give me array made by final values.

Thank you for any advice.

Body:
Actually you can just do

var result = [arr1, arr2, arr3, arr4];

Or

var result = [];
result[0] = arr1;
result[1] = arr2;
result[2] = arr3;
result[3] = arr4;

Or

var result = [];
result.push(arr1);
result.push(arr2);
result.push(arr3);
result.push(arr4);


问:
reCaptcha blocked frame (SOP?)
Got a Typo3 Installation where i've added Googles reCaptcha to a Form.

Did that already successful on other Typo3 installations, but this time, i get the blocked frame error in the Browser.

```<code>Blocked frame with origin "https://www.google.com" from accessing a cross-origin frame.
  at um.f.hc (https://www.gstatic.com/recaptcha/api2/....)
</code>```

This happens two times and after that, i get this massage in the frontend.

Please upgrade to a supported browser to get a reCAPTCHA challenge.

Alternatively if you think you are getting this page in error, please check your internet connection and reload.

Why is this happening to me?

This is happening in all Browsers i checked (Chrome, FF, IE11).

To include the reCaptcha i've adde the following to the Template:

```<code>  <script src="//www.google.com/recaptcha/api.js" async defer></script>
  <script type="text/javascript">
    var captchaCallback = function() { document.getElementById("captchaResponse").value = document.getElementById("g-recaptcha-response").value }
    var onSuccess = function(response) {
      var errorDivs = document.getElementsByClassName("recaptcha-error");
      if (errorDivs.length) {
        errorDivs[0].className = "";
      }
      var errorMsgs = document.getElementsByClassName("recaptcha-error-message");
      if (errorMsgs.length) {
        errorMsgs[0].parentNode.removeChild(errorMsgs[0]);
      }
      captchaCallback();
      document.getElementById("fhcallback").submit();
    };
  </script>
  <input type="hidden" id="captchaResponse" name="fhcb[recaptcha]" value="" />
  <div id="recaptcha-demo" class="g-recaptcha" data-sitekey="[MYPUBLICKEY]" data-callback="onSuccess" data-bind="inp-submit"></div>
  <button class="orderButton bold" id="inp-submit" ###submit_nextStep###>Senden</button>
</code>```

And in PHP:

```<code>$secret = '[MYSECRETKEY]';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$apiResponse = json_decode(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($url.'?secret='.$secret.'&response='.$this->gp[$this->formFieldName]), true);
if($apiResponse['success'] == FALSE) {
    $checkFailed = $this->getCheckFailed();
}
</code>```

The Form is not visible on pageload. Its a slide in at the right side of the page, after clicking its toggle element.

I'am out of ideas and the client is bugging me already.

答:
I found the Issue. On this Installation, the JavaScript Library Mootools was included.

After removing the include of Mootools, no further problems with blocked Frames occurred.

Title: reCaptcha blocked frame (SOP?)

Body:
Got a Typo3 Installation where i've added Googles reCaptcha to a Form.

Did that already successful on other Typo3 installations, but this time, i get the blocked frame error in the Browser.

Blocked frame with origin "https://www.google.com" from accessing a cross-origin frame.
  at um.f.hc (https://www.gstatic.com/recaptcha/api2/....)

This happens two times and after that, i get this massage in the frontend.

Please upgrade to a supported browser to get a reCAPTCHA challenge.

Alternatively if you think you are getting this page in error, please check your internet connection and reload.

Why is this happening to me?

This is happening in all Browsers i checked (Chrome, FF, IE11).

To include the reCaptcha i've adde the following to the Template:

  <input type="hidden" id="captchaResponse" name="fhcb[recaptcha]" value="" />

  <button class="orderButton bold" id="inp-submit" ###submit_nextStep###>Senden</button>

And in PHP:

$secret = '[MYSECRETKEY]';
$url = 'https://www.google.com/recaptcha/api/siteverify';
$apiResponse = json_decode(\TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($url.'?secret='.$secret.'&response='.$this->gp[$this->formFieldName]), true);
if($apiResponse['success'] == FALSE) {
    $checkFailed = $this->getCheckFailed();
}

The Form is not visible on pageload. Its a slide in at the right side of the page, after clicking its toggle element.

I'am out of ideas and the client is bugging me already.


问:
How do i install xcode on my ubuntu machine?
I have Lenovo Ideapad310 laptop with Ubuntu OS. But for iOS development I want to install Xcode in my machine, so how can i install Xcode in my machine?
please anyone help me??</p>

答:
First: You can't install Xcode on Ubuntu it's restricted only for Mac OS.

Second: I assume you want Swift, which you can install it over terminal using this command

```<code>sudo apt-get install clang
</code>```

If you installed the Swift toolchain on Linux to a directory other than the system root, you will need to run the following command, using the actual path of your Swift installation:

```<code>export PATH=/path/to/Swift/usr/bin:"${PATH}"
</code>```

You can verify that you are running the expected version of Swift by entering the swift command and passing the --version flag:

```<code>swift --version
</code>```

for IDE you might use Visual Studio Code and install Swift plugin.

Good Luck

Body:
First: You can't install Xcode on Ubuntu it's restricted only for Mac OS.

Second: I assume you want Swift, which you can install it over terminal using this command

sudo apt-get install clang

If you installed the Swift toolchain on Linux to a directory other than the system root, you will need to run the following command, using the actual path of your Swift installation:

export PATH=/path/to/Swift/usr/bin:"${PATH}"

You can verify that you are running the expected version of Swift by entering the swift command and passing the --version flag:

swift --version

for IDE you might use Visual Studio Code and install Swift plugin.

Good Luck


问:
Create a Gmail share link
I would like to put a button on my one page web application that allows a user to send a link through Gmail. I found that some websites such as addthis.com provide such a button, however this button automatically uses the link from the url bar. Since I have a one page web application the link in the url bar will always be the same. I need to be able to to put the link in the button myself (which is possible with, for example, the Facebook and Twitter share buttons).

How can I create a Gmail button that can be used to share a link?

Thank you.

答: Try the official Google+ Share button. There's a field there where you'll specify the "URL to share". Since you're only using one URL, this might work in your favor.

Title: Create a Gmail share link


问:
Is it possible to mark a property shown in a property grid as a password field
I'm using C# and have a windows form containing a property grid control.

I have assigned the SelectedObject of the propertygrid to a settings file, which displays and lets me edit the settings. However one of the settings is a password - and I'd like it to display asterisks in the field rather than the plain text value of the password setting.

The field will be encrypted when saved, but I want it to behave like a normal password entry box with asterisks displayed when the user is entering in the password.

I'm wondering if there is an attribute that can be applied to the setting property to mark it as being a password?

Thanks.

答:
Starting with .Net 2, you can use the PasswordPropertyTextAttribute attached to your password property.

Hope this helps.

OwnerDisplayName: Nicolas Cadilhac


问:
Invert some values in SQL Server
I have a table like this one:

```<code>ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95
</code>```

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

```<code>SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...
</code>```

Who can help? I'm using SQL Server 2008 Express Edition

答:
Perhaps I'm oversimplifying, but could you do this:</p>

```<code>select sum(abs(Value)) as Total
    from Table
    where Account = 110
        or DepAccount = 110
</code>```

Title: Invert some values in SQL Server

Body:
I have a table like this one:

ID   |   Description  |  Account  |  DepAccount  |  Value
----------------------------------------------------------
0    |  Something     | 110       | 0            | 500,50
1    |  Something x   | 0         | 110          | -320,95

Now I need a query to sum the values but there is an issue with it.

Like in the example, if the account is 110, it is fine, if the DepAccount is 110, I need to invert the value so I sum 320,95 instead of -320,95

So the query should return value: 821,45

So something like:

SELECT SUM(Value) As Total
FROM Table
WHERE Account = 110 OR DepAccount = 110 WHERE etc...

Who can help? I'm using SQL Server 2008 Express Edition

Body:
Perhaps I'm oversimplifying, but could you do this:

select sum(abs(Value)) as Total
    from Table
    where Account = 110
        or DepAccount = 110


问:
Getting hover to work despite same class
I'm trying to get my div element to change pictures. The problem I'm having is that all the div that I've selected are changing. I've tried the .each() function but I haven't been able to get it to work.

$('.product_category_item div').hover(function() {
  $('.main_image').each(function() {
    $(this).css("display", "none");
  });

  $('.hover_image').each(function() {
    $(this).css("display", "block");
  });
}, function() {
  $('.main_image').each(function() {
    $(this).css("display", "block");
  });

  $('.hover_image').each(function() {
    $(this).css("display", "none");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-lg-3 product_category_item">

    <div>
      <img class="main_image" src="img/water-faucet1.jpg">
      <img class="hover_image" src="img/gold-faucet1.jpg">
      <p>
        taps
      </p>
    </div>

</div>
<div class="col-lg-3 product_category_item">
  <div>
    <img class="main_image" src="img/block_seal.jpg">
    <img class="hover_image" src="img/round_seal.jpg">

    <p>
      seals
    </p>
  </div>
</div>
<div class="col-lg-3 product_category_item">
  <div>
    <img class="main_image" src="img/hinge1.jpg">
    <img class="hover_image" src="img/hinge2.jpg">

    <p>
      hinges
    </p>
  </div>
</div>
<div class="col-lg-3 product_category_item">
  <div>
    <img class="main_image" src="img/handle1.jpg">
    <img class="hover_image" src="img/handle2.jpg">

    <p>
      handles
    </p>
  </div>
</div></code>```

答:
Try changing your code to below.</p>

```<code>$('.product_category_item div').hover(function(){
   $(this).find('.main_image').hide();
   $(this).find('.hover_image').show();
}, function(){
   $(this).find('.main_image').show();
   $(this).find('.hover_image').hide();
});
</code>```

Body:
I'm trying to get my div element to change pictures. The problem I'm having is that all the div that I've selected are changing. I've tried the .each() function but I haven't been able to get it to work.

$('.product_category_item div').hover(function() {
  $('.main_image').each(function() {
    $(this).css("display", "none");
  });

  $('.hover_image').each(function() {
    $(this).css("display", "block");
  });
}, function() {
  $('.main_image').each(function() {
    $(this).css("display", "block");
  });

  $('.hover_image').each(function() {
    $(this).css("display", "none");
  });
});

        taps

      seals

      hinges

      handles

Body:
Try changing your code to below.

$('.product_category_item div').hover(function(){
   $(this).find('.main_image').hide();
   $(this).find('.hover_image').show();
}, function(){
   $(this).find('.main_image').show();
   $(this).find('.hover_image').hide();
});


问:
How to set a class attribute to a Symfony form input with an attribut from entity linked
I have in my form a "beds" attribute, an entity linked to another "bedroom".
I would like for each input to add a class with the id of the linked entity "bedroom".

```<code>$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                  ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'attr' => array(
        'class' => function ($bed) {
            return $bed->getBedroom()->getId();
        }
     ),
 ))
</code>```

I have two problems:

'attr' => array('class'=>'test) return a class attribut in the div  containing the input, not a class attribut in the input.

This previous code does not work and returns:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Closure could not be converted to string") in form_div_layout.html.twig at line 358.

Thank you for your help

答:
For EntityType it would rather look like this: </p>

```<code>$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                    ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'choice_attr' => function (Bed $bed, $key, $index) {
            return ['class' => $bed->getBedroom()->getId();];
    },
))
</code>```

Body:
I have in my form a "beds" attribute, an entity linked to another "bedroom".
I would like for each input to add a class with the id of the linked entity "bedroom".

$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                  ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'attr' => array(
        'class' => function ($bed) {
            return $bed->getBedroom()->getId();
        }
     ),
 ))

I have two problems:

'attr' => array('class'=>'test) return a class attribut in the div  containing the input, not a class attribut in the input.

This previous code does not work and returns:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Closure could not be converted to string") in form_div_layout.html.twig at line 358.

Thank you for your help

Body:
For EntityType it would rather look like this:

$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                    ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'choice_attr' => function (Bed $bed, $key, $index) {
            return ['class' => $bed->getBedroom()->getId();];
    },
))