问:
Parsing MuleSoft CXF Request
I am attempting to parse a request that I am receiving at one of the end-points I have created in MuleSoft.

This is a SOAP Request coming from Salesforce, I wan't to be able to just get the XML and grab a value from it. The soap request message is below.

SAMPLE SOAP REQUEST:

```<code><?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <notifications
            xmlns="http://soap.sforce.com/2005/09/outbound">
            <OrganizationId>00123jhk1h230AQ</OrganizationId>
            <ActionId>04215wergf2345AA0</ActionId>
            <SessionId>00Dn00000008w1T!AQ0AQLiuZg345345EGC8LAY00OqInU_Exn4.FVinnwwc2j.Naerwt2323g0R4qi9ykmHt.eertert212342dh</SessionId>
            <EnterpriseUrl>https://12fwghoft.cs50.my.salesforce.com/services/Soap/c/39.0/00Dn00000008w1T</EnterpriseUrl>
            <PartnerUrl>https://12fwghoft.cs50.my.salesforce.com/services/Soap/u/39.0/00Dn00000008w1T</PartnerUrl>
            <Notification>
                <Id>04l45611902IG</Id>
                <sObject xsi:type="sf:Account"
                    xmlns:sf="urn:sobject.enterprise.soap.sforce.com">
                    <sf:Id>00q2sv2224ggwAV</sf:Id>
                </sObject>
            </Notification>
        </notifications>
    </soapenv:Body>
</soapenv:Envelope>
</code>```

MULE INBOUND MESSAGE DETAILS:

```<code>org.mule.DefaultMuleMessage
{
  id=114f2110-0058-11e7-9989-5ce0c55142df
  payload=[Ljava.lang.Object;
  correlationId=<not set>
  correlationGroup=-1
  correlationSeq=-1
  encoding=UTF-8
  exceptionPayload=<not set>

Message properties:
  INVOCATION scoped properties:
    _ApikitResponseTransformer_AcceptedHeaders=*/*
    _ApikitResponseTransformer_apikitRouterRequest=yes
    _ApikitResponseTransformer_contractMimeTypes=[]
    cxf_operation={http://soap.sforce.com/2005/09/outbound}notifications
    cxf_service={http://soap.sforce.com/2005/09/outbound}NotificationPortService
    method=public abstract boolean sfdc.account.NotificationPort.notifications(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.util.List)
  INBOUND scoped properties:
    accept-encoding=gzip
    cache-control=max-age=259200
    content-length=1028
    content-type=text/xml; charset=utf-8
    host=36ce69be.ngrok.io
    http.listener.path=/api/*
    http.method=POST
    http.query.params=ParameterMap{[]}
    http.query.string=
    http.relative.path=/api/netsuite/customers
    http.remote.address=/127.0.0.1:59266
    http.request.path=/api/netsuite/customers
    http.request.uri=/api/netsuite/customers
    http.scheme=http
    http.uri.params=ParameterMap{[]}
    http.version=HTTP/1.1
    soapaction=""
    user-agent=Jakarta Commons-HttpClient/3.1
    x-forwarded-for=136.147.62.8
  OUTBOUND scoped properties:
    MULE_ENCODING=UTF-8
  SESSION scoped properties:
}
</code>```

答:
You can extract SOAP message body part xml using below simple xsl code with the XSLT transformer step.</p>

```<code>    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:outbound="http://soap.sforce.com/2005/09/outbound">
        <xsl:template match="/">
         <xsl:copy-of select="/soapenv:Envelope/soapenv:Body/outbound:notifications"/>
        </xsl:template>
    </xsl:stylesheet>
</code>```

Title: Parsing MuleSoft CXF Request

Body:
I am attempting to parse a request that I am receiving at one of the end-points I have created in MuleSoft.

This is a SOAP Request coming from Salesforce, I wan't to be able to just get the XML and grab a value from it. The soap request message is below.

SAMPLE SOAP REQUEST:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <notifications
            xmlns="http://soap.sforce.com/2005/09/outbound">
            <OrganizationId>00123jhk1h230AQ</OrganizationId>
            <ActionId>04215wergf2345AA0</ActionId>
            <SessionId>00Dn00000008w1T!AQ0AQLiuZg345345EGC8LAY00OqInU_Exn4.FVinnwwc2j.Naerwt2323g0R4qi9ykmHt.eertert212342dh</SessionId>
            <EnterpriseUrl>https://12fwghoft.cs50.my.salesforce.com/services/Soap/c/39.0/00Dn00000008w1T</EnterpriseUrl>
            <PartnerUrl>https://12fwghoft.cs50.my.salesforce.com/services/Soap/u/39.0/00Dn00000008w1T</PartnerUrl>
            <Notification>
                <Id>04l45611902IG</Id>
                <sObject xsi:type="sf:Account"
                    xmlns:sf="urn:sobject.enterprise.soap.sforce.com">
                    <sf:Id>00q2sv2224ggwAV</sf:Id>
                </sObject>
            </Notification>
        </notifications>
    </soapenv:Body>
</soapenv:Envelope>

MULE INBOUND MESSAGE DETAILS:

org.mule.DefaultMuleMessage
{
  id=114f2110-0058-11e7-9989-5ce0c55142df
  payload=[Ljava.lang.Object;
  correlationId=<not set>
  correlationGroup=-1
  correlationSeq=-1
  encoding=UTF-8
  exceptionPayload=<not set>

Message properties:
  INVOCATION scoped properties:
    _ApikitResponseTransformer_AcceptedHeaders=*/*
    _ApikitResponseTransformer_apikitRouterRequest=yes
    _ApikitResponseTransformer_contractMimeTypes=[]
    cxf_operation={http://soap.sforce.com/2005/09/outbound}notifications
    cxf_service={http://soap.sforce.com/2005/09/outbound}NotificationPortService
    method=public abstract boolean sfdc.account.NotificationPort.notifications(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.util.List)
  INBOUND scoped properties:
    accept-encoding=gzip
    cache-control=max-age=259200
    content-length=1028
    content-type=text/xml; charset=utf-8
    host=36ce69be.ngrok.io
    http.listener.path=/api/*
    http.method=POST
    http.query.params=ParameterMap{[]}
    http.query.string=
    http.relative.path=/api/netsuite/customers
    http.remote.address=/127.0.0.1:59266
    http.request.path=/api/netsuite/customers
    http.request.uri=/api/netsuite/customers
    http.scheme=http
    http.uri.params=ParameterMap{[]}
    http.version=HTTP/1.1
    soapaction=""
    user-agent=Jakarta Commons-HttpClient/3.1
    x-forwarded-for=136.147.62.8
  OUTBOUND scoped properties:
    MULE_ENCODING=UTF-8
  SESSION scoped properties:
}

Body:
You can extract SOAP message body part xml using below simple xsl code with the XSLT transformer step.

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:outbound="http://soap.sforce.com/2005/09/outbound">
        <xsl:template match="/">
         <xsl:copy-of select="/soapenv:Envelope/soapenv:Body/outbound:notifications"/>
        </xsl:template>
    </xsl:stylesheet>


来源: stackexchange

问:
100% CPU, stuck on CreateDelegate and CerHashtable`2.get_Item
I have a .NET 3.5 website that occasionally hangs and spikes to 100% CPU.  Running a dump through WinDbg shows that about half of my threads are sitting at

```<code>System.Reflection.CerHashtable`2[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].get_Item(System.__Canon)
</code>```

and the other half are sitting at

```<code>System.Reflection.Emit.DynamicMethod.CreateDelegate(System.Type)
</code>```

they are all in the middle of LINQ-to-SQL queries. Does anybody know what could be going on here?  The DB appears to remain responsive, at least from SSMS while the problem is going on.

If anyone needs more information to go on, let me know.

Edit:

There are 22 threads.  (and I was generalizing when I said half)  This is output of !threads

```ThreadCount: 23
UnstartedThread: 0
BackgroundThread: 22
PendingThread: 0
DeadThread: 1
Hosted Runtime: no
                                              PreEmptive                                                Lock
       ID OSID        ThreadOBJ     State   GC     GC Alloc Context                  Domain           Count APT Exception
   7    1 19a0 00000000022c7710      8220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 Ukn
  27    2 1fa0 0000000005591f90      b220 Enabled  00000001a0425058:00000001a04266c0 00000000022a2940     0 MTA (Finalizer)
  29    3 4824 0000000006550450   380b220 Enabled  000000012213cf18:000000012213dec0 00000000067500a0     1 MTA (Threadpool Worker)
  30    4 40c8 00000000061378c0   380b220 Enabled  00000001c1f84c38:00000001c1f860f0 00000000067500a0     1 MTA (Threadpool Worker)
  31    5 2a54 0000000006138770   180b220 Disabled 0000000101e3c858:0000000101e3db00 00000000067500a0     2 MTA (Threadpool Worker)
  32    6 1984 000000000613c940   180b220 Enabled  0000000000000000:0000000000000000 00000000067500a0     0 MTA (Threadpool Worker) System.ObjectDisposedException (000000017fffe458)
  33    7 18d8 000000000613eb80   380b220 Enabled  00000001820c3a30:00000001820c3c90 00000000067500a0     1 MTA (Threadpool Worker)
  34    8 31f4 0000000006141d10   380b220 Enabled  0000000122147048:0000000122147ec0 00000000067500a0     1 MTA (Threadpool Worker)
  35    9 5fe4 00000000061427c0   180b220 Enabled  00000001e1ffbdc8:00000001e1ffc190 00000000067500a0     2 MTA (Threadpool Worker)
  36    a 3768 0000000006143270   180b220 Enabled  00000001e200add0:00000001e200c190 00000000067500a0     1 MTA (Threadpool Worker)
  37    b 1820 000000000670fa10    80a220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 MTA (Threadpool Completion Port)
  38    c 1220 000000000673e160      1220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 Ukn
  39    d 507c 0000000008c1f9b0   180b220 Enabled  0000000101e392d0:0000000101e39b00 00000000067500a0     2 MTA (Threadpool Worker)
  14    e 651c 000000000a507000   880a220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 MTA (Threadpool Completion Port)
  40    f 14a0 000000000ab0a850   380b220 Enabled  00000001a15886c0:00000001a158a638 00000000067500a0     1 MTA (Threadpool Worker)
XXXX   10    0 000000000bd7c7b0      9820 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 MTA
  42   11 48d8 000000000c00c120   380b220 Enabled  0000000000000000:0000000000000000 00000000067500a0     0 MTA (Threadpool Worker)
   3   12 6180 000000000c00c6f0       220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 Ukn
  43   13 3798 000000000c00d290   180b220 Enabled  00000001420f9730:00000001420f9828 00000000067500a0     2 MTA (Threadpool Worker)
  45   14 1be8 000000001184f150   180b220 Enabled  00000001c1f880e0:00000001c1f880f0 00000000067500a0     2 MTA (Threadpool Worker)
  48   15 13ec 000000001184f720   200b220 Enabled  0000000000000000:0000000000000000 00000000067500a0     1 MTA
  49   17 3bac 00000000198f1b20   180b220 Enabled  0000000182059020:0000000182059c90 00000000067500a0     2 MTA (Threadpool Worker)
  50   16 4670 00000000197b6b00   380b220 Enabled  0000000162040fd0:0000000162042658 00000000067500a0     1 MTA (Threadpool Worker)
```

and this is the lengthy result of !EEStack   (posted on pastebin since it wouldn't fit in this post)

http://pastebin.com/qcF4jX1g

I am using SQL 2005 standard

EDIT:

Here is the result is !syncblk, which shows the "CerHashtable" as the owner, although all threads on CerHashtable appear to be waiting for a lock?

```Index         SyncBlock MonitorHeld Recursion Owning Thread Info          SyncBlock Owner
  148 000000000e4ec1f8           12         0 0000000000000000     none    000000017fe48560 System.Reflection.CerHashtable`2[[System.Reflection.RuntimeMethodInfo, mscorlib],[System.Reflection.RuntimeMethodInfo, mscorlib]]
        Waiting threads:*** WARNING: Unable to verify checksum for NewRelic.Profiler.dll
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for NewRelic.Profiler.dll -
 29 30 33 34 40 50
-----------------------------
Total           252
CCW             3
RCW             5
ComClassFactory 0
Free            81
```

答:
Linq-To-Sql was discontinued by Microsoft.

They recommend using Entity Framework.

It would not be a huge overhaul since you linq code us still valid.
You just need to recreate you data model.

For .Net 3.5 you can use EF v1.

Try to download Microsoft .NET Framework 3.5 Service Pack 1 from http://www.microsoft.com/download/en/details.aspx?id=22

It should include The First version of Entity Framework (EFv1) as stated on http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework.

ContentLicense: CC BY-SA 3.0

Body:
I have a .NET 3.5 website that occasionally hangs and spikes to 100% CPU.  Running a dump through WinDbg shows that about half of my threads are sitting at

System.Reflection.CerHashtable`2[[System.__Canon, mscorlib],[System.__Canon, mscorlib]].get_Item(System.__Canon)

and the other half are sitting at

System.Reflection.Emit.DynamicMethod.CreateDelegate(System.Type)

they are all in the middle of LINQ-to-SQL queries. Does anybody know what could be going on here?  The DB appears to remain responsive, at least from SSMS while the problem is going on.

If anyone needs more information to go on, let me know.

Edit:

There are 22 threads.  (and I was generalizing when I said half)  This is output of !threads

ThreadCount: 23
UnstartedThread: 0
BackgroundThread: 22
PendingThread: 0
DeadThread: 1
Hosted Runtime: no
                                              PreEmptive                                                Lock
       ID OSID        ThreadOBJ     State   GC     GC Alloc Context                  Domain           Count APT Exception
   7    1 19a0 00000000022c7710      8220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 Ukn
  27    2 1fa0 0000000005591f90      b220 Enabled  00000001a0425058:00000001a04266c0 00000000022a2940     0 MTA (Finalizer)
  29    3 4824 0000000006550450   380b220 Enabled  000000012213cf18:000000012213dec0 00000000067500a0     1 MTA (Threadpool Worker)
  30    4 40c8 00000000061378c0   380b220 Enabled  00000001c1f84c38:00000001c1f860f0 00000000067500a0     1 MTA (Threadpool Worker)
  31    5 2a54 0000000006138770   180b220 Disabled 0000000101e3c858:0000000101e3db00 00000000067500a0     2 MTA (Threadpool Worker)
  32    6 1984 000000000613c940   180b220 Enabled  0000000000000000:0000000000000000 00000000067500a0     0 MTA (Threadpool Worker) System.ObjectDisposedException (000000017fffe458)
  33    7 18d8 000000000613eb80   380b220 Enabled  00000001820c3a30:00000001820c3c90 00000000067500a0     1 MTA (Threadpool Worker)
  34    8 31f4 0000000006141d10   380b220 Enabled  0000000122147048:0000000122147ec0 00000000067500a0     1 MTA (Threadpool Worker)
  35    9 5fe4 00000000061427c0   180b220 Enabled  00000001e1ffbdc8:00000001e1ffc190 00000000067500a0     2 MTA (Threadpool Worker)
  36    a 3768 0000000006143270   180b220 Enabled  00000001e200add0:00000001e200c190 00000000067500a0     1 MTA (Threadpool Worker)
  37    b 1820 000000000670fa10    80a220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 MTA (Threadpool Completion Port)
  38    c 1220 000000000673e160      1220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 Ukn
  39    d 507c 0000000008c1f9b0   180b220 Enabled  0000000101e392d0:0000000101e39b00 00000000067500a0     2 MTA (Threadpool Worker)
  14    e 651c 000000000a507000   880a220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 MTA (Threadpool Completion Port)
  40    f 14a0 000000000ab0a850   380b220 Enabled  00000001a15886c0:00000001a158a638 00000000067500a0     1 MTA (Threadpool Worker)
XXXX   10    0 000000000bd7c7b0      9820 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 MTA
  42   11 48d8 000000000c00c120   380b220 Enabled  0000000000000000:0000000000000000 00000000067500a0     0 MTA (Threadpool Worker)
   3   12 6180 000000000c00c6f0       220 Enabled  0000000000000000:0000000000000000 00000000022a2940     0 Ukn
  43   13 3798 000000000c00d290   180b220 Enabled  00000001420f9730:00000001420f9828 00000000067500a0     2 MTA (Threadpool Worker)
  45   14 1be8 000000001184f150   180b220 Enabled  00000001c1f880e0:00000001c1f880f0 00000000067500a0     2 MTA (Threadpool Worker)
  48   15 13ec 000000001184f720   200b220 Enabled  0000000000000000:0000000000000000 00000000067500a0     1 MTA
  49   17 3bac 00000000198f1b20   180b220 Enabled  0000000182059020:0000000182059c90 00000000067500a0     2 MTA (Threadpool Worker)
  50   16 4670 00000000197b6b00   380b220 Enabled  0000000162040fd0:0000000162042658 00000000067500a0     1 MTA (Threadpool Worker)

and this is the lengthy result of !EEStack   (posted on pastebin since it wouldn't fit in this post)

http://pastebin.com/qcF4jX1g

I am using SQL 2005 standard

EDIT:

Here is the result is !syncblk, which shows the "CerHashtable" as the owner, although all threads on CerHashtable appear to be waiting for a lock?

Index         SyncBlock MonitorHeld Recursion Owning Thread Info          SyncBlock Owner
  148 000000000e4ec1f8           12         0 0000000000000000     none    000000017fe48560 System.Reflection.CerHashtable`2[[System.Reflection.RuntimeMethodInfo, mscorlib],[System.Reflection.RuntimeMethodInfo, mscorlib]]
        Waiting threads:*** WARNING: Unable to verify checksum for NewRelic.Profiler.dll
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for NewRelic.Profiler.dll -
 29 30 33 34 40 50
-----------------------------
Total           252
CCW             3
RCW             5
ComClassFactory 0
Free            81


问:
Java- How to manage a database connection in a large java project
The main question is that in a a large/big java project with multiple classes having multiple db connection,

Should we use a global Single Connection to db and run it till the program ends and close it at the end of program or
Should we use multiple db connections whenever it is required ?
which is better in terms of security , ease of access.

答:
Should we use a global Single Connection to db and run it till the
  program ends and close it at the end of program?

In general, you should never use a single connection for the whole application till the program ends, which is a bad practice.

Should we use multiple db connections whenever it is required?**

Yes, you need to use multiple connections and release each connection object whenever the task is done i.e., ALWAYS close the resources in finally block or use try-with-resources such that they don't create any connection leaks.

Database connection creation is costly and in an enterprise application, you need to go for connection pooling which gets loaded with the specific number of connections during the startup and you will use & return the connections from the pool. You can look here more on this.


问:
Greasemonkey - adjust an input field
I want to manipulate the following code so that when you click in the search box it selects all the text in the box rather than having to double click or press ctrl+A

The current code is:

```<code><input name="sysparm_search" id="sysparm_search" placeholder="Search"
type="search" class="form-control form-control-search">
</code>```

Is this possible to do with greasemonkey scripts?

答:
The most simple way would be the following (using jQuery):

```<code>$("#sysparam_search").click(function() {
    $(this).select();
});
</code>```

There are some drawbacks associated with this kind of selection, though. See this topic for more details: Selecting all text in HTML text input when clicked

Title: Greasemonkey - adjust an input field

Body:
I want to manipulate the following code so that when you click in the search box it selects all the text in the box rather than having to double click or press ctrl+A

The current code is:

<input name="sysparm_search" id="sysparm_search" placeholder="Search"
type="search" class="form-control form-control-search">

Is this possible to do with greasemonkey scripts?

Body:
The most simple way would be the following (using jQuery):

$("#sysparam_search").click(function() {
    $(this).select();
});

There are some drawbacks associated with this kind of selection, though. See this topic for more details: Selecting all text in HTML text input when clicked


问:
HTML, CSS, or JavaScript first? How should I write my code?
I have been learning web development for the past few months now, I have really been enjoying it a lot but I have started my own projects just to mess around and see what I really know.

With my most recent project I have been building my portfolio page, the way I currently write my code goes like this: I write all my HTML first so I have the layout of the page, after I have all of that is written, I then go into my CSS and style everything. Then I go and do JavaScript.

My question is this, is this an efficient way of writing code? Should I keep doing it this way? Or should I write some HTML, style it, go back and forth, then move onto JavaScript? Is there a more efficient way of how you write code?

答:
This is opinion based so there is not a correct answer.

Some may like to write first the html and after that css, others like to write small parts html and after that the css that comes with that particular html, so you are writing step by step your website.

Take a look at https://meta.stackoverflow.com/ for questions like this.

However, to answer your question: I like to write small parts of the application step by step. So, First write HTML and CSS for my Navigation for instance. After I have written the HTML and CSS I like to write the JS of that particular component.

The reason I like this so much is because it's close to the principles of Scrum where you deliver each time a working piece of software instead of piece of code that isn't working at all. So I prefer a website where you have only a working navigation bar above a whole website where nothing is working at all.


问:
when I use nio, serverSocket.accept() throws IllegalBlockingModeException
When I code like this:

```<code>ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();
</code>```

the ServerSocket.accept() method throws java.nio.channels.IllegalBlockingModeException. Why can't I call accept(), even though I set blocking to false?

答:
The Javadoc specifically states that ServerSocketChannel.accept():

Accepts a connection made to this channel's socket.

If this channel is in non-blocking mode then this method will immediately
  return null if there are no pending connections. Otherwise it will block
  indefinitely until a new connection is available or an I/O error occurs.

The general idea is:

If you want to block while waiting for incoming connections, you leave the server socket in blocking mode. If you're writing a server that has nothing to do until a connection actually comes in, then blocking mode is what you want.

If you want to do other things, and periodically check to see whether there's a pending connection, you want non-blocking mode.

Blocking mode is the default for a reason: Most servers don't want to poll their accepting socket for incoming connections.

ContentLicense: CC BY-SA 2.5

Body:
When I code like this:

ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();

the ServerSocket.accept() method throws java.nio.channels.IllegalBlockingModeException. Why can't I call accept(), even though I set blocking to false?

LastEditorDisplayName: sblundy

OwnerDisplayName: Brian Clapper


问:
Updating a MySQL table with the COUNT of another
I'm trying to update a column in table Profiles with a COUNT from another table Videos.  All videos are stored in the Videos table, and I want to create a column in Profiles called VideoCount which shows the COUNT of that user's videos in the Videos table.

Basically, I want to run a cron job - so I need to know how to find the COUNT of a user's videos in the Videos table and then UPDATE that user's VideoCount in Profiles with this count number.

To identify who's uploaded which video, Videos.Owner and Profiles.ID should be made to match.  Does anybody know the SQL which I need to run for the PHP file cron job?

答:
Something like

```<code>UPDATE A SET VideoCount =
(
  SELECT COUNT(B.*)
  FROM Videos AS B INNER JOIN Profiles AS B ON (A.Profile_ID = B.Owner_ID)
  GROUP BY B.Owner_ID
);
</code>```

I'm not sure this syntax is completely correct. give it a try

Body:
Something like

UPDATE A SET VideoCount =
(
  SELECT COUNT(B.*)
  FROM Videos AS B INNER JOIN Profiles AS B ON (A.Profile_ID = B.Owner_ID)
  GROUP BY B.Owner_ID
);

I'm not sure this syntax is completely correct. give it a try


问:
Disconnect signed on user iSeries Navigator
I am using iSeries Navigator 7.1
Is there an option to disconnect the current signed on user?
I think in version 4, there was an option.

The hierarchy is as following:

MyConnections

Databases

Schema

Library A

Library B

Library C
As per my understanding, on each library, I can have a different signed on user. Please correct if I am wrong

答:
I would have preferred to leave a comment....and maybe I missed something in the question, BUT....
Is there an option to disconnect the current signed on user?
If you log into iNav, the hierarchy is something like :

my connections

the 400's IP address (or server address if you prefer)

work management

Systems

subsystems

Active Subsystems

Qinter (Q interactive)

bounce a user from there.
Green screen WRKACTJOB  is easier for me. I just scroll to QINTER and "4" the user, especially when they lock files that are needed for back up process. Seems evil but sometimes required.


问:
SQL: exclude code
I don't understand what's the meaning of this clause:

```<code>cn = (select count(c1.challenge_id) from challenges as c1
group by c1.hacker_id
order by count(c1.challenge_id) desc limit 1) "?
</code>```

Whole SQL:

```<code>select c.hacker_id, h.name, count(c.challenge_id) as cn
from challenges as c join hackers as h
on c.hacker_id = h.hacker_id
group by c.hacker_id having
cn =
(select count(c1.challenge_id) from challenges as c1
 group by c1.hacker_id
 order by count(c1.challenge_id) desc limit 1)
or
cn not in
(select count(c2.challenge_id) from challenges as c2
 group by c2.hacker_id having
 c.hacker_id != c2.hacker_id)
order by cn desc, c.hacker_id
</code>```

答:
```<code>select count(c1.challenge_id) from challenge
</code>```

It counts the number of challenges.

```<code>select count(c1.challenge_id) from challenges as c1
group by c1.hacker_id
</code>```

It counts challenges created by hacker.

E.g Hacker A has created 56 challenges
    Hacker B has create 36 challenges

```<code>order by count(c1.challenge_id) desc limit 1
</code>```

It orders the count of challenges by hackers in descending order. Limit 1 picks up the first element in this order.

It's a query of finding the maximum challenges.

Title: SQL: exclude code

Body:
I don't understand what's the meaning of this clause:

cn = (select count(c1.challenge_id) from challenges as c1
group by c1.hacker_id
order by count(c1.challenge_id) desc limit 1) "?

Whole SQL:

select c.hacker_id, h.name, count(c.challenge_id) as cn
from challenges as c join hackers as h
on c.hacker_id = h.hacker_id
group by c.hacker_id having
cn =
(select count(c1.challenge_id) from challenges as c1
 group by c1.hacker_id
 order by count(c1.challenge_id) desc limit 1)
or
cn not in
(select count(c2.challenge_id) from challenges as c2
 group by c2.hacker_id having
 c.hacker_id != c2.hacker_id)
order by cn desc, c.hacker_id

Body:
select count(c1.challenge_id) from challenge

It counts the number of challenges.

select count(c1.challenge_id) from challenges as c1
group by c1.hacker_id

It counts challenges created by hacker.

E.g Hacker A has created 56 challenges
    Hacker B has create 36 challenges

order by count(c1.challenge_id) desc limit 1

It orders the count of challenges by hackers in descending order. Limit 1 picks up the first element in this order.

It's a query of finding the maximum challenges.


问:
SharpZipLib not compressing memory stream
I have a memory stream that I want to compress:

```<code>public static MemoryStream ZipChunk(MemoryStream unZippedChunk) {

        MemoryStream zippedChunk = new MemoryStream();

        ZipOutputStream zipOutputStream = new ZipOutputStream(zippedChunk);
        zipOutputStream.SetLevel(3);

        ZipEntry entry = new ZipEntry("name");
        zipOutputStream.PutNextEntry(entry);

        Utils.StreamCopy(unZippedChunk, zippedChunk, new byte[4096]);
        zipOutputStream.CloseEntry();

        zipOutputStream.IsStreamOwner = false;
        zipOutputStream.Close();
        zippedChunk.Close();

        return zippedChunk;
    }

public static void StreamCopy(Stream source, Stream destination, byte[] buffer, bool bFlush = true) {
        bool flag = true;
        while (flag) {

            int num = source.Read(buffer, 0, buffer.Length);
            if (num > 0) {
                destination.Write(buffer, 0, num);
            }

            else {

                if (bFlush) {
                    destination.Flush();
                }

                flag = false;
            }
        }
    }
</code>```

It's supposed to be quite simple. You provide it with a stream you want to compress. The methods compresses the stream and returns it. Great.

However, I don't get compressed stream back. What I get are streams that have about 20ish bytes added at the beginning and end, which seem to have something to do with the zip library. But the data in the middle is completely uncompressed (ranges of 256 bytes that have same value, etc). I tried upping the level to 9, but nothing changed.

Why aren't my streams compressing?

答:
You yourself copy original stream right into output stream via:

```<code>Utils.StreamCopy(unZippedChunk, zippedChunk, new byte[4096]);
</code>```

You should copy to zipOutputStream instead:

```<code>StreamCopy(unZippedChunk, zipOutputStream, new byte[4096]);
</code>```

Side note: instead of using custom copy stream methods - use a default one:

```<code>unZippedChunk.CopyTo(zipOutputStream);
</code>```

Body:
I have a memory stream that I want to compress:

public static MemoryStream ZipChunk(MemoryStream unZippedChunk) {

        MemoryStream zippedChunk = new MemoryStream();

        ZipOutputStream zipOutputStream = new ZipOutputStream(zippedChunk);
        zipOutputStream.SetLevel(3);

        ZipEntry entry = new ZipEntry("name");
        zipOutputStream.PutNextEntry(entry);

        Utils.StreamCopy(unZippedChunk, zippedChunk, new byte[4096]);
        zipOutputStream.CloseEntry();

        zipOutputStream.IsStreamOwner = false;
        zipOutputStream.Close();
        zippedChunk.Close();

        return zippedChunk;
    }

public static void StreamCopy(Stream source, Stream destination, byte[] buffer, bool bFlush = true) {
        bool flag = true;
        while (flag) {

            int num = source.Read(buffer, 0, buffer.Length);
            if (num > 0) {
                destination.Write(buffer, 0, num);
            }

            else {

                if (bFlush) {
                    destination.Flush();
                }

                flag = false;
            }
        }
    }

It's supposed to be quite simple. You provide it with a stream you want to compress. The methods compresses the stream and returns it. Great.

However, I don't get compressed stream back. What I get are streams that have about 20ish bytes added at the beginning and end, which seem to have something to do with the zip library. But the data in the middle is completely uncompressed (ranges of 256 bytes that have same value, etc). I tried upping the level to 9, but nothing changed.

Why aren't my streams compressing?

Body:
You yourself copy original stream right into output stream via:

Utils.StreamCopy(unZippedChunk, zippedChunk, new byte[4096]);

You should copy to zipOutputStream instead:

StreamCopy(unZippedChunk, zipOutputStream, new byte[4096]);

Side note: instead of using custom copy stream methods - use a default one:

unZippedChunk.CopyTo(zipOutputStream);


问:
What does $("something") mean in Java?
I was looking into some tutorial and stumbled on this code:

```<code>public void run(String... args) throws Exception {
    eventBus.on($("quotes"), receiver);
    publisher.publishQuotes(NUMBER_OF_QUOTES);
}
</code>```

This is the first time I see $("quotes") in Java. I'd appreciate someone explaining to me what's going on there.

Here's the source:

https://github.com/spring-guides/deprecate-gs-messaging-reactor/blob/master/complete/src/main/java/hello/Application.java#L53

Update:

This is not a question about $ as Java variable name. I know that it's a valid variable name. However, the format of $("something") looks JQuery-like; hence threw me off thinking that it's a special directive or something.

答:
it is just a call to the method called $ that is statically imported:

```<code>import static reactor.bus.selector.Selectors.$;
</code>```

it is just a normal method with a strange name.

'$' is a valid character for identifiers according the Java Language Specification 3.8

The "Java letters" include uppercase and lowercase ASCII Latin  letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for  historical reasons, the ASCII underscore (_, or \u005f) and  dollar sign ($, or \u0024). The $ sign should be used only in mechanically generated source code or, rarely, to access  pre-existing names on legacy systems.

Title: What does $("something") mean in Java?

Body:
I was looking into some tutorial and stumbled on this code:

public void run(String... args) throws Exception {
    eventBus.on($("quotes"), receiver);
    publisher.publishQuotes(NUMBER_OF_QUOTES);
}

This is the first time I see $("quotes") in Java. I'd appreciate someone explaining to me what's going on there.

Here's the source:

https://github.com/spring-guides/deprecate-gs-messaging-reactor/blob/master/complete/src/main/java/hello/Application.java#L53

Update:

This is not a question about $ as Java variable name. I know that it's a valid variable name. However, the format of $("something") looks JQuery-like; hence threw me off thinking that it's a special directive or something.

Body:
it is just a call to the method called $ that is statically imported:

import static reactor.bus.selector.Selectors.$;

it is just a normal method with a strange name.

'$' is a valid character for identifiers according the Java Language Specification 3.8

The "Java letters" include uppercase and lowercase ASCII Latin  letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for  historical reasons, the ASCII underscore (_, or \u005f) and  dollar sign ($, or \u0024). The $ sign should be used only in mechanically generated source code or, rarely, to access  pre-existing names on legacy systems.


问:
How do I concat a column's unique values in a group by for MySQL?
I know how to concat all the values for a field in a group by (see below), but I don't want repeated values. For example, if "Bob" did 5 actions of type "1" and also a type "2", I want only: 1,2, not 1,1,1,1,1,2.

However, the UNIQUE must not be on the total query because I still need the values of the other columns for those actions.

```<code>SELECT
  user.name,
  GROUP_CONCAT(type SEPARATOR ',') AS types,
  SUM(produced)
FROM user
GROUP BY user.name;
</code>```

答:
You can use distinct inside group_cocat function</p>

```<code>SELECT
  user.name,
  GROUP_CONCAT(distinct type SEPARATOR ',') AS types,
  SUM(produced)
FROM user
GROUP BY user.name;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know how to concat all the values for a field in a group by (see below), but I don't want repeated values. For example, if "Bob" did 5 actions of type "1" and also a type "2", I want only: 1,2, not 1,1,1,1,1,2.

However, the UNIQUE must not be on the total query because I still need the values of the other columns for those actions.

SELECT
  user.name,
  GROUP_CONCAT(type SEPARATOR ',') AS types,
  SUM(produced)
FROM user
GROUP BY user.name;

Body:
You can use distinct inside group_cocat function

SELECT
  user.name,
  GROUP_CONCAT(distinct type SEPARATOR ',') AS types,
  SUM(produced)
FROM user
GROUP BY user.name;


问:
Parallel while loop in R
I would like to know if / how it is possible to parallelize a while loop in R.

If it is not possible or reasonably considered too difficult to accomplish, I would greatly appreciate an alternative, possibly using a parallel for loop instead.

答:
You can use futures with any looping R construct including for() and while() loops.  Futures are implemented in the future package (I'm the author).

It is not clear what condition you want to use for your while loop.  That would have helped give a more precise answer.  Here is an example where the while condition does not depend on any of the results calculated:

```<code>library("listenv")
library("future")
plan(multiprocess, workers = 2L)

res <- listenv()

ii <- 1L
while (ii <= 5) {
  ## This is evaluated in parallel and will only block
  ## if all workers are busy.
  res[[ii]] %<-% {
    list(iteration = ii, pid = Sys.getpid())
  }
  ii <- ii + 1L
}

## Resolve all futures (blocks if not already finished)
res <- as.list(res)

str(res)
List of 5
 $ :List of 2
  ..$ iteration: int 1
  ..$ pid      : int 15606
 $ :List of 2
  ..$ iteration: int 2
  ..$ pid      : int 15608
 $ :List of 2
  ..$ iteration: int 3
  ..$ pid      : int 15609
 $ :List of 2
  ..$ iteration: int 4
  ..$ pid      : int 15610
 $ :List of 2
  ..$ iteration: int 5
  ..$ pid      : int 15611
</code>```

If you want your while condition to depend on the outcome of one or more of the parallel results (in res[[ii]]) then things become much more complicated, because then you need to figure out what should happen if the future (= parallel task) is still not resolved; should you check back, say, 5 iterations later, or should you wait.  That's a design issue of the parallel algorithm and not how to implement.  Anything is possible.

PS. I don't understand the downvotes this question received. It could be that it's because your question is poorly phrased / not very clear - remember to try as far as possible to "help the helper help you" by being as precise as possible.  If the downvotes are because of the while loop, I (obviously) beg to disagree.

Title: Parallel while loop in R

Body:
You can use futures with any looping R construct including for() and while() loops.  Futures are implemented in the future package (I'm the author).

It is not clear what condition you want to use for your while loop.  That would have helped give a more precise answer.  Here is an example where the while condition does not depend on any of the results calculated:

library("listenv")
library("future")
plan(multiprocess, workers = 2L)

res <- listenv()

ii <- 1L
while (ii <= 5) {
  ## This is evaluated in parallel and will only block
  ## if all workers are busy.
  res[[ii]] %<-% {
    list(iteration = ii, pid = Sys.getpid())
  }
  ii <- ii + 1L
}

## Resolve all futures (blocks if not already finished)
res <- as.list(res)

str(res)
List of 5
 $ :List of 2
  ..$ iteration: int 1
  ..$ pid      : int 15606
 $ :List of 2
  ..$ iteration: int 2
  ..$ pid      : int 15608
 $ :List of 2
  ..$ iteration: int 3
  ..$ pid      : int 15609
 $ :List of 2
  ..$ iteration: int 4
  ..$ pid      : int 15610
 $ :List of 2
  ..$ iteration: int 5
  ..$ pid      : int 15611

If you want your while condition to depend on the outcome of one or more of the parallel results (in res[[ii]]) then things become much more complicated, because then you need to figure out what should happen if the future (= parallel task) is still not resolved; should you check back, say, 5 iterations later, or should you wait.  That's a design issue of the parallel algorithm and not how to implement.  Anything is possible.

PS. I don't understand the downvotes this question received. It could be that it's because your question is poorly phrased / not very clear - remember to try as far as possible to "help the helper help you" by being as precise as possible.  If the downvotes are because of the while loop, I (obviously) beg to disagree.


问:
Migrate from Google to Firebase analytics Android - Multiple trackers
In my current application, I am using multiple trackers to report my events. However, while migrating to Firebase we found that we can configure only one application corresponding to a Mobile app. Previously I was using multiple trackers to report events to customer and marketing company accounts.

Is it possible to report events to multiple Firebase analytics accounts simultaneously?

I am planning to connect my existing Google analytics accounts to Firebase analytics account. Is it possible for me to route the events from Firebase analytics to multiple Google analytics account? May be using something like Google Tag manager?

答:
It is not possible to report multiple Firebase account simultaneously with Firebase Analytics.

You have few options to emulate multiple trackers in Google Analytics:

You can export the Firebase Analytics data to BigQuery and DataStudio and provide customized access to different parties. This approach gives you a lot of flexibility but its quite involved.

As you suggested you can use Google Tag Manager and send data to multiple Google Analytics accounts. This approach is simpler but it has some limitations. First, you will not get as detailed app reporting from Google Analytics account as you would from Firebase Analytics. Since the data is send independently to each account there might be discrepancies between the accounts. You will be uploading the data multiple times, once for each account, as every account will needs the data uploaded separately. This uses more mobile data and system resources on the device.


问:
missing something with autentication in django?
PYTHON:

```<code>from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.contrib.auth import authenticate

class Firstapp(View):

    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):

        username = request.POST['your_name']
        user = authenticate(username=username)
        return HttpResponse(user)
</code>```

HTML:

```<code><form method="POST">
{% csrf_token %}

<input type="text" name ='your_name' placeholder="username"/>
<button type="submit">Button</button>
</code>```

I have created many users: admin, user_one, user_two etc. Checked via /admin page and usernames are there as they should be. Followed by documentantion in Django I wrote the code, however I don't understand why submiting a username which is in database returns none in Fistapp.post? like authnetication(username='user_one') returns None. Would appreciate your help.

答:
If you are using the default Django backend to authenticate, a password would be required

If what you needs is a authentication without password, I recommend you read this doc

Django would always returns None if has an invalid authentication

Body:
PYTHON:

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from django.contrib.auth import authenticate

class Firstapp(View):

    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):

        username = request.POST['your_name']
        user = authenticate(username=username)
        return HttpResponse(user)

HTML:

<form method="POST">
{% csrf_token %}

<input type="text" name ='your_name' placeholder="username"/>
<button type="submit">Button</button>

I have created many users: admin, user_one, user_two etc. Checked via /admin page and usernames are there as they should be. Followed by documentantion in Django I wrote the code, however I don't understand why submiting a username which is in database returns none in Fistapp.post? like authnetication(username='user_one') returns None. Would appreciate your help.


问:
Obtaining the Build ID in a Java Application
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime? </p>

<p>Building from within Eclipse, all I need is the ID, I can then pass it up to the title.  </p>

答:
If you're using Maven, especially if you want the build number from SVN (though it can generate unique build numbers for you through a configuration), look at the buildnumber-maven-plugin.

You simply add a snippet similar to the following to your pom.xml file:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>buildnumber-maven-plugin</artifactId>
            <version>1.0-beta-3</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>create</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <doCheck>true</doCheck>
                <doUpdate>true</doUpdate>
            </configuration>
        </plugin>
```

<p>Then use ${buildNumber} later on in your pom to refer to the build id.  I use it to write that number to the manifest like so, using the maven-war-plugin.</p>

<pre class="lang-xml prettyprint-override"><code>                <archive>
                    <manifest>
                        <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                    </manifest>
                    <manifestEntries>
                        <Implementation-Build>${buildNumber}</Implementation-Build>
                    </manifestEntries>
                </archive>
</code>```

Body:
Does anyone have a simple suggestion for recording a build ID (generated at compile time) which is displayed in the title bar of the app at runtime?

Building from within Eclipse, all I need is the ID, I can then pass it up to the title.

Body:
If you're using Maven, especially if you want the build number from SVN (though it can generate unique build numbers for you through a configuration), look at the buildnumber-maven-plugin.

You simply add a snippet similar to the following to your pom.xml file:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>buildnumber-maven-plugin</artifactId>
            <version>1.0-beta-3</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>create</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <doCheck>true</doCheck>
                <doUpdate>true</doUpdate>
            </configuration>
        </plugin>

Then use ${buildNumber} later on in your pom to refer to the build id.  I use it to write that number to the manifest like so, using the maven-war-plugin.

                <archive>
                    <manifest>
                        <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                    </manifest>
                    <manifestEntries>
                        <Implementation-Build>${buildNumber}</Implementation-Build>
                    </manifestEntries>
                </archive>


问:
How to enable cors nodejs with express?
In summary I am using a viewer like api of dicom files called cornerstone, for this I connect to the WADO service of dc4chee to get the dicom, dcm4chee runs port 8080, and my application on node uses port 3000, so I am trying to show The browser's dicom.

https://www.npmjs.com/package/cornerstone-wado-image-loader

This is the error displayed by the browser

```<code>XMLHttpRequest can not load http: // localhost: 8080 / wado? RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 & contentType = application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is therefore not allowed access.
</code>```

In the documentation specified

Note that the web server must support Cross source resource sharing or the image will fail to load. If you are unable to get CORS enabled on the web server you are loading DICOM P10 instances from, you can use a reverse proxy. Here's a simple Node.js based on http-proxy that adds CORS headers that you might find useful.

And show this example code but I'm using express and this code does not work

```<code>Var http = require ('http'),
    HttpProxy = require ('http-proxy');

Var proxy = httpProxy.createProxyServer ({target: 'http: // localhost: 8042'}) .listen (8000);

Proxy.on ('proxyRes', function (proxyReq, req, res, options) {
  // add the CORS header to the response
  Res.setHeader ('Access-Control-Allow-Origin', '*');
});

Proxy.on ('error', function (e) {
  // suppress errors
});
</code>```

Also use npm cors here the code

```<code>Var express = require ('express')
Var cors = require ('cors')
Var app = express ()

App.get ('/ products /: id', cors (), function (req, res, next) {
  Res.json ({msg: 'This is CORS-enabled for a Single Route'))
})

App.listen (80, function () {
  Console.log ('CORS-enabled web server listening on port 80')
})
</code>```

But with this I enable the cors on port 3000 and not the 8080, I need the mode to activate or add 'Access-Control-Allow-Origin in headers response and not in header request,

How can I do to add CORS on port 8080 where dcm4chee runs from NODEjs?

update!

The server responds with the following;

RESPONDE HEADER

```<code>Content-Type:application/dicom
Date:Sat, 01 Apr 2017 01:15:38 GMT
Expires:0
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Powered-By:Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA
date=200807181439)/JBossWeb-2.0
</code>```

REQUEST HEADER

```<code>Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:es-ES,es;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:localhost:8080
Origin:http: //localhost:3000
Referer:http: //localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/55.0.2883.87 Safari/537.36
</code>```

HOW TO ENABLE THE CORS IN RESPONSE HEADER??

答:
To enable cors you can do this:

```<code>var cors = require('cors');
app.use(cors());
// to change your ports for different cors stuff:
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'), function() {
  console.log('we are listening on: ',
  app.get('port'))
});
</code>```

Remember that cors are middleware, so you will want to have app.use before it so that your incoming requests will go through cors before they hit your routes.

You can change the ports depending on which one you want to use. I am pretty sure you can also replace the || with && to listen on multiple ports and set cors on those.

In raw node, I believe you have to use the writeHead, but I am not sure about the raw node implementation.

Title: How to enable cors nodejs with express?

Body:
In summary I am using a viewer like api of dicom files called cornerstone, for this I connect to the WADO service of dc4chee to get the dicom, dcm4chee runs port 8080, and my application on node uses port 3000, so I am trying to show The browser's dicom.

https://www.npmjs.com/package/cornerstone-wado-image-loader

This is the error displayed by the browser

XMLHttpRequest can not load http: // localhost: 8080 / wado? RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 & contentType = application% 2Fdicom & transferSyntax = 1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is therefore not allowed access.

In the documentation specified

Note that the web server must support Cross source resource sharing or the image will fail to load. If you are unable to get CORS enabled on the web server you are loading DICOM P10 instances from, you can use a reverse proxy. Here's a simple Node.js based on http-proxy that adds CORS headers that you might find useful.

And show this example code but I'm using express and this code does not work

Var http = require ('http'),
    HttpProxy = require ('http-proxy');

Var proxy = httpProxy.createProxyServer ({target: 'http: // localhost: 8042'}) .listen (8000);

Proxy.on ('proxyRes', function (proxyReq, req, res, options) {
  // add the CORS header to the response
  Res.setHeader ('Access-Control-Allow-Origin', '*');
});

Proxy.on ('error', function (e) {
  // suppress errors
});

Also use npm cors here the code

Var express = require ('express')
Var cors = require ('cors')
Var app = express ()

App.get ('/ products /: id', cors (), function (req, res, next) {
  Res.json ({msg: 'This is CORS-enabled for a Single Route'))
})

App.listen (80, function () {
  Console.log ('CORS-enabled web server listening on port 80')
})

But with this I enable the cors on port 3000 and not the 8080, I need the mode to activate or add 'Access-Control-Allow-Origin in headers response and not in header request,

How can I do to add CORS on port 8080 where dcm4chee runs from NODEjs?

update!

The server responds with the following;

RESPONDE HEADER

Content-Type:application/dicom
Date:Sat, 01 Apr 2017 01:15:38 GMT
Expires:0
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Powered-By:Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA
date=200807181439)/JBossWeb-2.0

REQUEST HEADER

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:es-ES,es;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Host:localhost:8080
Origin:http: //localhost:3000
Referer:http: //localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/55.0.2883.87 Safari/537.36

HOW TO ENABLE THE CORS IN RESPONSE HEADER??

Body:
To enable cors you can do this:

var cors = require('cors');
app.use(cors());
// to change your ports for different cors stuff:
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'), function() {
  console.log('we are listening on: ',
  app.get('port'))
});

Remember that cors are middleware, so you will want to have app.use before it so that your incoming requests will go through cors before they hit your routes.

You can change the ports depending on which one you want to use. I am pretty sure you can also replace the || with && to listen on multiple ports and set cors on those.

In raw node, I believe you have to use the writeHead, but I am not sure about the raw node implementation.


问:
NS-2.34 DYMO patch
i'm trying to add DYMO routing protocol to NS-2.34 but it didn't work,
i'm following this tuto : https://khaledben.wordpress.com/2011/04/16/patching-dymo-um-in-ns-2/

in other hand i can not find dymo-3.patch for ns-2.34 (http://masimum.inf.um.es/?Software:DYMOUM is no more available).

could any one help me to get the patch file or fix this issue please !

答:
"dymoum-0.3.tgz" is here  https://drive.google.com/file/d/0B7S255p3kFXNeTFjUkc4T3NGWjA/view?usp=sharing

ns-allinone-2.34 is old. gcc / g++ version 3.4.6 or 4.1.2 can be used.

I did :

```<code>cd ns-allinone-2.34/
patch -p0 < Edited-dymoum_ns-2.34_v0.3.patch
export CC=gcc34 CXX=g++34 && ./install
</code>```

Testingdymoum/ns/test/{test_2n_m.tcl, test_2n.tcl, test_3n_m.tcl, test_3n.tcl} : All OK. And four nice nam animations.

Second run with Dymoum and ns-2.34 : I made up a new patch from { ns234_gcc49.patch + Edited-dymoum_ns-2.34_v0.3.patch + the dymoum/ folder} to DYMO-03-all_ns234-gcc5.patch. So with a stock ns-allinone-2.34 it is :

```<code>cd ns-allinone-2.34/
patch -p0 < DYMO-03-all_ns234-gcc5.patch
./install
</code>```

Link, DYMO-03-all_ns234-gcc5.patch https://drive.google.com/file/d/0B7S255p3kFXNbHNsUzQ3QXdMa0E/view?usp=sharing

Also available : DYMO-03-all__ns235.patch
https://drive.google.com/file/d/0B7S255p3kFXNejVmQ0duZmRHUEU/view?usp=sharing

For ns-allinone-2.35_gcc482.tar.gz ( All gcc versions 4.6 - 5.2 )
https://drive.google.com/file/d/0B7S255p3kFXNSGJCZ2YzUGJDVk0/view?usp=sharing

Other links 1) The old dymoum_ns-2.34_v0.3.patch (Don't use it)
https://drive.google.com/file/d/0B7S255p3kFXNLXJzdURCZmRzWjA/view?usp=sharing ... uploaded as "old" : dymoum_ns-2.34_v0.3.old.patch

2) "dymoum_ns-2.34_v0.3.patch", edited : Edited-dymoum_ns-2.34_v0.3.patch
https://drive.google.com/file/d/0B7S255p3kFXNeS1oVlkzd0hsd2s/view?usp=sharing

Title: NS-2.34 DYMO patch

Body:
"dymoum-0.3.tgz" is here  https://drive.google.com/file/d/0B7S255p3kFXNeTFjUkc4T3NGWjA/view?usp=sharing

ns-allinone-2.34 is old. gcc / g++ version 3.4.6 or 4.1.2 can be used.

I did :

cd ns-allinone-2.34/
patch -p0 < Edited-dymoum_ns-2.34_v0.3.patch
export CC=gcc34 CXX=g++34 && ./install

Testingdymoum/ns/test/{test_2n_m.tcl, test_2n.tcl, test_3n_m.tcl, test_3n.tcl} : All OK. And four nice nam animations.

Second run with Dymoum and ns-2.34 : I made up a new patch from { ns234_gcc49.patch + Edited-dymoum_ns-2.34_v0.3.patch + the dymoum/ folder} to DYMO-03-all_ns234-gcc5.patch. So with a stock ns-allinone-2.34 it is :

cd ns-allinone-2.34/
patch -p0 < DYMO-03-all_ns234-gcc5.patch
./install

Link, DYMO-03-all_ns234-gcc5.patch https://drive.google.com/file/d/0B7S255p3kFXNbHNsUzQ3QXdMa0E/view?usp=sharing

Also available : DYMO-03-all__ns235.patch
https://drive.google.com/file/d/0B7S255p3kFXNejVmQ0duZmRHUEU/view?usp=sharing

For ns-allinone-2.35_gcc482.tar.gz ( All gcc versions 4.6 - 5.2 )
https://drive.google.com/file/d/0B7S255p3kFXNSGJCZ2YzUGJDVk0/view?usp=sharing

Other links 1) The old dymoum_ns-2.34_v0.3.patch (Don't use it)
https://drive.google.com/file/d/0B7S255p3kFXNLXJzdURCZmRzWjA/view?usp=sharing ... uploaded as "old" : dymoum_ns-2.34_v0.3.old.patch

2) "dymoum_ns-2.34_v0.3.patch", edited : Edited-dymoum_ns-2.34_v0.3.patch
https://drive.google.com/file/d/0B7S255p3kFXNeS1oVlkzd0hsd2s/view?usp=sharing


问:
How to independently use single Zend Framework component like XML-RPC or REST?
Zend framework is well known for loosely coupled components.

I would like to use XML-RPC from zend framework, is there any dependency for XML-RPC? Like if I had taken out XML-RPC folder off Zend Framework Library and try to instantiate RPC object, would it throw error?

Where can I find the proper way of separating component from the framework?

Thanks

答: You should never split single components off a framework or library independent from Zend Framework, or any other. Especially when using PHP there is also no performance reason, because with PHPs autoloading functionality it will always just include the files, which are requested.</p>


问:
Send struct, float and int over UDP sockets in C++
I want to send/receive structs containing float and int variables in client/server socket programs written in C++.

Earlier, the code was written in C, so I was simply sending them as follows:

```<code>//structure definition
struct {
    float a;
    float b;
    float c;
    float d[2];

}myStruct_;

//code to send struct
int slen = sizeof(client_sock)

if(recvfrom(sockFD, &myStruct_, sizeof(myStruct_), 0 ,(struct sockaddr *)&client_sock, &slen)<0) {
            printf("Failure while receiving data %d" , WSAGetLastError());
            getchar();
            exit(1);
}
</code>```

But now in C++, this is giving me this error message:

error: cannot convert '(anonymous struct)*' to 'char *' for argument '2' to 'int recvfrom(SOCKET, char*, int, int, sockaddr*, int*)'

I tried to look for this error, and found out that I have to serialize the struct before sending, and later deserialize the same to get the exact structure. Could you suggest/or provide an example how to serialize and de-serialize it?

答:
The code you showed will work fine in C++ with a little tweaking.

In some platforms (like Linux), recvfrom() is defined as expecting a void* pointer to the memory buffer that it will fill in.  In other platforms (like Windows), recvfrom() expects a char* pointer instead.

To get rid of the error, simply type-cast the buffer pointer (just like you do with the 5th parameter, where you are passing a sockaddr_in* pointer where a sockaddr* pointer is expected):

```<code>recvfrom(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&client_sock, &slen);
</code>```

Do the same thing when sending a struct:

```<code>sendto(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&server_sock, &slen);
</code>```

Body:
I want to send/receive structs containing float and int variables in client/server socket programs written in C++.

Earlier, the code was written in C, so I was simply sending them as follows:

//structure definition
struct {
    float a;
    float b;
    float c;
    float d[2];

}myStruct_;

//code to send struct
int slen = sizeof(client_sock)

if(recvfrom(sockFD, &myStruct_, sizeof(myStruct_), 0 ,(struct sockaddr *)&client_sock, &slen)<0) {
            printf("Failure while receiving data %d" , WSAGetLastError());
            getchar();
            exit(1);
}

But now in C++, this is giving me this error message:

error: cannot convert '(anonymous struct)*' to 'char *' for argument '2' to 'int recvfrom(SOCKET, char*, int, int, sockaddr*, int*)'

I tried to look for this error, and found out that I have to serialize the struct before sending, and later deserialize the same to get the exact structure. Could you suggest/or provide an example how to serialize and de-serialize it?

Body:
The code you showed will work fine in C++ with a little tweaking.

In some platforms (like Linux), recvfrom() is defined as expecting a void* pointer to the memory buffer that it will fill in.  In other platforms (like Windows), recvfrom() expects a char* pointer instead.

To get rid of the error, simply type-cast the buffer pointer (just like you do with the 5th parameter, where you are passing a sockaddr_in* pointer where a sockaddr* pointer is expected):

recvfrom(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&client_sock, &slen);

Do the same thing when sending a struct:

sendto(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&server_sock, &slen);


问:
Centos cgconfig fails to start
I need docker installed on one of my servers, and whenever I try to start the docker service, it fails because of cgconfig. Cgconfig throws the following error:

```<code>Starting cgconfig service: Error: cannot mount cpu to /cgroup/cpu: No such file or directory
/sbin/cgconfigparser; error loading /etc/cgconfig.conf: Cgroup mounting failed
Failed to parse /etc/cgconfig.conf or /etc/cgconfig.d      [FAILED]
</code>```

I'm running CentOS 6.5 Final with the following /etc/cgconfig.conf file:

```<code>mount {
    cpuset  = /cgroup/cpuset;
    cpu     = /cgroup/cpu;
    cpuacct = /cgroup/cpuacct;
    memory  = /cgroup/memory;
    devices = /cgroup/devices;
    freezer = /cgroup/freezer;
    net_cls = /cgroup/net_cls;
    blkio   = /cgroup/blkio;
}
</code>```

I appreciate any responses

答:
To use cgroups on newer versions of CentOS you need to install libcgroup as well as libcgroup-tools:

```<code>$ sudo yum install libcgroup
$ sudo yum install libcgroup-tools
</code>```

To create group use cgcreate, e.g.:

```<code>$ sudo cgcreate -g memory,cpu,blkio,cpuset:userlimited
</code>```

To verify that /etc/cgconfig.conf is correct use cgconfigparser

```<code>$ cgconfigparser -l /etc/cgconfig.conf
</code>```

For details check: https://wiki.archlinux.org/index.php/cgroups

Note: In CentOS 6 and earlier versions one only needed to install libcgroup

Title: Centos cgconfig fails to start

Body:
I need docker installed on one of my servers, and whenever I try to start the docker service, it fails because of cgconfig. Cgconfig throws the following error:

Starting cgconfig service: Error: cannot mount cpu to /cgroup/cpu: No such file or directory
/sbin/cgconfigparser; error loading /etc/cgconfig.conf: Cgroup mounting failed
Failed to parse /etc/cgconfig.conf or /etc/cgconfig.d      [FAILED]

I'm running CentOS 6.5 Final with the following /etc/cgconfig.conf file:

mount {
    cpuset  = /cgroup/cpuset;
    cpu     = /cgroup/cpu;
    cpuacct = /cgroup/cpuacct;
    memory  = /cgroup/memory;
    devices = /cgroup/devices;
    freezer = /cgroup/freezer;
    net_cls = /cgroup/net_cls;
    blkio   = /cgroup/blkio;
}

I appreciate any responses

Body:
To use cgroups on newer versions of CentOS you need to install libcgroup as well as libcgroup-tools:

$ sudo yum install libcgroup
$ sudo yum install libcgroup-tools

To create group use cgcreate, e.g.:

$ sudo cgcreate -g memory,cpu,blkio,cpuset:userlimited

To verify that /etc/cgconfig.conf is correct use cgconfigparser

$ cgconfigparser -l /etc/cgconfig.conf

For details check: https://wiki.archlinux.org/index.php/cgroups

Note: In CentOS 6 and earlier versions one only needed to install libcgroup


问:
sqli take only first value in query
I am building a music player trying to print only  the first row of my database to use it as the first song of the playlist that will be currently playing and the others are going to be stored in a JQuery ListView. I am getting this error code:

Notice: Object of class mysqli_result could not be converted to int in C:\Users\Xaimer\Desktop\Interactive\USBWebserver v8.6\root\playlist.php on line 39.

Line 39 is the if statement

```<code><?php
echo'<p>Playlist</p>';
$sql="SELECT * FROM co1706assigment.tracks INNER JOIN co1706assigment.playlist ON tracks.track_id=playlist.track_id ";
$playlistcounter=mysqli_query($conn,"SELECT count(*) FROM co1706assigment.playlist")or die(mysqli_error($conn));
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while (($row = mysqli_fetch_array($result))&&($row1=mysqli_fetch_array($playlistcounter))) // it takes all the results from sql query
{
    if($playlistcounter<2)
    {
        echo'<ul data-role="listview" data-filter="true">
                            <li><img id="song" src="'.$row["image"].'"/><p class="name">Track Name: </p>'.$row["name"].'
                            <p class="name">Album Name: </p>'.$row["album"].'
                            <p class="name">Sample</p>
                            <audio controls>
                            <source src="'.$row["sample"].'" type="audio/mpeg">
                            </audio>
                            </li>
                            </ul>';
    }
}
echo'<p> My Playlist</p>';
while ($row = mysqli_fetch_array($result)) // it takes all the results from sql query
{
   echo'<ul data-role="listview">
  <li><a href="TrackDescription.php" data-ajax="false">'.$row["name"].'</a></li>
  </ul>';
}
?>
</code>```

答:
Use mysqli_fetch_assoc look to

http://php.net/manual/en/mysqli-result.fetch-assoc.php

OR

use it like this while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){}

Title: sqli take only first value in query

Body:
I am building a music player trying to print only  the first row of my database to use it as the first song of the playlist that will be currently playing and the others are going to be stored in a JQuery ListView. I am getting this error code:

Notice: Object of class mysqli_result could not be converted to int in C:\Users\Xaimer\Desktop\Interactive\USBWebserver v8.6\root\playlist.php on line 39.

Line 39 is the if statement

<?php
echo'
Playlist
';
$sql="SELECT * FROM co1706assigment.tracks INNER JOIN co1706assigment.playlist ON tracks.track_id=playlist.track_id ";
$playlistcounter=mysqli_query($conn,"SELECT count(*) FROM co1706assigment.playlist")or die(mysqli_error($conn));
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while (($row = mysqli_fetch_array($result))&&($row1=mysqli_fetch_array($playlistcounter))) // it takes all the results from sql query
{
    if($playlistcounter<2)
    {
        echo'

Track Name:
'.$row["name"].'

Album Name:
'.$row["album"].'

Sample

                            <audio controls>
                            <source src="'.$row["sample"].'" type="audio/mpeg">
                            </audio>

';
    }
}
echo'
 My Playlist
';
while ($row = mysqli_fetch_array($result)) // it takes all the results from sql query
{
   echo'

'.$row["name"].'

';
}
?>


问:
Max length of data returned from UIAutomation call
I'm working on a Windows 7 C++ program that will capture the text on a screen.  Microsoft's UIAutomation framework seems to be the best way of going about it.  I've got it pretty much working, except for one thing--when I use the framework's functions to get the text, it seems to only be returning the first million characters.  That might seem like a lot, but try doing a listing of every file on your hard drive, and it very quickly gets up in the multi-million-character range.  I've tried two different ways to get that text, and both ways return the same thing, and both are limited to the first million characters.

Here's a sample of the code:

```<code>IUIAutomationElement *element = findElement();

VARIANT v;
VariantInit(&v);

element->GetCurrentPropertyValue(UIA_LegacyIAccessibleValuePropertyId, &v);

BSTR tempString = V_BSTR(&v);
</code>```

Everything works as intended when the amount of text is less than a million characters long, but anything over that limit gets truncated.

I hypothesis that there might be two places where the problem occurs.  First, it's possible that a VARIANT can only hold a million characters, but that seems to not be correct, based on what I could find out about Microsoft's VARIANT implemented.  The second is that the GetCurrentPropertyValue() call only returns up to a million characters.  Which is rather bad because I don't see a way around it.

Note that I've also done this using IUIAutomationValuePattern and IUIAutomationTextRange, but it yields the same results.

Any thoughts?

答:
After instrumenting the code a bit more, I've realized that I'm incorrect in my assertion about VARIANT's ability to hold more than a million characters.  What's actually happening is that the BSTR I'm pulling from the VARIANT is holding all the data, so it's not truncating at all.  What's really happening is that the wstring that I'm creating from the BSTR (for ease of string manipulation) is what's doing the truncating.  Seems as if

```<code>wstring(tempString);
</code>```

will only give me a string of at most a million characters.  So, while I haven't fixed the problem, I have succeeded in narrowing down the culprit some more, and at least it's a tractable problem, since I'm not actually losing the data.

EDIT:  And I'm wrong about wstring's ability to handle ultra-long strings too.  If I just look at the length of the wstring, I see that it's copying the BSTR correctly.  Which is a relief.

The thing that is limited to one million characters is Visual Studio 2015's string inspection facility--anytime I'd look at the contents of the wstring, it would be no longer than one million characters.

So, thanks for this journey of self-discovery you've helped me with--nothing more to see here.  Move along.  Move along.

Body:
I'm working on a Windows 7 C++ program that will capture the text on a screen.  Microsoft's UIAutomation framework seems to be the best way of going about it.  I've got it pretty much working, except for one thing--when I use the framework's functions to get the text, it seems to only be returning the first million characters.  That might seem like a lot, but try doing a listing of every file on your hard drive, and it very quickly gets up in the multi-million-character range.  I've tried two different ways to get that text, and both ways return the same thing, and both are limited to the first million characters.

Here's a sample of the code:

IUIAutomationElement *element = findElement();

VARIANT v;
VariantInit(&v);

element->GetCurrentPropertyValue(UIA_LegacyIAccessibleValuePropertyId, &v);

BSTR tempString = V_BSTR(&v);

Everything works as intended when the amount of text is less than a million characters long, but anything over that limit gets truncated.

I hypothesis that there might be two places where the problem occurs.  First, it's possible that a VARIANT can only hold a million characters, but that seems to not be correct, based on what I could find out about Microsoft's VARIANT implemented.  The second is that the GetCurrentPropertyValue() call only returns up to a million characters.  Which is rather bad because I don't see a way around it.

Note that I've also done this using IUIAutomationValuePattern and IUIAutomationTextRange, but it yields the same results.

Any thoughts?

Body:
After instrumenting the code a bit more, I've realized that I'm incorrect in my assertion about VARIANT's ability to hold more than a million characters.  What's actually happening is that the BSTR I'm pulling from the VARIANT is holding all the data, so it's not truncating at all.  What's really happening is that the wstring that I'm creating from the BSTR (for ease of string manipulation) is what's doing the truncating.  Seems as if

wstring(tempString);

will only give me a string of at most a million characters.  So, while I haven't fixed the problem, I have succeeded in narrowing down the culprit some more, and at least it's a tractable problem, since I'm not actually losing the data.

EDIT:  And I'm wrong about wstring's ability to handle ultra-long strings too.  If I just look at the length of the wstring, I see that it's copying the BSTR correctly.  Which is a relief.

The thing that is limited to one million characters is Visual Studio 2015's string inspection facility--anytime I'd look at the contents of the wstring, it would be no longer than one million characters.

So, thanks for this journey of self-discovery you've helped me with--nothing more to see here.  Move along.  Move along.


问:
Javascript age calculator not working, it returns a string
I need a bit of help with this code. It returns a string instead of the required result and I'm a bit stuck.</p>

```<code>function calculateAge(name, birthYear) {
    this.name = name;
    this.birthYear = birthYear;
    this.result =  function(){
        var currentYear = new Date().getFullYear();
        return currentYear - birthYear;
    };
    document.write("Hi there " + this.name + " ." + "You are " + this.result + " old !" );
};

var John = new calculateAge("ion" , 1980);
John.result();
</code>```

答:
Call the function to get the desired result - this.result().

function calculateAge(name, birthYear) {

  this.name = name;
  this.birthYear = birthYear;
  this.result = function() {
    var currentYear = new Date().getFullYear();
    return currentYear - birthYear;
  };
  document.write("Hi there " + this.name + " ." + "You are " + this.result() + " old !");
};
var John = new calculateAge("ion", 1980);
John.result();```

Body:
I need a bit of help with this code. It returns a string instead of the required result and I'm a bit stuck.

function calculateAge(name, birthYear) {
    this.name = name;
    this.birthYear = birthYear;
    this.result =  function(){
        var currentYear = new Date().getFullYear();
        return currentYear - birthYear;
    };
    document.write("Hi there " + this.name + " ." + "You are " + this.result + " old !" );
};

var John = new calculateAge("ion" , 1980);
John.result();


问:
HTML, CSS, or JavaScript first? How should I write my code?
I have been learning web development for the past few months now, I have really been enjoying it a lot but I have started my own projects just to mess around and see what I really know.

With my most recent project I have been building my portfolio page, the way I currently write my code goes like this: I write all my HTML first so I have the layout of the page, after I have all of that is written, I then go into my CSS and style everything. Then I go and do JavaScript.

My question is this, is this an efficient way of writing code? Should I keep doing it this way? Or should I write some HTML, style it, go back and forth, then move onto JavaScript? Is there a more efficient way of how you write code?

答:
Subjective question however the way I was taught was develop for mobile first HTML and CSS. Once the layout for that is done then you can focus on the interaction using JavaScript and stuff like that.

However, I don't really use .html files anymore since I'm developing multiple pages I instead use .PHP because of the includes. However, if it was a single page then I would use HTML.

On the flip side however, I also got bored with CSS and realized I needed a faster way so I switched to a CSS processor like Sass which makes writing CSS a lot quicker and more efficient.


问:
How to send the requests in batches using Jmeter
I've a scenario where I need to send the requests in batches of user defined number (for example 1K,5K,10K etc) with a specified interval between each batch.

Assume Interval between batch is 30 Seconds, I've to send 'N' number of request per batch, for example 1K. Sending 1K request got finished within 10 Seconds, so for next 20 Seconds no request should go. Once the interval gets over another batch of 1K should be sent.

Input : Data is flowing from a CSV, for the 2nd batch it should ideally start from 1001.

Options tried : Constant Throughput Timer. With this I'm restricting the speed of the request, which I do not want to do.

Can someone help me with other option which i can try with?

答:
You also may use beanshell/JSR223 timer (after all your samples in a thread group) instead of sampler or post processor, as it's been proposed.
As well as pre-processor (before all your samples in a thread group) to set the start time variable - instead of sampler.

In such a timer, you're going to simply return the delay to be applied (like return (interval - (endTime - startTime)); )


问:
User Agent Stylesheet - css property for strong is disabled?

In my codepen I placed  tags within a paragraph, but I noticed no emphasis being displayed.  Chrome developer tools shows the user agent stylesheet for strong has a line through it.  What could possibly be disabling this setting as I do not override strong myself or change any font-weight within my code?

I am using chrome version 56.

```<code><p id="p10">offset() - Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. <strong>[returns: object]</strong>
</p>
</code>```

答:
Is it possible that you are setting the font-weight or calling font: inherit on the
 tag or possibly from the id?

As other answers have stated, you are probably overwriting this in your css reset file:
https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css

You could redeclare it as follows:

```<code>strong {
   font-weight: bold !important;
}
</code>```

Body:
In my codepen I placed  tags within a paragraph, but I noticed no emphasis being displayed.  Chrome developer tools shows the user agent stylesheet for strong has a line through it.  What could possibly be disabling this setting as I do not override strong myself or change any font-weight within my code?

I am using chrome version 56.

offset() - Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. [returns: object]

Body:
Is it possible that you are setting the font-weight or calling font: inherit on the <p> tag or possibly from the id?

As other answers have stated, you are probably overwriting this in your css reset file:
https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css

You could redeclare it as follows:

strong {
   font-weight: bold !important;
}


问:
Questions about writing a program in Java using Digital signature

Write two programs - one for Alice, another for Bob. Data exchange between them is achieved through a text file used as a communication channel.

I keep getting an error in Netbeans:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Signature.encode

Can anyone help steer me in the right direction? I can post the error message if needed; it shows Alice's keys and extended messsage but nothing about Bob.
I can also post the lab directions if needed as well.

```<code>import java.math.BigInteger;

class Signature {
    static class Keys {
        BigInteger n = new BigInteger("9617");
        BigInteger d = new BigInteger("3869");
        BigInteger e = new BigInteger("17");
    }

    public static void main(String[] args) {

        Keys keys = new Keys();
        String message = "What's up Bob";
        int blockSize = 4;

        Signature obj = new Signature();

        System.out.println("Alice's keys:");
        System.out.println("e: " + keys.e);
        System.out.println("d: " + keys.d);
        System.out.println("n: " + keys.n);
        while (message.length() % (blockSize / 2) != 0) {
            message += "-";
        }
        /
        System.out.println(
            "Alice's extended message:\n" +
            message);
        String encodedMsg = obj.encode(message);
        String signature = obj.dosignature(
            encodedMsg, keys.d, keys.n, blockSize);

        System.out.println(
            "Alice's digital signature\n" +
            signature);
        String signedMsg = message + "_" + signature;

        System.out.println(
            "Alice's signed message:\n" +
            signedMsg);
        String extractedMsgText =
            signedMsg.substring(
                0, signedMsg.indexOf('_'));

        System.out.println(
            "Bob's extracted message text:\n" +
            extractedMsgText);
        String extractedSignature =
            signedMsg.substring(
                signedMsg.indexOf('_') + 1);
        System.out.println(
            "Bob's extracted digital signature:\n" +
            extractedSignature);
        String decipheredSignature;
        decipheredSignature = obj.doRSA(extractedSignature, keys.e, keys.n, blockSize);

        String decodedSignature = obj.decode(
            decipheredSignature);
        System.out.println(
            "Bob's decoded digital signature:\n" +
            decodedSignature);
        if (extractedMsgText.equals(decodedSignature)) {
            System.out.println(
                "Bob's conclusion: Valid signature");
        } else {
            System.out.println(
                "Bob's conclusion: Invalid signature");
        }

    }

}
</code>```

答: Class Signature does not have an encode method.

Body:
Write two programs - one for Alice, another for Bob. Data exchange between them is achieved through a text file used as a communication channel.

I keep getting an error in Netbeans:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Signature.encode

Can anyone help steer me in the right direction? I can post the error message if needed; it shows Alice's keys and extended messsage but nothing about Bob.
I can also post the lab directions if needed as well.

import java.math.BigInteger;

class Signature {
    static class Keys {
        BigInteger n = new BigInteger("9617");
        BigInteger d = new BigInteger("3869");
        BigInteger e = new BigInteger("17");
    }

    public static void main(String[] args) {

        Keys keys = new Keys();
        String message = "What's up Bob";
        int blockSize = 4;

        Signature obj = new Signature();

        System.out.println("Alice's keys:");
        System.out.println("e: " + keys.e);
        System.out.println("d: " + keys.d);
        System.out.println("n: " + keys.n);
        while (message.length() % (blockSize / 2) != 0) {
            message += "-";
        }
        /
        System.out.println(
            "Alice's extended message:\n" +
            message);
        String encodedMsg = obj.encode(message);
        String signature = obj.dosignature(
            encodedMsg, keys.d, keys.n, blockSize);

        System.out.println(
            "Alice's digital signature\n" +
            signature);
        String signedMsg = message + "_" + signature;

        System.out.println(
            "Alice's signed message:\n" +
            signedMsg);
        String extractedMsgText =
            signedMsg.substring(
                0, signedMsg.indexOf('_'));

        System.out.println(
            "Bob's extracted message text:\n" +
            extractedMsgText);
        String extractedSignature =
            signedMsg.substring(
                signedMsg.indexOf('_') + 1);
        System.out.println(
            "Bob's extracted digital signature:\n" +
            extractedSignature);
        String decipheredSignature;
        decipheredSignature = obj.doRSA(extractedSignature, keys.e, keys.n, blockSize);

        String decodedSignature = obj.decode(
            decipheredSignature);
        System.out.println(
            "Bob's decoded digital signature:\n" +
            decodedSignature);
        if (extractedMsgText.equals(decodedSignature)) {
            System.out.println(
                "Bob's conclusion: Valid signature");
        } else {
            System.out.println(
                "Bob's conclusion: Invalid signature");
        }

    }

}


问:
Add methods to a model using entity framework
With entity framework, is it possible to add methods to an object class ?
For example, i have a CLIENT mapping and i would like to create a "getAgeFromBirhDate" method.</p>

答:
Yes. It's possible. Entity Framework generates Partial Classes.

That means you can create another file that contains another portion of the Partial Class definition (with your additional methods) and everything will work just fine.


问:
angular 2 observable json error
```<code>import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class CommentService{
private _url :string ="https://jsonplaceholder.typicode.com/posts"
   constructor(private _http:Http){}
  // method to fetch CommentS from a api service
 getComments(){

 return this._http.get(this._url)
        .map((response:Response)=> response.json())
        .catch(this._errorHandler);

  }

  _errorHandler(error:Response){
       console.error(error);
     return Observable.throw(error ||"Server Error");

 }

}
</code>```

the above code works great with this url https://jsonplaceholder.typicode.com/posts

but does not work with this url http://ergast.com/api/f1/2016/driverStandings.json

any ideas ...TIA

答:
To make the second one work you need to get the data using

```<code>return this._http.get(this._url)
        .map((response:Response)=> response.MRDATA.json())
        .catch(this._errorHandler);

  }
</code>```

Because in this working one the data is in array of objects type Meaning

The one which does not work is completely single object

Title: angular 2 observable json error

Body:
import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class CommentService{
private _url :string ="https://jsonplaceholder.typicode.com/posts"
   constructor(private _http:Http){}
  // method to fetch CommentS from a api service
 getComments(){

 return this._http.get(this._url)
        .map((response:Response)=> response.json())
        .catch(this._errorHandler);

  }

  _errorHandler(error:Response){
       console.error(error);
     return Observable.throw(error ||"Server Error");

 }

}

the above code works great with this url https://jsonplaceholder.typicode.com/posts

but does not work with this url http://ergast.com/api/f1/2016/driverStandings.json

any ideas ...TIA

Body:
To make the second one work you need to get the data using

return this._http.get(this._url)
        .map((response:Response)=> response.MRDATA.json())
        .catch(this._errorHandler);

  }

Because in this working one the data is in array of objects type Meaning

The one which does not work is completely single object


问:
Calling void function before main()
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

```<code>#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}
</code>```

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

答:
An answer to this question brought __attribute__((constructor)) to my attention, however, for reasons I don't fully understand, I observed a SIGSEGV when using that if the void function used std::cout (printf did not cause the SIGSEGV).

I posted a version of this question earlier (but stupidly deleted it). An answerer at that time pointed me to this excellent article which discusses the situation and solution:

http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html

Excerpt of the solution (modified slightly to pass compilation) is here:

```<code>#include <cstdio>
#include <cstdlib>

void preinit(int argc, char * * argv, char * * envp) {
  printf("%s\n", __FUNCTION__);
}
void init(int argc, char * * argv, char * * envp) {
  printf("%s\n", __FUNCTION__);
}

void fini() {
  printf("%s\n", __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof (init) * __init = init;
__attribute__((section(".preinit_array"))) typeof (preinit) * __preinit = preinit;
__attribute__((section(".fini_array"))) typeof (fini) * __fini = fini;

void __attribute__((constructor)) constructor() {
  printf("%s\n", __FUNCTION__);
}

void __attribute__((destructor)) destructor() {
  printf("%s\n", __FUNCTION__);
}

void my_atexit() {
  printf("%s\n", __FUNCTION__);
}

void my_atexit2() {
  printf("%s\n", __FUNCTION__);
}

int main() {
  atexit(my_atexit);
  atexit(my_atexit2);
}
</code>```

(Apologies to the original answerer that I deleted my original post and can't give due credit.)

Title: Calling void function before main()

Body:
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

Body:
An answer to this question brought __attribute__((constructor)) to my attention, however, for reasons I don't fully understand, I observed a SIGSEGV when using that if the void function used std::cout (printf did not cause the SIGSEGV).

I posted a version of this question earlier (but stupidly deleted it). An answerer at that time pointed me to this excellent article which discusses the situation and solution:

http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html

Excerpt of the solution (modified slightly to pass compilation) is here:

#include <cstdio>
#include <cstdlib>

void preinit(int argc, char * * argv, char * * envp) {
  printf("%s\n", __FUNCTION__);
}
void init(int argc, char * * argv, char * * envp) {
  printf("%s\n", __FUNCTION__);
}

void fini() {
  printf("%s\n", __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof (init) * __init = init;
__attribute__((section(".preinit_array"))) typeof (preinit) * __preinit = preinit;
__attribute__((section(".fini_array"))) typeof (fini) * __fini = fini;

void __attribute__((constructor)) constructor() {
  printf("%s\n", __FUNCTION__);
}

void __attribute__((destructor)) destructor() {
  printf("%s\n", __FUNCTION__);
}

void my_atexit() {
  printf("%s\n", __FUNCTION__);
}

void my_atexit2() {
  printf("%s\n", __FUNCTION__);
}

int main() {
  atexit(my_atexit);
  atexit(my_atexit2);
}

(Apologies to the original answerer that I deleted my original post and can't give due credit.)


问:
What does $("something") mean in Java?
I was looking into some tutorial and stumbled on this code:

```<code>public void run(String... args) throws Exception {
    eventBus.on($("quotes"), receiver);
    publisher.publishQuotes(NUMBER_OF_QUOTES);
}
</code>```

This is the first time I see $("quotes") in Java. I'd appreciate someone explaining to me what's going on there.

Here's the source:

https://github.com/spring-guides/deprecate-gs-messaging-reactor/blob/master/complete/src/main/java/hello/Application.java#L53

Update:

This is not a question about $ as Java variable name. I know that it's a valid variable name. However, the format of $("something") looks JQuery-like; hence threw me off thinking that it's a special directive or something.

答:
You have an import static reactor.bus.selector.Selectors.$;

From the documentation that is a short-hand alias for object(T) which in turn creates a Selector based on the given object.

Title: What does $("something") mean in Java?

Body:
I was looking into some tutorial and stumbled on this code:

public void run(String... args) throws Exception {
    eventBus.on($("quotes"), receiver);
    publisher.publishQuotes(NUMBER_OF_QUOTES);
}

This is the first time I see $("quotes") in Java. I'd appreciate someone explaining to me what's going on there.

Here's the source:

https://github.com/spring-guides/deprecate-gs-messaging-reactor/blob/master/complete/src/main/java/hello/Application.java#L53

Update:

This is not a question about $ as Java variable name. I know that it's a valid variable name. However, the format of $("something") looks JQuery-like; hence threw me off thinking that it's a special directive or something.


问:
How does doctrine:build-schema create config/doctrine/schema.yml?
I'm having a really tough problem and, in an effort to solve it, I want to find the code that's generating config/doctrine/schema.yml. I'm having a hard time tracking it down. Would anyone happen to know where it is?</p>

答: I ended up solving the problem a different way, so this question is irrelevant.</p>


问:
Python does not find installed modules
Python3.5 does not locate installed modules when invoked in virtual env.

Create virtual env: python3.5 -m venv autogit/venv && cd autogit

source venv/bin/activate

which python == ...autogit/venv/bin/python
Weird, would expect python3.5

Add my python source code to /autogit and pip freeze>requirements.txt

pip install -r requirements.txt

ls venv/lib/python3.5/site-packages shows request-0-0-0-py3.5.egg-info and some other stuff

Since dependencies are installed under python3.5 and which python revealed python rather than python3.5, lets invoke the python3.5binary explicitly.... venv/bin/python3.5 autogit.py
Get ImportError: No module named 'request

???  Where could python be looking for packages if not in my virtual env?

UPDATE The questions above remain unanswered; here are things I noticed since then and the workaround I used:

pip install produced a file request-0-0-0-py3.5.egg-info. It did NOT produce an actual request directory with the source code or binaries for this module.  Also why is it version 0 0 0 that is fishy

After some googling I noticed the module I wanted seemed to be named requests not request which is what was in my source. I changed it requests, pip install, and everything works. It was hard to see that there was a mistake because pip installing request did not fail

答:
Have you got other Python versions installed? That might be the problem.

Try using pip3 instead of pip

Title: Python does not find installed modules


问:
React - does a child component re-mount each time the parent component renders?
In this very basic example I am including the component Bar inside the render function of component Foo. I am observing that the componentDidMount method for Bar is firing each time Foo re-renders - is this the correct behaviour?

```<code>import Bar from './Bar.jsx';

export default class Foo extends Component {
    render() {
        return (
            <Bar />
        );
    }
}
</code>```

Note: I have asked this question to sanity check the expected behaviour, in order to track down a bug.

答:
Need to be careful when using if if/else logic in the render function. In the example below, the Bar component will unmount if the loading prop value changes to true:

```<code>import Bar from './Bar.jsx';

export default class Foo extends Component {
    render() {
        if(this.props.loading){
            return (
                <div>Loading...</div>
            );
        }
        else{
            return (
                <Bar />
            );
        }
    }
}
</code>```

Body:
In this very basic example I am including the component Bar inside the render function of component Foo. I am observing that the componentDidMount method for Bar is firing each time Foo re-renders - is this the correct behaviour?

import Bar from './Bar.jsx';

export default class Foo extends Component {
    render() {
        return (
            <Bar />
        );
    }
}

Note: I have asked this question to sanity check the expected behaviour, in order to track down a bug.

Body:
Need to be careful when using if if/else logic in the render function. In the example below, the Bar component will unmount if the loading prop value changes to true:

import Bar from './Bar.jsx';

export default class Foo extends Component {
    render() {
        if(this.props.loading){
            return (
                <div>Loading...</div>
            );
        }
        else{
            return (
                <Bar />
            );
        }
    }
}