问:
GET https://127.0.0.1:9000/peerjs/peerjs/id?ts=14993271469660.591159722513086 net::ERR_CONNECTION_REFUSED
I have created a simple video chat app using javascript's webRTC library peerjs.
And now I am trying to deploy the site on zeit.co. But I get the error when a peerjs instance gets created
Below is the code where I have mentioned ports and host to run the server

Server side code

```<code>const express = require('express')
const app = express()
const path = require('path')
const server = require('http').createServer(app)
const io = require('socket.io').listen(server)

const srv = server.listen(3000)

app.use('/peerjs', require('peer').ExpressPeerServer(srv, {
    debug: true
}))

const users = []
const connections = []

server.listen(3000, () => {
  console.log('server running')
})

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

app.get('/', (req, res) => {

})
</code>```

Client side code

```<code>const peerObj = {
  host: '127.0.0.1',
  path: '/peerjs',
  debug: 3,
  config: {icerServers: [
    { url: 'stun:stun1.l.google.com:19302' },
    { url: 'turn:numb.viagenie.ca',
      credential: 'muazkh',
      username: 'webrtc@live.com' }
  ]}
}

peer = new Peer(peerObj)
</code>```

List item

答:
I have found a solution for my question. Actually peer server runs on http, and for making it run on https, we have to generate a ssl key and certificate. Even after generating the keys and certificates it will only run on local host and the systems connected to that network.

There is a peer server hosted on heroku, so it is running on https, rather than running your own peer server, we can mention the path of the heroku peer server and then host the app on some hosting website, The app will run properly. Below is my new client side code

```<code>peer = new Peer({host:'peerjs-server.herokuapp.com', secure:true, port:443})
</code>```

and this will run the app properly.

Body:
I have created a simple video chat app using javascript's webRTC library peerjs.
And now I am trying to deploy the site on zeit.co. But I get the error when a peerjs instance gets created
Below is the code where I have mentioned ports and host to run the server

Server side code

const express = require('express')
const app = express()
const path = require('path')
const server = require('http').createServer(app)
const io = require('socket.io').listen(server)

const srv = server.listen(3000)

app.use('/peerjs', require('peer').ExpressPeerServer(srv, {
    debug: true
}))

const users = []
const connections = []

server.listen(3000, () => {
  console.log('server running')
})

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

app.get('/', (req, res) => {

})

Client side code

const peerObj = {
  host: '127.0.0.1',
  path: '/peerjs',
  debug: 3,
  config: {icerServers: [
    { url: 'stun:stun1.l.google.com:19302' },
    { url: 'turn:numb.viagenie.ca',
      credential: 'muazkh',
      username: 'webrtc@live.com' }
  ]}
}

peer = new Peer(peerObj)

List item

Body:
I have found a solution for my question. Actually peer server runs on http, and for making it run on https, we have to generate a ssl key and certificate. Even after generating the keys and certificates it will only run on local host and the systems connected to that network.

There is a peer server hosted on heroku, so it is running on https, rather than running your own peer server, we can mention the path of the heroku peer server and then host the app on some hosting website, The app will run properly. Below is my new client side code

peer = new Peer({host:'peerjs-server.herokuapp.com', secure:true, port:443})

and this will run the app properly.


来源: stackexchange

问:
Android Throwing OutOfMemoryError "Failed to allocate a 164 byte allocation with 44 free bytes and 44B until OOM" (recursive case)
This app worked yesterday, but when starting to work this morning, I get the following error

```<code>Throwing OutOfMemoryError "Failed to allocate a 164 byte allocation with 44 free bytes and 44B until OOM" (recursive case)
</code>```

I have no idea what's going on, or why it's out of memory. Is this just the emulator not working perfectly? Or does this have something to do with my app?

I don't know how much information you need. If you need further information, please tell me so and I will provide.

UPDATE:

I guess this has something to do with the garbage collector? Refer below

```<code>Background sticky concurrent mark sweep GC freed 2839(223KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 1603KB/1603KB, paused 31.379ms total 44.794ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 529(29KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 1574KB/2MB, paused 52.919ms total 60.062ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 5551(277KB) AllocSpace objects, 0(0B) LOS objects, 40% free, 4MB/7MB, paused 15.550ms total 85.518ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 20777(1035KB) AllocSpace objects, 0(0B) LOS objects, 36% free, 7MB/11MB, paused 12.467ms total 61.496ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 46653(2MB) AllocSpace objects, 0(0B) LOS objects, 24% free, 12MB/16MB, paused 1.335ms total 138.439ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 27622(1368KB) AllocSpace objects, 0(0B) LOS objects, 20% free, 15MB/19MB, paused 1.459ms total 182.567ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 45635(2MB) AllocSpace objects, 0(0B) LOS objects, 18% free, 17MB/21MB, paused 1.365ms total 157.690ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 22802(1159KB) AllocSpace objects, 0(0B) LOS objects, 16% free, 20MB/24MB, paused 1.211ms total 180.755ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 14475(641KB) AllocSpace objects, 0(0B) LOS objects, 2% free, 23MB/24MB, paused 1.106ms total 122.625ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 27477(1338KB) AllocSpace objects, 0(0B) LOS objects, 14% free, 23MB/27MB, paused 1.511ms total 147.653ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 37938(1865KB) AllocSpace objects, 0(0B) LOS objects, 13% free, 25MB/29MB, paused 1.253ms total 178.420ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 23214(1147KB) AllocSpace objects, 0(0B) LOS objects, 12% free, 28MB/32MB, paused 3.789ms total 190.825ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 36253(1773KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 31MB/35MB, paused 1.085ms total 227.583ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 13949(616KB) AllocSpace objects, 0(0B) LOS objects, 2% free, 34MB/35MB, paused 665us total 175.362ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 40440(2000KB) AllocSpace objects, 0(0B) LOS objects, 10% free, 33MB/37MB, paused 2.158ms total 311.515ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 13956(617KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 36MB/37MB, paused 42.198ms total 81.851ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 33376(1624KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 36MB/40MB, paused 1.211ms total 322.374ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 4052(174KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 40MB/40MB, paused 1.245ms total 105.928ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 38452(1891KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 39MB/43MB, paused 1.212ms total 282.053ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 15083(667KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 42MB/43MB, paused 1.006ms total 134.368ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 33122(1609KB) AllocSpace objects, 0(0B) LOS objects, 8% free, 42MB/46MB, paused 1.759ms total 685.984ms
2431-2443/com.example.christian.welldanaapp W/art﹕ Suspending all threads took: 21.776ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 2898(122KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 46MB/46MB, paused 23.019ms total 71.640ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 29828(1485KB) AllocSpace objects, 0(0B) LOS objects, 8% free, 45MB/49MB, paused 1.250ms total 194.222ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 37388(1848KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 48MB/52MB, paused 1.243ms total 332.837ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 31151(1528KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 51MB/55MB, paused 1.446ms total 336.916ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 12755(563KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 54MB/55MB, paused 14.512ms total 48.881ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 40981(2014KB) AllocSpace objects, 0(0B) LOS objects, 6% free, 53MB/57MB, paused 1.288ms total 402.576ms
2431-2443/com.example.christian.welldanaapp W/art﹕ Suspending all threads took: 18.769ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 32370(1572KB) AllocSpace objects, 0(0B) LOS objects, 6% free, 56MB/60MB, paused 20.234ms total 387.007ms
2431-2443/com.example.christian.welldanaapp W/art﹕ Suspending all threads took: 10.568ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 12559(558KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 59MB/60MB, paused 11.757ms total 42.520ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Clamp target GC heap from 64MB to 64MB
</code>```

Actual red text:

```<code>07-22 06:39:06.976    2431-2431/com.example.christian.welldanaapp E/AndroidRuntime﹕ Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 458 byte allocation with 1613776 free bytes and 1575KB until OOM; failed due to fragmentation (required continguous free 32768 bytes for a new buffer where largest contiguous free 4096 bytes)
        at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
        at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:146)
        at java.lang.StringBuilder.append(StringBuilder.java:216)
        at java.lang.Throwable.toString(Throwable.java:360)
        at java.lang.Throwable.printStackTrace(Throwable.java:315)
        at java.lang.Throwable.printStackTrace(Throwable.java:300)
        at android.util.Log.getStackTraceString(Log.java:335)
        at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:59)
        at com.android.internal.os.RuntimeInit.access$200(RuntimeInit.java:43)
        at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:85)
        at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
        at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
</code>```

EDIT: JAVA CODE

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ChangeLanguage("dk");
    SetListeners();
}

//Changes the language depending on the button pressed
private void ChangeLanguage(String language){
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getResources().updateConfiguration(config,getResources().getDisplayMetrics());
    setContentView(R.layout.activity_main);
    RestartActivity();
}

//Restarts the activity after changing the languagse
private void RestartActivity(){
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}
</code>```

答:
Try this may help you add this tag in your manifest file.

```<code><application android:largeHeap="true">
</application>
</code>```

it will allocate large heap for your app. Best of luck :)

ContentLicense: CC BY-SA 3.0

Body:
This app worked yesterday, but when starting to work this morning, I get the following error

Throwing OutOfMemoryError "Failed to allocate a 164 byte allocation with 44 free bytes and 44B until OOM" (recursive case)

I have no idea what's going on, or why it's out of memory. Is this just the emulator not working perfectly? Or does this have something to do with my app?

I don't know how much information you need. If you need further information, please tell me so and I will provide.

UPDATE:

I guess this has something to do with the garbage collector? Refer below

Background sticky concurrent mark sweep GC freed 2839(223KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 1603KB/1603KB, paused 31.379ms total 44.794ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 529(29KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 1574KB/2MB, paused 52.919ms total 60.062ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 5551(277KB) AllocSpace objects, 0(0B) LOS objects, 40% free, 4MB/7MB, paused 15.550ms total 85.518ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 20777(1035KB) AllocSpace objects, 0(0B) LOS objects, 36% free, 7MB/11MB, paused 12.467ms total 61.496ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 46653(2MB) AllocSpace objects, 0(0B) LOS objects, 24% free, 12MB/16MB, paused 1.335ms total 138.439ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 27622(1368KB) AllocSpace objects, 0(0B) LOS objects, 20% free, 15MB/19MB, paused 1.459ms total 182.567ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 45635(2MB) AllocSpace objects, 0(0B) LOS objects, 18% free, 17MB/21MB, paused 1.365ms total 157.690ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 22802(1159KB) AllocSpace objects, 0(0B) LOS objects, 16% free, 20MB/24MB, paused 1.211ms total 180.755ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 14475(641KB) AllocSpace objects, 0(0B) LOS objects, 2% free, 23MB/24MB, paused 1.106ms total 122.625ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 27477(1338KB) AllocSpace objects, 0(0B) LOS objects, 14% free, 23MB/27MB, paused 1.511ms total 147.653ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 37938(1865KB) AllocSpace objects, 0(0B) LOS objects, 13% free, 25MB/29MB, paused 1.253ms total 178.420ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 23214(1147KB) AllocSpace objects, 0(0B) LOS objects, 12% free, 28MB/32MB, paused 3.789ms total 190.825ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 36253(1773KB) AllocSpace objects, 0(0B) LOS objects, 11% free, 31MB/35MB, paused 1.085ms total 227.583ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 13949(616KB) AllocSpace objects, 0(0B) LOS objects, 2% free, 34MB/35MB, paused 665us total 175.362ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 40440(2000KB) AllocSpace objects, 0(0B) LOS objects, 10% free, 33MB/37MB, paused 2.158ms total 311.515ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 13956(617KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 36MB/37MB, paused 42.198ms total 81.851ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 33376(1624KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 36MB/40MB, paused 1.211ms total 322.374ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 4052(174KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 40MB/40MB, paused 1.245ms total 105.928ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 38452(1891KB) AllocSpace objects, 0(0B) LOS objects, 9% free, 39MB/43MB, paused 1.212ms total 282.053ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 15083(667KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 42MB/43MB, paused 1.006ms total 134.368ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 33122(1609KB) AllocSpace objects, 0(0B) LOS objects, 8% free, 42MB/46MB, paused 1.759ms total 685.984ms
2431-2443/com.example.christian.welldanaapp W/art﹕ Suspending all threads took: 21.776ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 2898(122KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 46MB/46MB, paused 23.019ms total 71.640ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 29828(1485KB) AllocSpace objects, 0(0B) LOS objects, 8% free, 45MB/49MB, paused 1.250ms total 194.222ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 37388(1848KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 48MB/52MB, paused 1.243ms total 332.837ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 31151(1528KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 51MB/55MB, paused 1.446ms total 336.916ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 12755(563KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 54MB/55MB, paused 14.512ms total 48.881ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 40981(2014KB) AllocSpace objects, 0(0B) LOS objects, 6% free, 53MB/57MB, paused 1.288ms total 402.576ms
2431-2443/com.example.christian.welldanaapp W/art﹕ Suspending all threads took: 18.769ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background partial concurrent mark sweep GC freed 32370(1572KB) AllocSpace objects, 0(0B) LOS objects, 6% free, 56MB/60MB, paused 20.234ms total 387.007ms
2431-2443/com.example.christian.welldanaapp W/art﹕ Suspending all threads took: 10.568ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Background sticky concurrent mark sweep GC freed 12559(558KB) AllocSpace objects, 0(0B) LOS objects, 1% free, 59MB/60MB, paused 11.757ms total 42.520ms
2431-2443/com.example.christian.welldanaapp I/art﹕ Clamp target GC heap from 64MB to 64MB

Actual red text:

07-22 06:39:06.976    2431-2431/com.example.christian.welldanaapp E/AndroidRuntime﹕ Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 458 byte allocation with 1613776 free bytes and 1575KB until OOM; failed due to fragmentation (required continguous free 32768 bytes for a new buffer where largest contiguous free 4096 bytes)
        at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
        at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:146)
        at java.lang.StringBuilder.append(StringBuilder.java:216)
        at java.lang.Throwable.toString(Throwable.java:360)
        at java.lang.Throwable.printStackTrace(Throwable.java:315)
        at java.lang.Throwable.printStackTrace(Throwable.java:300)
        at android.util.Log.getStackTraceString(Log.java:335)
        at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:59)
        at com.android.internal.os.RuntimeInit.access$200(RuntimeInit.java:43)
        at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:85)
        at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
        at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)

EDIT: JAVA CODE

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ChangeLanguage("dk");
    SetListeners();
}

//Changes the language depending on the button pressed
private void ChangeLanguage(String language){
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    getResources().updateConfiguration(config,getResources().getDisplayMetrics());
    setContentView(R.layout.activity_main);
    RestartActivity();
}

//Restarts the activity after changing the languagse
private void RestartActivity(){
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Body:
Try this may help you add this tag in your manifest file.

<application android:largeHeap="true">
</application>

it will allocate large heap for your app. Best of luck :)


问:
When should we use core in CodeIgniter?
I have one question, if I use core, I just write some functions to my MY_Model to reuse that functions when I need. Is it the only thing MY_Model can do? Anything else?</p>

答:
You can use Core to hack with pre-built functionalities.
Like you want to tweak the default garbage collector of sessions.
Basically, the core contains the code which makes CodeIgniter to work and contain default-features provided in CodeIgniter.

Model is what you are you are adding for your application. The Model for your app.

Refer MVC concept

Title: When should we use core in CodeIgniter?


问:
Postgresql UUID supported by Hibernate?
I can't get Hibernate working with java.util.UUID for PostgreSQL.

Here is the mapping using javax.persistence.* annotations:

```<code>private UUID itemUuid;

@Column(name="item_uuid",columnDefinition="uuid NOT NULL")
public UUID getItemUuid() {
    return itemUuid;
}

public void setItemUuid(UUID itemUuid) {
    this.itemUuid = itemUuid;
}
</code>```

When persisting a transient object I get a SQLGrammarException:

```<code>column "item_uuid" is of type uuid but expression is of type bytea at character 149
</code>```

PostgreSQL version is 8.4.4

JDBC driver - 8.4.4-702 (also tried 9.0 - same thing)

Hibernate version is 3.6, main configuration properties:

```<code><property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://192.168.1.1/db_test</property>
</code>```

答:
You try to persist object of type UUID, which is not hibernate-annotated entity. So the hibernate wants to serialize it to byte array (blob type). This is why you get this message 'expression of type bytea'.

You can either store UUID as blobs in database (not elegant), or provide your custom serializer (much work) or manually convert that object. UUID class has methods fromString and toString, so I would store it as String.

Title: Postgresql UUID supported by Hibernate?

Body:
I can't get Hibernate working with java.util.UUID for PostgreSQL.

Here is the mapping using javax.persistence.* annotations:

private UUID itemUuid;

@Column(name="item_uuid",columnDefinition="uuid NOT NULL")
public UUID getItemUuid() {
    return itemUuid;
}

public void setItemUuid(UUID itemUuid) {
    this.itemUuid = itemUuid;
}

When persisting a transient object I get a SQLGrammarException:

column "item_uuid" is of type uuid but expression is of type bytea at character 149

PostgreSQL version is 8.4.4

JDBC driver - 8.4.4-702 (also tried 9.0 - same thing)

Hibernate version is 3.6, main configuration properties:

<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://192.168.1.1/db_test</property>

ContentLicense: CC BY-SA 2.5


问:
Can't set headers after they are sent. Express JS
Help me :(, i cannot find solution for my error, i try using return before my response it dosen't work

this my code

```<code>function isAuthenticated(req, res, next) {
var getToken = req.cookies.token;
var getUrl = req.originalUrl;
console.log(getToken)
if(getToken == undefined) {
    res.redirect('/login')
    next()
} else {
    console.log('success')
    next()
}
next() }

router.get('/login', isAuthenticated, auth.login);
router.get('/logout', isAuthenticated, auth.logout);
router.post('/logging', auth.prosesLogin);
</code>```

答:
It seems that in your functions, the order of function arguments is wrong.

Instead of (err, res) make (req, res) or (err, req, res, next). Hope this helps.

Body:
Help me :(, i cannot find solution for my error, i try using return before my response it dosen't work

this my code

function isAuthenticated(req, res, next) {
var getToken = req.cookies.token;
var getUrl = req.originalUrl;
console.log(getToken)
if(getToken == undefined) {
    res.redirect('/login')
    next()
} else {
    console.log('success')
    next()
}
next() }

router.get('/login', isAuthenticated, auth.login);
router.get('/logout', isAuthenticated, auth.logout);
router.post('/logging', auth.prosesLogin);


问:
Rails : How to create an object of class within a controller which is in another namespace?
I'm using CarrierWave to upload files from the AngularJS client. The uploader generated for the carrierWave is in another namespace while the controller is in another namespace.

So when I'm trying to create an object of uploader inside the controller, I am getting the following error :

```<code>uninitialized constant Api::V1::ProductsController::FileUploader
</code>```

Here is my directory structure :

```<code>app
|--controllers
   |--api
      |--controllers
         |--api
            |--v1
               |--products_controller.rb
|--uploaders
   |--file_uploader.rb
</code>```

The Products Controller

```<code>  class Api::V1::ProductsController < ApplicationController
    respond_to :json

  ......

  def createFromExcel
    puts "------------------------------------"
    puts params[:file]
    puts "------------------------------------"
    uploader = FileUploader.new
    uploader.store!(params[:file])
  end

end
</code>```

The FileUploader class :

```<code>class FileUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process resize_to_fit: [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
   def extension_whitelist
     %w(xlsx xls)
   end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end
</code>```

How can I create an object of FileUploader class within my Controller?

答: try using uploader = ::FileUploader.new

Body:
I'm using CarrierWave to upload files from the AngularJS client. The uploader generated for the carrierWave is in another namespace while the controller is in another namespace.

So when I'm trying to create an object of uploader inside the controller, I am getting the following error :

uninitialized constant Api::V1::ProductsController::FileUploader

Here is my directory structure :

app
|--controllers
   |--api
      |--controllers
         |--api
            |--v1
               |--products_controller.rb
|--uploaders
   |--file_uploader.rb

The Products Controller

  class Api::V1::ProductsController < ApplicationController
    respond_to :json

  ......

  def createFromExcel
    puts "------------------------------------"
    puts params[:file]
    puts "------------------------------------"
    uploader = FileUploader.new
    uploader.store!(params[:file])
  end

end

The FileUploader class :

class FileUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  # include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url(*args)
  #   # For Rails 3.1+ asset pipeline compatibility:
  #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  #
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process scale: [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process resize_to_fit: [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
   def extension_whitelist
     %w(xlsx xls)
   end

  # Override the filename of the uploaded files:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.
  # def filename
  #   "something.jpg" if original_filename
  # end

end

How can I create an object of FileUploader class within my Controller?

Body: try using uploader = ::FileUploader.new


问:
How to remove straight lines from a Matlab image?
I have a matlab image from a matrix named Two_dim as shown in the figure below.

I would like to remove all 3 of the bottom straight horizontal lines from the image. I looked up on Stackoverflow to use regionprops to eliminate horizontal lines and obtained this code. But that doesn't seem to remove the lines.

```<code>rp = regionprops(Two_dim, 'PixelIdxList', 'Eccentricity', 'Orientation');
rp = rp([rp.Eccentricity]>0.95 & (abs([rp.Orientation])<2 | abs([rp.Orientation])>89));
Two_dim(vertcat(rp.PixelIdxList)) = false;
</code>```

答:
regionprops needs a binary image with each pixel being one of two values.

You can do e.g.

```<code>Two_dim(Two_dim<0.5) = 0;
Two_dim(Two_dim>=0.5) = 1; # the actual value doesn't matter
</code>```

or

```<code>Two_dim = logical(Two_dim);
</code>```

Body:
I have a matlab image from a matrix named Two_dim as shown in the figure below.

I would like to remove all 3 of the bottom straight horizontal lines from the image. I looked up on Stackoverflow to use regionprops to eliminate horizontal lines and obtained this code. But that doesn't seem to remove the lines.

rp = regionprops(Two_dim, 'PixelIdxList', 'Eccentricity', 'Orientation');
rp = rp([rp.Eccentricity]>0.95 & (abs([rp.Orientation])<2 | abs([rp.Orientation])>89));
Two_dim(vertcat(rp.PixelIdxList)) = false;

Body:
regionprops needs a binary image with each pixel being one of two values.

You can do e.g.

Two_dim(Two_dim<0.5) = 0;
Two_dim(Two_dim>=0.5) = 1; # the actual value doesn't matter

or

Two_dim = logical(Two_dim);


问:
JavaScript: Passing parameters to a callback function
I'm trying to pass some parameter to a function used as callback, how can I do that?

This is my try:

function tryMe(param1, param2) {
  alert(param1 + " and " + param2);
}

function callbackTester(callback, param1, param2) {
  callback(param1, param2);
}

callbackTester(tryMe, "hello", "goodbye");```

答:
Use curried function as in this simple example.

const BTN = document.querySelector('button')
const RES = document.querySelector('p')

const changeText = newText => () => {
  RES.textContent = newText
}

BTN.addEventListener('click', changeText('Clicked!'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>ClickMe</button>
<p>Not clicked<p></code>```

ContentLicense: CC BY-SA 4.0

Body:
Use curried function as in this simple example.

const BTN = document.querySelector('button')
const RES = document.querySelector('p')

const changeText = newText => () => {
  RES.textContent = newText
}

BTN.addEventListener('click', changeText('Clicked!'))

<button>ClickMe</button>
<p>Not clicked<p>


问:
Web scraping - Python script return [] / None
I am trying to get the simple python code to return mobile name mentioned in the site. but it did not work. please suggest me if in good direction.

```<code>import requests
from bs4
import BeautifulSoup

url = 'https://www.flipkart.com/offers-list/new-launches?screen=dynamic&pk=themeViews%3DNewLaunches%3ADesktopView~widgetType%3DdealCard~contentType%3Dneo&wid=5.dealCard.OMU&otracker=clp_omu_New+Launches_mobiles_4'

r = requests.get(url)
soup = BeautifulSoup(r.content)

mobileN = soup.find_all("div", {
  "class",
  "iUmrbN"
})

for mo in mobileN:
  print mo.text.strip()
</code>```

Error/warning is like

```<code>*** Remote Interpreter Reinitialized  ***
>>>
C:\Python27\ArcGIS10.3\lib\site-packages\urllib3\util\ssl_.py:335: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  SNIMissingWarning
C:\Python27\ArcGIS10.3\lib\site-packages\urllib3\util\ssl_.py:133: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecurePlatformWarning
C:\Python27\ArcGIS10.3\lib\site-packages\bs4\__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 63 of the file C:\Users\DELL\AppData\Roaming\PyScripter\remserver.py. To get rid of this warning, change code that looks like this:

 BeautifulSoup(YOUR_MARKUP})

to this:

 BeautifulSoup(YOUR_MARKUP, "lxml")

  markup_type=markup_type))
>>>
</code>```

答:
Try this code</p>

```<code>import urllib
import bs4

req = urllib.request.Request('https://www.flipkart.com/offers-list/new-launches?screen=dynamic&pk=themeViews%3DNewLaunches%3ADesktopView~widgetType%3DdealCard~contentType%3Dneo&wid=5.dealCard.OMU&otracker=clp_omu_New+Launches_mobiles_4')
content = urllib.request.urlopen(req).read()
soup = bs4.BeautifulSoup(content, "html.parser")

for link in soup.findAll("a"):
    print(link.get("href"))
</code>```

Body:
I am trying to get the simple python code to return mobile name mentioned in the site. but it did not work. please suggest me if in good direction.

import requests
from bs4
import BeautifulSoup

url = 'https://www.flipkart.com/offers-list/new-launches?screen=dynamic&pk=themeViews%3DNewLaunches%3ADesktopView~widgetType%3DdealCard~contentType%3Dneo&wid=5.dealCard.OMU&otracker=clp_omu_New+Launches_mobiles_4'

r = requests.get(url)
soup = BeautifulSoup(r.content)

mobileN = soup.find_all("div", {
  "class",
  "iUmrbN"
})

for mo in mobileN:
  print mo.text.strip()

Error/warning is like

*** Remote Interpreter Reinitialized  ***
>>>
C:\Python27\ArcGIS10.3\lib\site-packages\urllib3\util\ssl_.py:335: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  SNIMissingWarning
C:\Python27\ArcGIS10.3\lib\site-packages\urllib3\util\ssl_.py:133: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecurePlatformWarning
C:\Python27\ArcGIS10.3\lib\site-packages\bs4\__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 63 of the file C:\Users\DELL\AppData\Roaming\PyScripter\remserver.py. To get rid of this warning, change code that looks like this:

 BeautifulSoup(YOUR_MARKUP})

to this:

 BeautifulSoup(YOUR_MARKUP, "lxml")

  markup_type=markup_type))
>>>

Body:
Try this code

import urllib
import bs4

req = urllib.request.Request('https://www.flipkart.com/offers-list/new-launches?screen=dynamic&pk=themeViews%3DNewLaunches%3ADesktopView~widgetType%3DdealCard~contentType%3Dneo&wid=5.dealCard.OMU&otracker=clp_omu_New+Launches_mobiles_4')
content = urllib.request.urlopen(req).read()
soup = bs4.BeautifulSoup(content, "html.parser")

for link in soup.findAll("a"):
    print(link.get("href"))


问:
OpenCV - background removal and object detection
I need to detect where objects (mostly people) are in relation to a wall. I can have a fixed position camera in the ceiling so I thought to get an image of the space with nothing in it. Then use the difference of that and the current camera image to get an image with just the things. Then I can do blob detection I think to get the positions (only need x).
Does this seem sound? I'm not very accomplished in OpenCV so am looking for some advice.</p>

答:
That would be one way of going about it, but not very robust as the video feed won't produce consistent precise images so the background will never be nicely subtracted out, and people walking through the scene will occlude light and could also possibly match parts of your background.

This process of removing the background from a video is simply dubbed "background subtraction" and there are built-in OpenCV methods for it.

OpenCV has tutorials on their site showing the basics, for both python and C++.


问:
awk: $2 == /"foo"/ { ... } does not work as expected (matching $2 exactly to foo, quoted)
With this file example :

```<code>"line1_value1","foo","line1_value3"
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
"line4_value1","foo","line4_value3"
"line3_value1","faa ","line3_value3"
</code>```

I want get all lines with the second column exactly equal to "faa" in the second column. With my example, this match with the lines 2 and 3. I tried that :

```<code>awk -F, '$2 == /"foo"/ { print $0 }' example_file
</code>```

But this command returns nothing...Where am I wrong?

答:
Do equality test on the , separated second field:

```<code>awk -F, '$2 == "\"faa\""' file.txt
</code>```

Also here, you need to escape the inner "s to make it literal inside "s.

Example:

```<code>% cat file.txt
"line1_value1","foo","line1_value3"
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
"line4_value1","foo","line4_value3"
"line3_value1","faa ","line3_value3"

% awk -F, '$2 == "\"faa\""' file.txt
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
</code>```

Reason your one failed:

You have used:

```<code>awk -F, '$2 == /"foo"/ { print $0 }'
</code>```

// incurs Regex match in awk, and returns 0 (no match) or 1 (match)

$2 == /"foo"/ is necessarily comparing (for equality) the second field with the integer 0 or 1, which will always be evaluated to false in this case. Also, /"foo"/ here is matching the pattern "foo" against the whole record

So, remember that, /<pattern>/ is shorthand for $0 ~ /<pattern>/ hence your $2 == /"foo"/ is a shorthand for $2 == ($0 ~ /"foo"/)

Body:
With this file example :

"line1_value1","foo","line1_value3"
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
"line4_value1","foo","line4_value3"
"line3_value1","faa ","line3_value3"

I want get all lines with the second column exactly equal to "faa" in the second column. With my example, this match with the lines 2 and 3. I tried that :

awk -F, '$2 == /"foo"/ { print $0 }' example_file

But this command returns nothing...Where am I wrong?

Body:
Do equality test on the , separated second field:

awk -F, '$2 == "\"faa\""' file.txt

Also here, you need to escape the inner "s to make it literal inside "s.

Example:

% cat file.txt
"line1_value1","foo","line1_value3"
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"
"line4_value1","foo","line4_value3"
"line3_value1","faa ","line3_value3"

% awk -F, '$2 == "\"faa\""' file.txt
"line2_value1","faa","line2_value3"
"line3_value1","faa","line3_value3"

Reason your one failed:

You have used:

awk -F, '$2 == /"foo"/ { print $0 }'

// incurs Regex match in awk, and returns 0 (no match) or 1 (match)

$2 == /"foo"/ is necessarily comparing (for equality) the second field with the integer 0 or 1, which will always be evaluated to false in this case. Also, /"foo"/ here is matching the pattern "foo" against the whole record

So, remember that, /<pattern>/ is shorthand for $0 ~ /<pattern>/ hence your $2 == /"foo"/ is a shorthand for $2 == ($0 ~ /"foo"/)


问:
Inserting a node at nth position
```<code>node* insertnth(struct node_q* list,int ndex,struct node_q* qtemp){//temp is the node to be inserted at the back of ndex
    struct node_q* temp;
    struct node_q* curr;
    int i;
    temp = list;
    curr = temp;
    for(i=0;i<=ndex;i++){
        if(temp!=NULL)
        temp = temp->pnext;
    }
        curr = temp;
        temp = temp->pnext;
        curr->pnext = NULL;
        curr->pnext = qtemp;
        qtemp->pnext = temp;

        return list;
}
</code>```

I dont have an idea why it crashes. this function should insert the node temp at the back of the index or after the index and reconnects it to the list all the pointer of the struct are set to null before passing as parameter  except for the list it has already nodes.

答:
```<code>public void InsertAtNth(int data, int position){
            NodeS newNode = new NodeS(data);
            NodeS temp = head1;
            NodeS prev = null;
            if(head1 == null ){
                head1 = newNode;
            }
            else if(position == 0){
                  newNode.next = head1;
                  head1 = newNode;
              }

            else{
                for(int i = 0;i < position; i++){
                    prev = temp;
                    temp = temp.next;
                }
                prev.next = newNode;
                newNode.next = temp;

            }
        }
</code>```

Title: Inserting a node at nth position

Body:
node* insertnth(struct node_q* list,int ndex,struct node_q* qtemp){//temp is the node to be inserted at the back of ndex
    struct node_q* temp;
    struct node_q* curr;
    int i;
    temp = list;
    curr = temp;
    for(i=0;i<=ndex;i++){
        if(temp!=NULL)
        temp = temp->pnext;
    }
        curr = temp;
        temp = temp->pnext;
        curr->pnext = NULL;
        curr->pnext = qtemp;
        qtemp->pnext = temp;

        return list;
}

I dont have an idea why it crashes. this function should insert the node temp at the back of the index or after the index and reconnects it to the list all the pointer of the struct are set to null before passing as parameter  except for the list it has already nodes.


问:
Table filtering with pipes using ngfor and web api data
I am trying to make a filter for my table so that when I search by a parameter it only shows the row containing the parameter. Here's a working example of what I'm trying to achieve - plunkr.

I used the code from that plunkr and this website as reference and tried implementing it in my solution. I get the table data from web api.

I'm trying to filter by "codeListVesselID".
Here is the code:

vesel.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';
import { CodeListVessel } from './vessels.component';

@Pipe({
    name: 'vesselfilter',
    pure: false
})
@Injectable()
export class VesselIDFilter implements PipeTransform {
  transform(vessel: CodeListVessel[], args: any[]): any {
    return vessel.filter(CodeListVessel => CodeListVessel.codeListVesselID.toLowerCase().indexOf(args[0].toLowerCase()) !== -1);
  }
}```
</div>
</div>
</p>

<p>The pipe is defined in app.module.ts under declarations.</p>

<p><strong>vessels.component.ts</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, Input } from '@angular/core';
...
import { VesselIDFilter } from '../vessels/vessels.pipe';

@Component({
    selector: 'vessels',
    template: require('./vessels.component.html'),
    styleUrls: ['./vessel.component.css']
})

export class vesselsComponent {
    // to get the Vessel Details
    public vessel: CodeListVessel[] = [];
    ...

    constructor(public http: Http, private dialogService: DialogService, private confirmationService: ConfirmationService, private auth: Auth) {
        this.getData();
    }
    //to get all the Vessel data from Web API
    getData() {
        this.http.get('/api/CodeListVesselAPI/Vessel').subscribe(result => {
        this.vessel = result.json();
        });
    }
    ...
}

export interface CodeListVessel {
    codeListVesselID: string;
    mmsi: string;
    imo: number;
    ...
}</code>```

vessels.component.html

<input type="text" id="inputID" class="form-control" placeholder="Code" [(ngModel)]="codeListVesselID">

                    Code
                    MMSI
                    IMO
                    ...

                        {{CodeListVessel.codeListVesselID}}

                        {{CodeListVessel.mmsi}}

                        {{CodeListVessel.imo}}

                    ...

```

Here is the error I get for running the above code:

It points to the code in pipe but I don't know what the problem is.
If I remove the filter code the data shows properly in the table so the data gets through fine.

There may also be an issue in another part.

Any help would be appreciated.

答:
I think codeListVesselID is maybe undefined during page init and thus args is empty and cannot access [0].

Try changing your transform function to this one:

```<code>transform(vessel: CodeListVessel[], args: any[]): any {
    if (args && args.length) {
        return vessel.filter(CodeListVessel => CodeListVessel.codeListVesselID.toLowerCase().indexOf(args[0].toLowerCase()) !== -1);
    }
    else {
        return vessel;
    }

}
</code>```

Body:
I am trying to make a filter for my table so that when I search by a parameter it only shows the row containing the parameter. Here's a working example of what I'm trying to achieve - plunkr.

I used the code from that plunkr and this website as reference and tried implementing it in my solution. I get the table data from web api.

I'm trying to filter by "codeListVesselID".
Here is the code:

vesel.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';
import { CodeListVessel } from './vessels.component';

@Pipe({
    name: 'vesselfilter',
    pure: false
})
@Injectable()
export class VesselIDFilter implements PipeTransform {
  transform(vessel: CodeListVessel[], args: any[]): any {
    return vessel.filter(CodeListVessel => CodeListVessel.codeListVesselID.toLowerCase().indexOf(args[0].toLowerCase()) !== -1);
  }
}

The pipe is defined in app.module.ts under declarations.

vessels.component.ts

import { Component, Input } from '@angular/core';
...
import { VesselIDFilter } from '../vessels/vessels.pipe';

@Component({
    selector: 'vessels',
    template: require('./vessels.component.html'),
    styleUrls: ['./vessel.component.css']
})

export class vesselsComponent {
    // to get the Vessel Details
    public vessel: CodeListVessel[] = [];
    ...

    constructor(public http: Http, private dialogService: DialogService, private confirmationService: ConfirmationService, private auth: Auth) {
        this.getData();
    }
    //to get all the Vessel data from Web API
    getData() {
        this.http.get('/api/CodeListVesselAPI/Vessel').subscribe(result => {
        this.vessel = result.json();
        });
    }
    ...
}

export interface CodeListVessel {
    codeListVesselID: string;
    mmsi: string;
    imo: number;
    ...
}

vessels.component.html

<input type="text" id="inputID" class="form-control" placeholder="Code" [(ngModel)]="codeListVesselID">

                    Code
                    MMSI
                    IMO
                    ...

                        {{CodeListVessel.codeListVesselID}}

                        {{CodeListVessel.mmsi}}

                        {{CodeListVessel.imo}}

                    ...

Here is the error I get for running the above code:

It points to the code in pipe but I don't know what the problem is.
If I remove the filter code the data shows properly in the table so the data gets through fine.

There may also be an issue in another part.

Any help would be appreciated.

Body:
I think codeListVesselID is maybe undefined during page init and thus args is empty and cannot access [0].

Try changing your transform function to this one:

transform(vessel: CodeListVessel[], args: any[]): any {
    if (args && args.length) {
        return vessel.filter(CodeListVessel => CodeListVessel.codeListVesselID.toLowerCase().indexOf(args[0].toLowerCase()) !== -1);
    }
    else {
        return vessel;
    }

}


问:
Symfony 2. Migration project to php 7 from php5.5. Performance issues
I have one project ~4y old, I started with 5.3 and Symfony 2.0, migrated to 5.5 and S2.3. At the moment I migrated to S2.8 and I want to migrate to php 7.

As there was so much heap around PHP 7 performance I was eager to test my project performance in dev env.

So running benchmark in dev env; service is on vagrant host having both php5-fpm and php7.0-fpm, shutting one down and setting another up.

I would expect that php7 would outperform php5, but basically it seems that php7 is 1.5-2 times slower on my local dev env.

What am I doing wrong? Or should I rewrite my app somehow?

phpinfo:
php 7 http://pastebin.com/a6a76vE2
php 5 http://pastebin.com/4GBXNmBB

P.S. Yes, I understand that running benchmarks in local dev env is not 100% valid and pure, but I need only to understand if php7 faster than php5, as it said.

U1

Funniest thing is that blackfire shows clearly that php 7 is ~45% faster than php 5. But when I am sieging, than I see that performance degrades.

U2

Here is more or less my custom configuration for dev env. It is the same for php5.5 and php7:

```<code>[Date]
date.timezone = Europe/Tallinn

[PHP]
memory_limit = 512M
expose_php = Off
cgi.fix_pathinfo = 0
post_max_size = 10M
upload_max_filesize = 10M
max_execution_time = 60
realpath_cache_size = 4096k
realpath_cache_ttl = 7200

error_reporting = E_ALL | E_STRICT
log_errors = On
error_log = /var/log/php.errors.log

display_errors = On
display_startup_errors = On
html_errors = On

; xdebug
xdebug.remote_enable = On
xdebug.remote_port = 9001
xdebug.max_nesting_level = 200
xdebug.remote_log = /tmp/xdebug.log
xdebug.remote_connect_back = on
xdebug.idekey = "vagrant"

[opcache]
opcache.enable_cli=0
opcache.save_comments=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=66000
opcache.fast_shutdown=1
opcache.enable=1
opcache.revalidate_freq=5
opcache.validate_timestamps=1
</code>```

答:
The reason of this will surely be the xdebug. Please turn it off and then check the performance.

I have to point out that in our case after switching from PHP5.5/Symfony 2.0 to PHP7/Symfony 3.0 we did encountered a performance drop. This was caused by how Symfony 2.8+ handles the php sessions. It stores them in a local directory instead of standard /tmp directory which almost always stored in RAM. So if you have pretty big count of session files the search of the file from HDD takes a long time compared to RAM.

After removing this in Symfony config, the application started showing the performance gains we hoped for.

Body:
I have one project ~4y old, I started with 5.3 and Symfony 2.0, migrated to 5.5 and S2.3. At the moment I migrated to S2.8 and I want to migrate to php 7.

As there was so much heap around PHP 7 performance I was eager to test my project performance in dev env.

So running benchmark in dev env; service is on vagrant host having both php5-fpm and php7.0-fpm, shutting one down and setting another up.

I would expect that php7 would outperform php5, but basically it seems that php7 is 1.5-2 times slower on my local dev env.

What am I doing wrong? Or should I rewrite my app somehow?

phpinfo:
php 7 http://pastebin.com/a6a76vE2
php 5 http://pastebin.com/4GBXNmBB

P.S. Yes, I understand that running benchmarks in local dev env is not 100% valid and pure, but I need only to understand if php7 faster than php5, as it said.

U1

Funniest thing is that blackfire shows clearly that php 7 is ~45% faster than php 5. But when I am sieging, than I see that performance degrades.

U2

Here is more or less my custom configuration for dev env. It is the same for php5.5 and php7:

[Date]
date.timezone = Europe/Tallinn

[PHP]
memory_limit = 512M
expose_php = Off
cgi.fix_pathinfo = 0
post_max_size = 10M
upload_max_filesize = 10M
max_execution_time = 60
realpath_cache_size = 4096k
realpath_cache_ttl = 7200

error_reporting = E_ALL | E_STRICT
log_errors = On
error_log = /var/log/php.errors.log

display_errors = On
display_startup_errors = On
html_errors = On

; xdebug
xdebug.remote_enable = On
xdebug.remote_port = 9001
xdebug.max_nesting_level = 200
xdebug.remote_log = /tmp/xdebug.log
xdebug.remote_connect_back = on
xdebug.idekey = "vagrant"

[opcache]
opcache.enable_cli=0
opcache.save_comments=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=66000
opcache.fast_shutdown=1
opcache.enable=1
opcache.revalidate_freq=5
opcache.validate_timestamps=1


问:
Wordpress get content from another page and append it to active page with jQuery
iam trying to create a infinite scroll in wordpress through appending content (seems the simples)

but the only thing that gets appended is
"http://localhost/wptest/test2/ #content"

I´ve read quite a bit but didnt understand enough to solve the problem sorry :( .

Would someone be so kind to push me in the right direction?

```<code><script>
  jQuery(document).ready(function() {
  alert( "test 1" );
  jQuery("#content").append("http://localhost/wptest/test2/ #content");
  alert( "test 2" );
  });
</script>
</code>```

答:
I got it finally^^,
it is actually quite simple: use the jQuery get function like this (for everyone who is searching):</p>

```<code><script>
jQuery(document).ready(function() {
    jQuery.get("http://localhost/wptest/test2/").success(function(data){
        jQuery(data).find('#content').appendTo('#content');
    });
});
</script>
</code>```

Body:
I got it finally^^,
it is actually quite simple: use the jQuery get function like this (for everyone who is searching):

<script>
jQuery(document).ready(function() {
    jQuery.get("http://localhost/wptest/test2/").success(function(data){
        jQuery(data).find('#content').appendTo('#content');
    });
});
</script>


问:
Accessing a JSON variable pre-fixed with a hash (#)
Last.fm seems to put # symbols in front of some of their variable names for it's JSON API. Have a look at a sample response here. As soon as I try and access #text with JavaScript I get an invalid symbol error in the console. Any quick fixes or reasons for this hash?

答:
jQuery is only used to retrieve the data. Accessing the #text data is done through straight JavaScript syntax, something like data.recenttracks.track.artist["#text"]

You can't do artist.#text , because # is an invalid first character symbol to be used for accessing an object member. Use the square brackets instead.


问:
convert simple curl data request to powershell invoke-webrequest
Converting a very simple Plaid API curl data request to a powershell invoke-webrequest

what works:

```<code>    curl -X POST https://tartan.plaid.com/balance \
  -d client_id=client-id-value \
  -d secret=secret-value \
  -d access_token=access-token-value
</code>```

What I'm trying unsuccessfully in Powershell

```<code>#test powershell api call

$hash = @{  client_id    = "client-id-value";
            secret = "secret-value"
            access_token = "access-token-value"
            }

$JSON = $hash | convertto-json

#Invoke-WebRequest -uri "https://tartan.plaid.com/balance" -Method POST -Body $JSON
</code>```

This returns a plaid error 1100 (client id missing), so I know some API functionality is working, but it's not parsing input data correctly.

My biggest misunderstanding is how to translate a "curl -data" value into the proper Powershell parameter.

Is this a header value, body value? etc.

答:
Unless the target url expects the POST body to be in JSON format, skip the ConvertTo-JSON step completely.

When the chosen HTTP method is POST, Invoke-WebRequest will automatically take all the keys in the hashtable supplied to the -Body parameter and construct a body payload similar to that of curl -d:

```<code>$POSTParams = @{
    client_id    = "client-id-value"
    secret       = "secret-value"
    access_token = "access-token-value"
}

Invoke-WebRequest -Uri "https://tartan.plaid.com/balance" -Method POST -Body $POSTParams
</code>```

Body:
Converting a very simple Plaid API curl data request to a powershell invoke-webrequest

what works:

    curl -X POST https://tartan.plaid.com/balance \
  -d client_id=client-id-value \
  -d secret=secret-value \
  -d access_token=access-token-value

What I'm trying unsuccessfully in Powershell

#test powershell api call

$hash = @{  client_id    = "client-id-value";
            secret = "secret-value"
            access_token = "access-token-value"
            }

$JSON = $hash | convertto-json

#Invoke-WebRequest -uri "https://tartan.plaid.com/balance" -Method POST -Body $JSON

This returns a plaid error 1100 (client id missing), so I know some API functionality is working, but it's not parsing input data correctly.

My biggest misunderstanding is how to translate a "curl -data" value into the proper Powershell parameter.

Is this a header value, body value? etc.

Body:
Unless the target url expects the POST body to be in JSON format, skip the ConvertTo-JSON step completely.

When the chosen HTTP method is POST, Invoke-WebRequest will automatically take all the keys in the hashtable supplied to the -Body parameter and construct a body payload similar to that of curl -d:

$POSTParams = @{
    client_id    = "client-id-value"
    secret       = "secret-value"
    access_token = "access-token-value"
}

Invoke-WebRequest -Uri "https://tartan.plaid.com/balance" -Method POST -Body $POSTParams


问:
Not getting values from XML with C#
I have a XML like this.

```<code><language code="eng">
  <label lang="tr">İngilizce</label>
  <label lang="en">English</label>
</language>
</code>```

This is example. I have a 402 nodes.

I'm trying to parse this XML file with C# like on the code and I just can get language code values.

Here is the code.

```<code>var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                          })
                          .ToList();
</code>```

But I need to get label lang="tr" and label lang="en" inner texts (Ingilizce,English) in same code. I didn't do it.

How can I change my code ? Thanks for your helps. :)

EDIT :

```<code> var languageCodeAndValue = doc.Root
                  .Elements("language")
                  .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string>(item.Attribute("lang").Value, item.Value)))
                  .ToList();
</code>```

This code give me a list like this :

```<code>tr,Turkce
en,Turkish
tr,Ingilizce
en,English
</code>```

But I need

```<code>tur,tr,Turkce
tur,en,Turkish
eng,tr,Ingilizce
eng,en,English
</code>```

答:
Try something like this:</p>

```<code>var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                              lables = x.Elements().Select(y => new {
                                   tr = y.Where(z => (string)z.Attribute("lang") == "tr").Select(z => (string)),
                                   en = y.Where(z => (string)z.Attribute("lang") == "en").Select(z => (string))
                               }).ToList()
                          }).ToList();
</code>```

Title: Not getting values from XML with C#

Body:
I have a XML like this.

<language code="eng">
  İngilizce
  English
</language>

This is example. I have a 402 nodes.

I'm trying to parse this XML file with C# like on the code and I just can get language code values.

Here is the code.

var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                          })
                          .ToList();

But I need to get label lang="tr" and label lang="en" inner texts (Ingilizce,English) in same code. I didn't do it.

How can I change my code ? Thanks for your helps. :)

EDIT :

 var languageCodeAndValue = doc.Root
                  .Elements("language")
                  .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string>(item.Attribute("lang").Value, item.Value)))
                  .ToList();

This code give me a list like this :

tr,Turkce
en,Turkish
tr,Ingilizce
en,English

But I need

tur,tr,Turkce
tur,en,Turkish
eng,tr,Ingilizce
eng,en,English

Body:
Try something like this:

var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                              lables = x.Elements().Select(y => new {
                                   tr = y.Where(z => (string)z.Attribute("lang") == "tr").Select(z => (string)),
                                   en = y.Where(z => (string)z.Attribute("lang") == "en").Select(z => (string))
                               }).ToList()
                          }).ToList();


问:
parsing wikipedia page content
I'm looking for a library to parse html pages, specifically wikipedia articles for example: http://en.wikipedia.org/wiki/Railgun, I want to extract the article's text and images (full scale or original image not the thumb).
Is there an html parser out there ?
I would prefer not to use the wikimedia api since I can't seem to figure out how to extract an article's text and the fullsize images with them.
Thanks and sorry for my english.

EDIT: I forgot to say that the ending result should be valid html

EDIT: I got the json string with this: https://en.wikipedia.org/w/api.php?action=parse&pageid=218930&prop=text&format=json so now I need to parse the json.
I know that in javascript I can do something like this:
var pageHTML = JSON.parse("the json string").parse.text["*"];
Since I know a bit of html/javascript and python, how can I make that http request and parse the json in python 3 ?

答:
I made a Node.js module called wikipedia-to-json (written in javascript) that parses the HTML in wikipedia articles and gives you back structed JSON objects that describe the layout of the article in-order. (titles, paragraphs, images, lists, sub-titles...)

That might be useful if you just want to do a quick extractions of text and sections and understand how things look like.

Title: parsing wikipedia page content


问:
Error development is not defined error with react-hot-loader v3 and webpack-hot-middleware
Given that these are the dependencies that I am using:

```<code>"react-hot-loader": "3.0.0-beta.7",
"webpack": "2.6.1",
"webpack-dev-middleware": "^1.11.0",
"webpack-hot-middleware": "^2.18.1",
"webpack-merge": "^4.1.0"
</code>```

Error

```<code>patch.js:5

Uncaught ReferenceError: development is not defined
    at Object.defineProperty.value (patch.js:5)
    at __webpack_require__ (bootstrap 921586e…:659)
    at fn (bootstrap 921586e…:85)
    at Object.options.path (patch.js:1)
    at __webpack_require__ (bootstrap 921586e…:659)
    at fn (bootstrap 921586e…:85)
    at Object.<anonymous> (process-update.js:132)
    at __webpack_require__ (bootstrap 921586e…:659)
    at validateFormat (bootstrap 921586e…:708)
    at bootstrap 921586e…:708
</code>```

You might want to either take a look at this repo

webpack-config

```<code>const FILE_PATHS = {
  entry: path.resolve('./src/index.js'),
  reactHotLoader: 'react-hot-loader/patch',
  hmrEntry: 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', // this is from the webpack-hot-middleware docs
  output: '/' // this is the path used by webpack-dev-middleware, the docs say no real path is required, just pass in `/`
}

const devOnly = {
  entry: FILE_PATHS.entry,
  output: {
    path: '/',
    publicPath: '/assets/',
    filename: 'bundle.js'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ],
        // react-hot-loader asks to include src and exclude node_modules in https://github.com/gaearon/react-hot-loader/blob/master/docs/Troubleshooting.md
        include: path.resolve('./src'),
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        use: [
          {
            loader: 'json-loader'
          }
        ]
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-sprite-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new DefinePlugin({
      'process.env.NODE_ENV': 'development'
    })
  ]
}

const hmr = {
  entry: [FILE_PATHS.reactHotLoader, FILE_PATHS.hmrEntry, FILE_PATHS.entry],
  plugins: [new HmrPlugin(), new NoErrorsPlugin()],
  devServer: {
    hot: true
  }
}

const dev = merge(devOnly, hmr)

module.exports = {dev}
</code>```

Express Server

```<code>// process.env.NODE_ENV = 'development'
const express = require('express')
const webpack = require('webpack')
const historyApiFallback = require('connect-history-api-fallback')

const normalizeAssets = assets => {
  return Array.isArray(assets) ? assets : [assets]
}

const getLinks = assets => {
  const styles = assets.filter(path => path.endsWith('.css'))
  const links = styles.map(path => `<link rel="stylesheet" href="${path}" />`)
  return links.join('\n')
}

const publicPath = '/assets/'

const getScripts = assets => {
  const js = assets.filter(path => path.endsWith('.js'))
  const scripts = js.map(path => `<script src="${path}"></script>`)
  return scripts.join('\n')
}

const devMiddlewareConfig = {
  serverSideRender: true,
  stats: 'normal',
  publicPath: publicPath,
  watchOptions: {
    poll: 1000,
    aggregateTimeout: 300
  }
}

const hotMiddlewareConfig = {
  reload: true,
  overlay: true
}

const devMiddlewareCreator = require('webpack-dev-middleware')
const hotMiddlewareCreator = require('webpack-hot-middleware')

const options = require('./webpack.config')

const {dev: devConfig} = options

const compiler = webpack(devConfig)
const devMiddleware = devMiddlewareCreator(compiler, devMiddlewareConfig)
const hotMiddleware = hotMiddlewareCreator(compiler, hotMiddlewareConfig)

const app = express()
app.use(devMiddleware)
app.use(hotMiddleware)
app.use(express.static(__dirname + '/public'))
app.use((req, res) => {
  const stats = res.locals.webpackStats.toJson()
  const assets = normalizeAssets(stats.assetsByChunkName.main)
  const styles = getLinks(assets)
  const scripts = getScripts(assets)
  res.send(
    `
<!DOCTYPE html>
    <html>
      <head>
        <title>Webpack is crazy</title>
        ${styles}
      </head>
      <body>
      <div id="app">
      </div>
      ${scripts}
      </body>
    </html>
`
  )
})

// app.use(historyApiFallback)

app.listen(3000, err => {
  if (!err) {
    console.log('Server is listening on port 3000')
  }
})
</code>```

答:
The error is caused by this part of your configuration:

```<code>new DefinePlugin({
  'process.env.NODE_ENV': 'development'
})
</code>```

To quote the documentation:

Note that because the plugin does a direct text replacement, the value given to it must include actual quotes inside of the string itself. Typically, this is done either with either alternate quotes, such as '"production"', or by using JSON.stringify('production').

If you replace it with, for example, the following, it should work:

```<code>new DefinePlugin({
  'process.env.NODE_ENV': '"development"'
})
</code>```

Body:
Given that these are the dependencies that I am using:

"react-hot-loader": "3.0.0-beta.7",
"webpack": "2.6.1",
"webpack-dev-middleware": "^1.11.0",
"webpack-hot-middleware": "^2.18.1",
"webpack-merge": "^4.1.0"

Error

patch.js:5

Uncaught ReferenceError: development is not defined
    at Object.defineProperty.value (patch.js:5)
    at __webpack_require__ (bootstrap 921586e…:659)
    at fn (bootstrap 921586e…:85)
    at Object.options.path (patch.js:1)
    at __webpack_require__ (bootstrap 921586e…:659)
    at fn (bootstrap 921586e…:85)
    at Object.<anonymous> (process-update.js:132)
    at __webpack_require__ (bootstrap 921586e…:659)
    at validateFormat (bootstrap 921586e…:708)
    at bootstrap 921586e…:708

You might want to either take a look at this repo

webpack-config

const FILE_PATHS = {
  entry: path.resolve('./src/index.js'),
  reactHotLoader: 'react-hot-loader/patch',
  hmrEntry: 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', // this is from the webpack-hot-middleware docs
  output: '/' // this is the path used by webpack-dev-middleware, the docs say no real path is required, just pass in `/`
}

const devOnly = {
  entry: FILE_PATHS.entry,
  output: {
    path: '/',
    publicPath: '/assets/',
    filename: 'bundle.js'
  },
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          {
            loader: 'babel-loader'
          }
        ],
        // react-hot-loader asks to include src and exclude node_modules in https://github.com/gaearon/react-hot-loader/blob/master/docs/Troubleshooting.md
        include: path.resolve('./src'),
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        use: [
          {
            loader: 'json-loader'
          }
        ]
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-sprite-loader'
          }
        ]
      }
    ]
  },
  plugins: [
    new DefinePlugin({
      'process.env.NODE_ENV': 'development'
    })
  ]
}

const hmr = {
  entry: [FILE_PATHS.reactHotLoader, FILE_PATHS.hmrEntry, FILE_PATHS.entry],
  plugins: [new HmrPlugin(), new NoErrorsPlugin()],
  devServer: {
    hot: true
  }
}

const dev = merge(devOnly, hmr)

module.exports = {dev}

Express Server

// process.env.NODE_ENV = 'development'
const express = require('express')
const webpack = require('webpack')
const historyApiFallback = require('connect-history-api-fallback')

const normalizeAssets = assets => {
  return Array.isArray(assets) ? assets : [assets]
}

const getLinks = assets => {
  const styles = assets.filter(path => path.endsWith('.css'))
  const links = styles.map(path => `<link rel="stylesheet" href="${path}" />`)
  return links.join('\n')
}

const publicPath = '/assets/'

const getScripts = assets => {
  const js = assets.filter(path => path.endsWith('.js'))
  const scripts = js.map(path => `<script src="${path}"></script>`)
  return scripts.join('\n')
}

const devMiddlewareConfig = {
  serverSideRender: true,
  stats: 'normal',
  publicPath: publicPath,
  watchOptions: {
    poll: 1000,
    aggregateTimeout: 300
  }
}

const hotMiddlewareConfig = {
  reload: true,
  overlay: true
}

const devMiddlewareCreator = require('webpack-dev-middleware')
const hotMiddlewareCreator = require('webpack-hot-middleware')

const options = require('./webpack.config')

const {dev: devConfig} = options

const compiler = webpack(devConfig)
const devMiddleware = devMiddlewareCreator(compiler, devMiddlewareConfig)
const hotMiddleware = hotMiddlewareCreator(compiler, hotMiddlewareConfig)

const app = express()
app.use(devMiddleware)
app.use(hotMiddleware)
app.use(express.static(__dirname + '/public'))
app.use((req, res) => {
  const stats = res.locals.webpackStats.toJson()
  const assets = normalizeAssets(stats.assetsByChunkName.main)
  const styles = getLinks(assets)
  const scripts = getScripts(assets)
  res.send(
    `
<!DOCTYPE html>

        <title>Webpack is crazy</title>
        ${styles}

      ${scripts}

`
  )
})

// app.use(historyApiFallback)

app.listen(3000, err => {
  if (!err) {
    console.log('Server is listening on port 3000')
  }
})

Body:
The error is caused by this part of your configuration:

new DefinePlugin({
  'process.env.NODE_ENV': 'development'
})

To quote the documentation:

Note that because the plugin does a direct text replacement, the value given to it must include actual quotes inside of the string itself. Typically, this is done either with either alternate quotes, such as '"production"', or by using JSON.stringify('production').

If you replace it with, for example, the following, it should work:

new DefinePlugin({
  'process.env.NODE_ENV': '"development"'
})


问:
Vuejs: How to properly pass props to component data
i'm playing with Vue 2.0, but there is something unclear..
how can i pass the props to the internal data of a component?
Looking at the documentation it seems that i have done right.

HTML

```<code><lista-servizi :servizi="modello"></lista-servizi>
</code>```

the "modello" is a data already defined.

THE VUE COMPONENT

```<code>Vue.component('lista-servizi', {
 template:
 '<span class="blu">{{listaServizi.lineaGialla.descrizione}}</span>',
    props: ['servizi'],
    data: function(){
    return{
       listaServizi : this.servizi
    }
</code>```

basically i try to give to data listaServizi the same value as props servizi,
but in the console i have the following message:

```<code>[Vue warn]: Error in render function: "TypeError: Cannot read property 'descrizione' of undefined"

found in

---> <ListaServizi>
       <Root>
</code>```

答:
You should used computed instead.

```<code>Vue.component('lista-servizi', {
  //...
  computed: {
    listaServizi() {
      return this.servizi
    }
  }
}
</code>```

Body:
i'm playing with Vue 2.0, but there is something unclear..
how can i pass the props to the internal data of a component?
Looking at the documentation it seems that i have done right.

HTML

<lista-servizi :servizi="modello"></lista-servizi>

the "modello" is a data already defined.

THE VUE COMPONENT

Vue.component('lista-servizi', {
 template:
 '{{listaServizi.lineaGialla.descrizione}}',
    props: ['servizi'],
    data: function(){
    return{
       listaServizi : this.servizi
    }

basically i try to give to data listaServizi the same value as props servizi,
but in the console i have the following message:

[Vue warn]: Error in render function: "TypeError: Cannot read property 'descrizione' of undefined"

found in

---> <ListaServizi>
       <Root>

Body:
You should used computed instead.

Vue.component('lista-servizi', {
  //...
  computed: {
    listaServizi() {
      return this.servizi
    }
  }
}


问:
AttributeError when using requests.post() in `with` statement
A/C python requests documentation, with statement can be used with requests for better speed.

with requests.get('http://httpbin.org/get', stream=True) as r:
      # Do things with the response here.

So why is this returning 'Attribute error'?

```<code>Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
with requests.post(url,headers=headers,data=data,stream=True) as post_res:
AttributeError: __exit__
</code>```

code:

```<code>with requests.post(url,headers=headers,data=data,stream=True) as post_res:
    print(b'Name' in post_res.content)
</code>```

P.S. This is working fine without 'with' statement.

答: AFAICS a context manager is documented only for GET requests, not POST. That does make sense since POST is not idempotent anyway.

Body:
A/C python requests documentation, with statement can be used with requests for better speed.

with requests.get('http://httpbin.org/get', stream=True) as r:
      # Do things with the response here.

So why is this returning 'Attribute error'?

Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
with requests.post(url,headers=headers,data=data,stream=True) as post_res:
AttributeError: __exit__

code:

with requests.post(url,headers=headers,data=data,stream=True) as post_res:
    print(b'Name' in post_res.content)

P.S. This is working fine without 'with' statement.


问:
How to refer long query, written in external file, in Spring data jpa @Query

I want to write query (properties or yaml) in external file to load database. -

This is long query and does not look good to eye when placed inside @Query("long query") in XXXRepository class.

Is there way to write this query in an external file (properties, yaml, xml or json) and call that file in @Query() in spring data jpa?

答:
You can use named queries, where the queries have to be defined in a file called META-INF/jpa-named-queries.properties. See the spring example:

```<code>User.findBySpringDataNamedQuery=select u from User u where u.lastname=?1
</code>```

Reference the query by name in the annotation in your repository, here the corresponding repository example from spring:

```<code>@Query(name = "User.findBySpringDataNamedQuery", countProjection = "u.firstname")
Page<User> findByNamedQueryAndCountProjection(String firstname, Pageable page);
</code>```

Body:
You can use named queries, where the queries have to be defined in a file called META-INF/jpa-named-queries.properties. See the spring example:

User.findBySpringDataNamedQuery=select u from User u where u.lastname=?1

Reference the query by name in the annotation in your repository, here the corresponding repository example from spring:

@Query(name = "User.findBySpringDataNamedQuery", countProjection = "u.firstname")
Page<User> findByNamedQueryAndCountProjection(String firstname, Pageable page);


问:
Qestion about understanding "detach()" on threads in C++
I always saw in the internet the rule:

If you don't detach\join a thread, then abort will be called.

I need a reason for why that abort happens.

I can understand with join — because when not doing join to some thread, the the main can be closed before the thread and it can make problems.

But detach doesn't do anything! It has no purpose (at least from what I've seen when running a thread with or without being detached).

What exactly make the abort to jump, any what exactly is the purpose of detach?

Here is a simple example for what causing "aborting":

```<code>#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void pause_thread(int n)
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}

int main()
{
  std::cout << "Spawning and detaching 3 threads...\n";
  std::thread (pause_thread,1);
  std::cout << "Done spawning threads.\n";
  // give the detached threads time to finish (but not guaranteed!):
  pause_thread(5);
  return 0;
}
</code>```

答:
A thread is a different beast from a process. Threads are not in a parent/child relation at all.

C++11 thread implementation has to be compatible with all major OS threads, so it had to make design decisions, which cannot be understood at first sight.

I'll describe pthread, which is used in the linux world.

When you create a thread, you can specify its detachstate. It can be two values:

DETACHED: when the thread exits, its allocated resources automatically released. Thread cannot be joined.

JOINABLE: when the thread exits, some of its resources are not automatically freed. For example, its return code (in pthread, there is a return value of a thread). Thread can be joined. Resources will be freed at join().

C++ threads are created as JOINABLE, but you can detach it later.

Now, if you don't detach/join a thread, at ~thread(), what could a thread implementation do? It is an issue, because if it doesn't do anything, then some resource will be silently leaked (as a JOINABLE thread when exits, some of its resources are not automatically freed)

call join() automatically: not a good idea, as the program can stall on it (if the thread still runs). It is potentially a programming bug.

call detach() automatically: not a good idea either, as it could be a programming bug (thread continue to run, but its thread object is destroyed -  a programmer should explicitly call detach() in this case)

call abort(): this is the best that an implementation can do, to avoid programming errors

So the designers of std::thread chose to call abort() to avoid programming errors.

(On windows, the thread system is similar. You have to call CloseHandle for a thread so its resources can be released)

Body:
I always saw in the internet the rule:

If you don't detach\join a thread, then abort will be called.

I need a reason for why that abort happens.

I can understand with join — because when not doing join to some thread, the the main can be closed before the thread and it can make problems.

But detach doesn't do anything! It has no purpose (at least from what I've seen when running a thread with or without being detached).

What exactly make the abort to jump, any what exactly is the purpose of detach?

Here is a simple example for what causing "aborting":

#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void pause_thread(int n)
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}

int main()
{
  std::cout << "Spawning and detaching 3 threads...\n";
  std::thread (pause_thread,1);
  std::cout << "Done spawning threads.\n";
  // give the detached threads time to finish (but not guaranteed!):
  pause_thread(5);
  return 0;
}


问:
Spring Integration - Apache ActiveMQ to Kafka
I am using the below configuration for integrating activemq with kafka. I receive message from activemq and forwards it to kafka. However, i am noticing that messages are getting dequeued from JMS Queue but messages are not going to kafka.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://www.springframework.org/schema/integration/jms"
    xmlns:integration="http://www.springframework.org/schema/integration"
    xmlns:int-kafka="http://www.springframework.org/schema/integration/kafka"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration/jms
    http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
    http://www.springframework.org/schema/integration/kafka
    http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd">

    <jms:message-driven-channel-adapter
        id="helloJMSAdapater" destination="helloJMSQueue" connection-factory="jmsConnectionfactory"
        channel="helloChannel" extract-payload="true" />

    <integration:channel id="helloChannel" />

    <integration:service-activator id="sayHelloServiceActivator"
        input-channel="helloChannel" ref="sayHelloService" method="sayHello" />

    <int-kafka:outbound-channel-adapter
        id="kafkaOutboundChannelAdapter" kafka-template="template"
        auto-startup="false" sync="true" channel="helloChannel" topic="test1234"
        >
    </int-kafka:outbound-channel-adapter>

    <bean id="template" class="org.springframework.kafka.core.KafkaTemplate">
        <constructor-arg>
            <bean class="org.springframework.kafka.core.DefaultKafkaProducerFactory">
                <constructor-arg>
                    <map>
                        <entry key="bootstrap.servers" value="localhost:9092" />
                        <!--entry key="retries" value="5" /> <entry key="batch.size" value="16384"
                            /> <entry key="linger.ms" value="1" /> <entry key="buffer.memory" value="33554432"
                            /> < entry key="key.serializer" value="org.apache.kafka.common.serialization.StringSerializer"
                            /> <entry key="value.serializer" value="org.apache.kafka.common.serialization.StringSerializer"
                            / -->
                    </map>
                </constructor-arg>
            </bean>
        </constructor-arg>
    </bean>

</beans>
</code>```

Also, in case there is any issue from Kafka, it is not even reporting any exception stack trace.

Did i miss anything ?

答:
As @Hassen Bennour says, if you want to send a message to two consumers, you need a publish/subscribe channel.

That said, you have auto-startup="false" on the kafka adapter, so it won't even be subscribed to the channel.

If it was started, with your current configuration messages would be sent round-robin alternately to the service activator and adapter.

Body:
I am using the below configuration for integrating activemq with kafka. I receive message from activemq and forwards it to kafka. However, i am noticing that messages are getting dequeued from JMS Queue but messages are not going to kafka.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jms="http://www.springframework.org/schema/integration/jms"
    xmlns:integration="http://www.springframework.org/schema/integration"
    xmlns:int-kafka="http://www.springframework.org/schema/integration/kafka"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration/jms
    http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
    http://www.springframework.org/schema/integration/kafka
    http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd">

    <jms:message-driven-channel-adapter
        id="helloJMSAdapater" destination="helloJMSQueue" connection-factory="jmsConnectionfactory"
        channel="helloChannel" extract-payload="true" />

    <integration:channel id="helloChannel" />

    <integration:service-activator id="sayHelloServiceActivator"
        input-channel="helloChannel" ref="sayHelloService" method="sayHello" />

    <int-kafka:outbound-channel-adapter
        id="kafkaOutboundChannelAdapter" kafka-template="template"
        auto-startup="false" sync="true" channel="helloChannel" topic="test1234"
        >
    </int-kafka:outbound-channel-adapter>

    <bean id="template" class="org.springframework.kafka.core.KafkaTemplate">
        <constructor-arg>
            <bean class="org.springframework.kafka.core.DefaultKafkaProducerFactory">
                <constructor-arg>
                    <map>
                        <entry key="bootstrap.servers" value="localhost:9092" />

                    </map>
                </constructor-arg>
            </bean>
        </constructor-arg>
    </bean>

</beans>

Also, in case there is any issue from Kafka, it is not even reporting any exception stack trace.

Did i miss anything ?


问:
SQL Server Stored Procedure Optimization
I have the following stored procedure running against an ExtractedMessages table which might contain up to 100M records (100,000,000).

For the purpose of my application, this stored procedure should run in less than one second

```<code>CREATE PROCEDURE GetNextMessages
    @taskId bigint
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ci INT
    DECLARE @cr INT

    SELECT
        @ci = CurrentIndex, @cr = CurrentResources
    FROM
        ExtractedTasks
    WHERE
        Id = @taskId

    UPDATE ExtractedTasks
    SET CurrentIndex = @ci + @cr
    WHERE Id = @taskId

    SELECT *
    FROM ExtractedMessages
    WHERE TaskId = @taskId
    ORDER BY Id
        OFFSET @ci ROWS
        FETCH NEXT @cr ROWS ONLY
END
</code>```

NB: cr can not be more than 1500

答:
Thanks Everyone for your kind help
I was able to identify the problem, after all it was a memory management issue on the server that is running SQL server. I have increased the dedicated memory of the server. And the issue has been resolved. The SP works smoothly now</p>

Body:
I have the following stored procedure running against an ExtractedMessages table which might contain up to 100M records (100,000,000).

For the purpose of my application, this stored procedure should run in less than one second

CREATE PROCEDURE GetNextMessages
    @taskId bigint
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ci INT
    DECLARE @cr INT

    SELECT
        @ci = CurrentIndex, @cr = CurrentResources
    FROM
        ExtractedTasks
    WHERE
        Id = @taskId

    UPDATE ExtractedTasks
    SET CurrentIndex = @ci + @cr
    WHERE Id = @taskId

    SELECT *
    FROM ExtractedMessages
    WHERE TaskId = @taskId
    ORDER BY Id
        OFFSET @ci ROWS
        FETCH NEXT @cr ROWS ONLY
END

NB: cr can not be more than 1500


问:
Find a substring and print it
I have this string

```<code>$string = "create or replace view COMPLEX_NAME_2 (b21d,21ld21)";
</code>```

I want to get the COMPLEX_NAME_2 and print it.

Keep in mind that that COMPLEX_NAME_2 is the sub string I need to find and it changes its value. I don't know how to get the substring in that place in the string—the value of the substring doesn't matter.

I tried

```<code>$string =~ m/view/gi;
print $';
</code>```

But the problem it is that it prints (b21d,21ld21) as well and I need only the name.

答:
If there are never any spaces in the substring then you can use a capture to save all non-space characters after view

Like this

```<code>if ( $string =~ /view\s+(\S+)/ ) {
    print $1, "\n";
}
</code>```

Title: Find a substring and print it

Body:
I have this string

$string = "create or replace view COMPLEX_NAME_2 (b21d,21ld21)";

I want to get the COMPLEX_NAME_2 and print it.

Keep in mind that that COMPLEX_NAME_2 is the sub string I need to find and it changes its value. I don't know how to get the substring in that place in the string—the value of the substring doesn't matter.

I tried

$string =~ m/view/gi;
print $';

But the problem it is that it prints (b21d,21ld21) as well and I need only the name.

Body:
If there are never any spaces in the substring then you can use a capture to save all non-space characters after view

Like this

if ( $string =~ /view\s+(\S+)/ ) {
    print $1, "\n";
}


问:
Assigning Number Values to String Array
I am trying to find a way to make an array with strings have values such as [1, 2, 3, 4,...] and so on.I believe I saw a way to do it utilizing 'indexOf + 1' thanks for any help.</p>

```<code>function sortGrades(lst){
var grades = ["VB", "V0", "V0+","V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8",` "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17"];

 }
</code>```

答:
Perhaps something like this?

```<code>grades.map(function(v,i) { return i + 1; });
// Or cleaner but ES5:
grades.map((v,i) => i+1)
</code>```

Even though I might have misunderstood your question.

Title: Assigning Number Values to String Array

Body:
I am trying to find a way to make an array with strings have values such as [1, 2, 3, 4,...] and so on.I believe I saw a way to do it utilizing 'indexOf + 1' thanks for any help.

function sortGrades(lst){
var grades = ["VB", "V0", "V0+","V1", "V2", "V3", "V4", "V5", "V6", "V7",
"V8",` "V9", "V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17"];

 }

Body:
Perhaps something like this?

grades.map(function(v,i) { return i + 1; });
// Or cleaner but ES5:
grades.map((v,i) => i+1)

Even though I might have misunderstood your question.