问:
Debugging RegularExpressionValidator control
I have an asp:regularexpressionvalidator with the following expression to validate a file upload.

```<code>\.{1}x?html?$
</code>```

Expresso shows me that it works. The simple html test page below shows that it works, but in my application, loading an html file in the file input always triggers the validator?!?

Anyone have any ideas or tips on debugging the javascript of this control?

Thanks,
Sam

the control:

```<code><asp:RegularExpressionValidator ID="validRegexHtmlOnly" runat="server" ControlToValidate="fileImportHTML"
        ValidationExpression="\.{1}x?html?" ErrorMessage="The file must be an HTML document (.html, .htm, .xhtml)" Display="Dynamic" />
</code>```

simple test page:

```<code><html>
<head>
<script type="text/javascript">
function validate(){
 var txt = document.getElementById("txtInput").value;
 alert(/\.{1}x?html?$/.test(txt));
}
</script>
</head>
<body>
<input type="file" id="txtInput" />
<input type="button" onclick="validate()" value="click me" />
</body>
</html>
</code>```

答:
I believe the regex in a RegularExpressionValidator is supposed to match the whole string, not just the end (or the beginning, or whatever).  Try changing your regex to

```<code>.*\.x?html?
</code>```

On a side note, the {1} wasn't doing anything useful, so I removed it.  It's not necessary to tell a regex to match one of something; that's the default behavior.  And {1} won't stop it from matching more than one of the thing it's attached to, either.  All it does is clutter up your regex.

Body:
I have an asp:regularexpressionvalidator with the following expression to validate a file upload.

\.{1}x?html?$

Expresso shows me that it works. The simple html test page below shows that it works, but in my application, loading an html file in the file input always triggers the validator?!?

Anyone have any ideas or tips on debugging the javascript of this control?

Thanks,
Sam

the control:

<asp:RegularExpressionValidator ID="validRegexHtmlOnly" runat="server" ControlToValidate="fileImportHTML"
        ValidationExpression="\.{1}x?html?" ErrorMessage="The file must be an HTML document (.html, .htm, .xhtml)" Display="Dynamic" />

simple test page:

<input type="file" id="txtInput" />
<input type="button" onclick="validate()" value="click me" />

Body:
I believe the regex in a RegularExpressionValidator is supposed to match the whole string, not just the end (or the beginning, or whatever).  Try changing your regex to

.*\.x?html?

On a side note, the {1} wasn't doing anything useful, so I removed it.  It's not necessary to tell a regex to match one of something; that's the default behavior.  And {1} won't stop it from matching more than one of the thing it's attached to, either.  All it does is clutter up your regex.


来源: stackexchange

问:
Adding values of strings containing a specific string in Javascript
I have an object called guild, that has the following array:

```<code>members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.
</code>```

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

```<code> var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }
</code>```

答:
Why are you reinitializing memberCoins in loop?

Just change this line

```<code>var memberCoins = memberCoins + Object.values(guild.members[i])[j];
</code>```

to

```<code>memberCoins += Object.values(guild.members[i])[j];
</code>```

Complete Code

```<code>var guildMembers = [];
    var memberCoins = 0;
for (i = 0; i < guild.members.length; i++) {
    for (j = 0; j < Object.keys(guild.members[i]).length; j++) {
        console.log(Object.keys(guild.members[i]));

        if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
            memberCoins += Object.values(guild.members[i])[j];
        }
    }
var member = {
    uuid: guild.members[i].uuid,
        rank: guild.members[i].rank,
    joined: guild.members[i].joined,
    coins: memberCoins
};
guildMembers.push(member);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an object called guild, that has the following array:

members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

 var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }

Body:
Why are you reinitializing memberCoins in loop?

Just change this line

var memberCoins = memberCoins + Object.values(guild.members[i])[j];

to

memberCoins += Object.values(guild.members[i])[j];

Complete Code

var guildMembers = [];
    var memberCoins = 0;
for (i = 0; i < guild.members.length; i++) {
    for (j = 0; j < Object.keys(guild.members[i]).length; j++) {
        console.log(Object.keys(guild.members[i]));

        if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
            memberCoins += Object.values(guild.members[i])[j];
        }
    }
var member = {
    uuid: guild.members[i].uuid,
        rank: guild.members[i].rank,
    joined: guild.members[i].joined,
    coins: memberCoins
};
guildMembers.push(member);
}


问:
spring cloud sleuth: manually triggered async services
I have a service A that creates an email and sends it to a customer. The customer will receive the email and will, eventually, click on the link in the body to trigger service B.

How can I correlate two different and completely isolated services that are part of the same business process with sleuth?

Should I leave the span "opened" or is there a way to "embed" the trace id somehow on the email?

答:
You can use asynchronous communication (http://cloud.spring.io/spring-cloud-sleuth/spring-cloud-sleuth.html#_asynchronous_communication) for example via a trace representation of the ExecutorService called the TraceableExecutorService (http://cloud.spring.io/spring-cloud-sleuth/spring-cloud-sleuth.html#_executor_executorservice_and_scheduledexecutorservice). You emit a completable future that will process the data in a separate thread. At some point you block and then you can retrieve the data. The trace representation of the ExecutorService will take care of passing of tracing data.

UPDATE:
If however, these are completely two separate processes then I'd close the span and create a completely separate span the moment someone clicks on the link. You should never leave spans explicitly open. What will bind the 2 processes will be the trace id. Zipkin doesn't yet support these long living tasks in the best possible way from the point of view of the UI but there's some work in progress going on to improve it (via so-called linked spans)


问:
MySQL audit table: hibernate-envers vs Triggers
I have a user table which I want to audit. I'm using hibernate-envers for the same. This is what my user class looks like:

```<code>@Audited
@Entity
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "phone_number")
    private String phoneNumber;

    @Column(name = "profile_pic")
    private String profilePic;
}
</code>```

I'm not sure about hibernate-enver's performance. Before hibernate-envers, I was using triggers to keep an audit trail. Should I continue with envers or switch back to triggers?

PS: I want a comparison based on performance. Cause using envers literally doesn't require any extra effort, so effort/development-time wise it's the obvious choice.

答:
If it fits the need and does the job, then continue.  Later on if you find it isn't performing up to some standard, you can always change it or report the performance concern and I can look at it.

To your question, no such benchmark exists.  I'd even be weary of such a benchmark if it did because it is most likely misleading anyway.

Typically, developers design audit triggers like you decribed to  be very simple.  In other words, they act as a row-copier and nothing else.  During an insert, update, or delete, they simply copy a snapshot of the data from the table into another.  Done.

Obviously Envers takes this farther by supporting the notion of audited relationships between entities.  It also allows you to provide it attributes about the environment during a change so you can track things like who changed what, why it was changed, etc.

The biggest advantage of Envers is in fact the effort required to get such a framework working.  As you've indicated, its effortless and even in the most complex of entity relationships, its super simple to manage those.

I'm sure there are use cases where a database trigger will perform equally or better than any client software-based solution.  In that case you have no network latency and the trigger can also use proprietary database options to improve performance where-as a framework will use more cross-platform database agnostic features.

Lastly, your entity you've shown seems to be super simple.  There would literally be little to no overhead for Envers to handle that entity.  There are no relationships and thus it would be a simple insert for each User row change and one for the revision entity.

There are implementations of Envers that use far more complex entity object graphs with inheritance and complex associations just fine.

Body:
I have a user table which I want to audit. I'm using hibernate-envers for the same. This is what my user class looks like:

@Audited
@Entity
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "phone_number")
    private String phoneNumber;

    @Column(name = "profile_pic")
    private String profilePic;
}

I'm not sure about hibernate-enver's performance. Before hibernate-envers, I was using triggers to keep an audit trail. Should I continue with envers or switch back to triggers?

PS: I want a comparison based on performance. Cause using envers literally doesn't require any extra effort, so effort/development-time wise it's the obvious choice.


问:
How do i press only the "/" - key on a german keyboard?
i searched for the shortcuts to comment a line in Android Studio.

The answer: Press the keys "Ctrl + /".

My problem:
I tried this combination and ... nothing happened.

So now i assume that since i'm using a german keyboard and in this layout the "/" is mapped to the shift-option of the "7"-key it is not possible to press only the keys ctrl + /.

I tried to press ctrl + shift + 7 to enter "Ctrl + /", but this places a bookmark at that line which is named "7".

Does anyone know how to type in "Ctrl + /" while using a german layout (without changing the shortcut-mapping)?

Thanks for your time!

答: With the windows key + space bar you can change the Keyboard layout. </p>


问:
Samsung Galaxy S8 full screen mode
Latest Samsung's smartphone has interesting feature called full screen (or in marketing terms infinity display). In this mode app covers also part of display where home/back buttons are. Usual apps don't cover this area, leaving it black. But Samsung's native ones cover this area.

Question: how to achieve this effect? I mean what kind of manifest declaration or programmatic call (possibly Samsung's legacy API) should I use?

答:
To enable new Samsung Galaxy S8 and LG G6 full screen support add to the AndroidManifest.xml under the <application> element:

```<code><meta-data android:name="android.max_aspect" android:value="2.1" />
</code>```

Where value of 2.1 is aspect ratio 18.5:9 (By default your App defaults to maximum ratio for 16:9 - 1.86). More info in: Android Blog.

Alternatively, you can set the following attribute for Application or Activity:

```<code>android:resizeableActivity="true"
</code>```

Because the documentations states (link):

You do not need to set a maximum aspect ratio if an activity's
  android:resizeableActivity attribute is set to true. If your app
  targets API level 24 or higher, this attribute defaults to true.

Title: Samsung Galaxy S8 full screen mode

Body:
To enable new Samsung Galaxy S8 and LG G6 full screen support add to the AndroidManifest.xml under the <application> element:

<meta-data android:name="android.max_aspect" android:value="2.1" />

Where value of 2.1 is aspect ratio 18.5:9 (By default your App defaults to maximum ratio for 16:9 - 1.86). More info in: Android Blog.

Alternatively, you can set the following attribute for Application or Activity:

android:resizeableActivity="true"

Because the documentations states (link):

You do not need to set a maximum aspect ratio if an activity's
  android:resizeableActivity attribute is set to true. If your app
  targets API level 24 or higher, this attribute defaults to true.


问:
JMeter 400 Error File Upload
I'm trying to use JMeter to test a restful endpoint for uploading files, but I'm getting a 400 error. The one thing that jumps out at me is the boundary value; it's not the same I provided as the one shown in the request. I'm able to use the endpoint in the browser without issue, and I've replicated the headers revealed in the developer tools in FF.

Here is the relevant info from JMeter:

Result Tab:

Thread Name: Asdf - Load Test 1-1

Sample Start: 2017-06-05 08:47:46 EDT

Load time: 159

Connect Time: 28

Latency: 159

Size in bytes: 438

Sent bytes:821003

Headers size in bytes: 438

Body size in bytes: 0

Sample Count: 1

Error Count: 1

Data type ("text"|"bin"|""):

Response code: 400

Response message: Bad Request

Response headers:

HTTP/1.1 400 Bad Request

Date: Mon, 05 Jun 2017 12:47:46 GMT

Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Pragma: no-cache

Expires: 0

Strict-Transport-Security: max-age=31536000 ; includeSubDomains

X-XSS-Protection: 1; mode=block

X-Frame-Options: DENY

X-Content-Type-Options: nosniff

Cache-Control: no-cache, must-revalidate

Content-Length: 0

Connection: close

HTTPSampleResult fields:

ContentType:

DataEncoding: null

Request Tab:

POST https://localhost/my/rest/endpoint

POST data:

--9amm365-gMmimP70lvs9jIvlIxOfkocUN

Content-Disposition: form-data; name="parseable"; filename="asdf.docx"

Content-Type: application/vnd.openxmlformats-

officedocument.wordprocessingml.document

Content-Transfer-Encoding: binary

--9amm365-gMmimP70lvs9jIvlIxOfkocUN--

[no cookies]

Request Headers:

Connection: keep-alive

Content-Type: multipart/form-data; boundary=--Uc_2uLvcVgc7SqvzIJxR3encUKw-
f7w9

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.5

Accept: application/json, text/plain, /

X-Request-OnBehalfOf: some-user-uuid

X-Requested-With: XMLHttpRequest

Content-Length: 820532

Host: localhost

User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)

Response Data Tab is blank.

Server side implementation:

```<code>@POST
@Override
@EnhancedDetail
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("my/rest/endpoint")
public Response uploadProduct(@PathParam("id") final String id, MultiPart multipart) throws IOException {
    return processMultiFileUpload(id, multipart, MultiPartUploadType.DRAFT, false);
}
</code>```

答:
If you are building your request manually like it is described in Testing REST API File Uploads in JMeter article - make sure you have Use multipart/form-data for POST box of the HTTP Request sampler is not checked.

And vice versa, if you tick this box, you won't need to override the Content-Type header

I believe the easiest way would be just recording your file upload event using HTTP(S) Test Script Recorder (just make sure your asdf.docx file is copied to the "bin" folder of your JMeter installation)

Title: JMeter 400 Error File Upload

Body:
I'm trying to use JMeter to test a restful endpoint for uploading files, but I'm getting a 400 error. The one thing that jumps out at me is the boundary value; it's not the same I provided as the one shown in the request. I'm able to use the endpoint in the browser without issue, and I've replicated the headers revealed in the developer tools in FF.

Here is the relevant info from JMeter:

Result Tab:

Thread Name: Asdf - Load Test 1-1

Sample Start: 2017-06-05 08:47:46 EDT

Load time: 159

Connect Time: 28

Latency: 159

Size in bytes: 438

Sent bytes:821003

Headers size in bytes: 438

Body size in bytes: 0

Sample Count: 1

Error Count: 1

Data type ("text"|"bin"|""):

Response code: 400

Response message: Bad Request

Response headers:

HTTP/1.1 400 Bad Request

Date: Mon, 05 Jun 2017 12:47:46 GMT

Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Pragma: no-cache

Expires: 0

Strict-Transport-Security: max-age=31536000 ; includeSubDomains

X-XSS-Protection: 1; mode=block

X-Frame-Options: DENY

X-Content-Type-Options: nosniff

Cache-Control: no-cache, must-revalidate

Content-Length: 0

Connection: close

HTTPSampleResult fields:

ContentType:

DataEncoding: null

Request Tab:

POST https://localhost/my/rest/endpoint

POST data:

--9amm365-gMmimP70lvs9jIvlIxOfkocUN

Content-Disposition: form-data; name="parseable"; filename="asdf.docx"

Content-Type: application/vnd.openxmlformats-

officedocument.wordprocessingml.document

Content-Transfer-Encoding: binary

--9amm365-gMmimP70lvs9jIvlIxOfkocUN--

[no cookies]

Request Headers:

Connection: keep-alive

Content-Type: multipart/form-data; boundary=--Uc_2uLvcVgc7SqvzIJxR3encUKw-
f7w9

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.5

Accept: application/json, text/plain, /

X-Request-OnBehalfOf: some-user-uuid

X-Requested-With: XMLHttpRequest

Content-Length: 820532

Host: localhost

User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)

Response Data Tab is blank.

Server side implementation:

@POST
@Override
@EnhancedDetail
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("my/rest/endpoint")
public Response uploadProduct(@PathParam("id") final String id, MultiPart multipart) throws IOException {
    return processMultiFileUpload(id, multipart, MultiPartUploadType.DRAFT, false);
}


问:
How to send an email to multiple recipients in Spring
The email gets sents only to the last email address in the String[] to array. I'm intending to send to all email addresses added to the array. How can I make that work?

```<code>public void sendMail(String from, String[] to, String subject, String msg, List attachments) throws MessagingException {

    // Creating message
    sender.setHost("smtp.gmail.com");
    MimeMessage mimeMsg = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "425");

    Session session = Session.getDefaultInstance(props, null);

    helper.setFrom(from);

    helper.setTo(to);

    helper.setSubject(subject);
    helper.setText(msg + "<html><body><h1>hi welcome</h1><body></html", true);

    Iterator it = attachments.iterator();

    while (it.hasNext()) {
        FileSystemResource file = new FileSystemResource(new File((String) it.next()));
        helper.addAttachment(file.getFilename(), file);
    }

    // Sending message
    sender.send(mimeMsg);
}
</code>```

答:
The better approach is to create an array containing the address of multiple recipients.</p>

```<code>    MimeMessageHelper helper = new MimeMessageHelper( message, true );
    helper.setTo( String[] to );
</code>```

Body:
The email gets sents only to the last email address in the String[] to array. I'm intending to send to all email addresses added to the array. How can I make that work?

public void sendMail(String from, String[] to, String subject, String msg, List attachments) throws MessagingException {

    // Creating message
    sender.setHost("smtp.gmail.com");
    MimeMessage mimeMsg = sender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "425");

    Session session = Session.getDefaultInstance(props, null);

    helper.setFrom(from);

    helper.setTo(to);

    helper.setSubject(subject);
    helper.setText(msg + "
hi welcome
</html", true);

    Iterator it = attachments.iterator();

    while (it.hasNext()) {
        FileSystemResource file = new FileSystemResource(new File((String) it.next()));
        helper.addAttachment(file.getFilename(), file);
    }

    // Sending message
    sender.send(mimeMsg);
}

Body:
The better approach is to create an array containing the address of multiple recipients.

    MimeMessageHelper helper = new MimeMessageHelper( message, true );
    helper.setTo( String[] to );


问:
Flowpaper Zine, How to show pdf in single-page mode instead of two-page mode, by default?
When I open a document in Zine PHP server side, it opens in two-page mode.
I have to click on menu bar in order to switch to single-page mode.
Is there anyway to open the PDF document in single-page mode by default.</p>

答:
Set the following parameter to force single page mode:

InitViewMode : 'Portrait',


问:
Conditional prepared statements PHP mysqli, reduce
it works but I don't feel like it's the best solution for my problem.
What I want my code to do is to check if the location = 1 and send the messages for all of the locations.

```<code>function getCurrentMessage($location){
    $conn = Connection::getConnection();

    if($location == 1) {
        $query = "SELECT first_name, last_name, description, title, message ,font_size , effective_date
                FROM tbl_messages
                JOIN tbl_authors ON tbl_authors.id_author = tbl_messages.id_author
                JOIN tbl_locations ON tbl_messages.id_location = tbl_locations.id_location
                AND effective_date <= CURDATE()
                ORDER BY effective_date desc
                LIMIT 2;";

        $result = array();

        if ($stmt = $conn->prepare($query)) {
            $stmt->bind_result($first_name, $last_name, $location, $title, $message, $size, $date);
            $stmt->execute();

            while ($stmt->fetch()) {
                $message = new Message($first_name, $last_name, $location, $title, $message, $size, $date);
                array_push($result, $message);
            }
        }
    }
    else{
        $query = "SELECT first_name, last_name, description, title, message ,font_size , effective_date
                FROM tbl_messages
                JOIN tbl_authors ON tbl_authors.id_author = tbl_messages.id_author
                JOIN tbl_locations ON tbl_messages.id_location = tbl_locations.id_location
                WHERE tbl_messages.id_location = ?
                AND effective_date <= CURDATE()
                ORDER BY effective_date desc
                LIMIT 2;";

        $result = array();

        if ($stmt = $conn->prepare($query)) {
            $stmt->bind_result($first_name, $last_name, $location, $title, $message, $size, $date);
            $stmt->bind_param('i', $location);
            $stmt->execute();

            while ($stmt->fetch()) {
                $m = new Message($first_name, $last_name, $location, $title, $message, $size, $date);
                array_push($result, $m);
            }
        }
    }

    return $result;
}
</code>```

Maybe I could put some logic in the SQL statement.
If you have any insight please help.

答:
I realize now that this question should have been posted in code review Code review
,
but after learning more about MYSQL I figured a way to clean up the code so here is my answer using Control Flow Functions.

If you have any other idea to further clean up the code please tell me.

```<code>$conn = getConnection();
$query = "SELECT first_name, last_name, description, title, message ,font_size , DATE_FORMAT(effective_date,'%h:%i %p %m-%d-%Y')
          FROM tbl_messages
          JOIN tbl_authors ON tbl_authors.id_author = tbl_messages.id_author
          JOIN tbl_locations ON tbl_messages.id_location = tbl_locations.id_location
          WHERE tbl_messages.id_location = IF(? = 1,tbl_messages.id_location,?)
          AND effective_date <= NOW()
          ORDER BY effective_date DESC
          LIMIT 1
          ";

if (!$stmt = $conn->prepare($query)) {
    return false;
}

$stmt->bind_param('ii', $location,$location);

$result = array();

$stmt->bind_result($first_name, $last_name, $location, $title, $message, $size, $date);
$stmt->execute();

while ($stmt->fetch()) {
    $m = new Message($first_name, $last_name, $location, $title, $message, $size, $date);
    array_push($result, $m);
}

return $result;
</code>```

Body:
it works but I don't feel like it's the best solution for my problem.
What I want my code to do is to check if the location = 1 and send the messages for all of the locations.

function getCurrentMessage($location){
    $conn = Connection::getConnection();

    if($location == 1) {
        $query = "SELECT first_name, last_name, description, title, message ,font_size , effective_date
                FROM tbl_messages
                JOIN tbl_authors ON tbl_authors.id_author = tbl_messages.id_author
                JOIN tbl_locations ON tbl_messages.id_location = tbl_locations.id_location
                AND effective_date <= CURDATE()
                ORDER BY effective_date desc
                LIMIT 2;";

        $result = array();

        if ($stmt = $conn->prepare($query)) {
            $stmt->bind_result($first_name, $last_name, $location, $title, $message, $size, $date);
            $stmt->execute();

            while ($stmt->fetch()) {
                $message = new Message($first_name, $last_name, $location, $title, $message, $size, $date);
                array_push($result, $message);
            }
        }
    }
    else{
        $query = "SELECT first_name, last_name, description, title, message ,font_size , effective_date
                FROM tbl_messages
                JOIN tbl_authors ON tbl_authors.id_author = tbl_messages.id_author
                JOIN tbl_locations ON tbl_messages.id_location = tbl_locations.id_location
                WHERE tbl_messages.id_location = ?
                AND effective_date <= CURDATE()
                ORDER BY effective_date desc
                LIMIT 2;";

        $result = array();

        if ($stmt = $conn->prepare($query)) {
            $stmt->bind_result($first_name, $last_name, $location, $title, $message, $size, $date);
            $stmt->bind_param('i', $location);
            $stmt->execute();

            while ($stmt->fetch()) {
                $m = new Message($first_name, $last_name, $location, $title, $message, $size, $date);
                array_push($result, $m);
            }
        }
    }

    return $result;
}

Maybe I could put some logic in the SQL statement.
If you have any insight please help.

Body:
I realize now that this question should have been posted in code review Code review
,
but after learning more about MYSQL I figured a way to clean up the code so here is my answer using Control Flow Functions.

If you have any other idea to further clean up the code please tell me.

$conn = getConnection();
$query = "SELECT first_name, last_name, description, title, message ,font_size , DATE_FORMAT(effective_date,'%h:%i %p %m-%d-%Y')
          FROM tbl_messages
          JOIN tbl_authors ON tbl_authors.id_author = tbl_messages.id_author
          JOIN tbl_locations ON tbl_messages.id_location = tbl_locations.id_location
          WHERE tbl_messages.id_location = IF(? = 1,tbl_messages.id_location,?)
          AND effective_date <= NOW()
          ORDER BY effective_date DESC
          LIMIT 1
          ";

if (!$stmt = $conn->prepare($query)) {
    return false;
}

$stmt->bind_param('ii', $location,$location);

$result = array();

$stmt->bind_result($first_name, $last_name, $location, $title, $message, $size, $date);
$stmt->execute();

while ($stmt->fetch()) {
    $m = new Message($first_name, $last_name, $location, $title, $message, $size, $date);
    array_push($result, $m);
}

return $result;


问:
Strange behaviour with num_rows()

EDIT

For heaven's sake, this is not a duplicate. Do not close it as such. I'm not inquiring about what the error means. I'm more interested in knowing why this is giving me an error in this case while it works fine when used at other places.

For a query such as:

```<code>$this->db->select('user_id');
$this->db->from("members");
$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)));
$query = $this->db->get();
if($query->num_rows() == 1)
{
   // some logic goes here
}
</code>```

I'm getting the following error.

Call to a member function num_rows() on boolean

If I use $this->db->last_query(), I'm getting the following result:

```<code>SELECT `user_id`
FROM `members`
WHERE `username` = 'adg'
AND `password` = '3a1c21a559ed42d6ce17c0b8205b6bda2465c2a8'
</code>```

The query is 100% correct and when run in MySql console, returns an empty set (0 rows) which is fine. But why then is it returning boolean when used in the code.

By the way, I'm using num_rows() on the $query object in various other places and that seem to be working fine.

CI version is 3.1.3

Update

var_dump($query) is printing out bool(false)

答:
It's not well documented but when a query fails a boolean might be returned instead of a CI_DB_result object. That is what is happening to you. My first guess as to why it happens in your example is that some piece of data is being improperly escaped - most likely in the where statement. Try this.

$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)), NULL, FALSE);

And see if that helps.

I have, on occasion, when queries are complicated, had to resort to the following check on my results like this.

```<code>if($query instanceof CI_DB_result && $query->num_rows() == 1) {...
</code>```

just to make sure I'm not trying to "Call to a member function num_rows() on boolean"

Title: Strange behaviour with num_rows()

Body:
EDIT

For heaven's sake, this is not a duplicate. Do not close it as such. I'm not inquiring about what the error means. I'm more interested in knowing why this is giving me an error in this case while it works fine when used at other places.

For a query such as:

$this->db->select('user_id');
$this->db->from("members");
$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)));
$query = $this->db->get();
if($query->num_rows() == 1)
{
   // some logic goes here
}

I'm getting the following error.

Call to a member function num_rows() on boolean

If I use $this->db->last_query(), I'm getting the following result:

SELECT `user_id`
FROM `members`
WHERE `username` = 'adg'
AND `password` = '3a1c21a559ed42d6ce17c0b8205b6bda2465c2a8'

The query is 100% correct and when run in MySql console, returns an empty set (0 rows) which is fine. But why then is it returning boolean when used in the code.

By the way, I'm using num_rows() on the $query object in various other places and that seem to be working fine.

CI version is 3.1.3

Update

var_dump($query) is printing out bool(false)

Body:
It's not well documented but when a query fails a boolean might be returned instead of a CI_DB_result object. That is what is happening to you. My first guess as to why it happens in your example is that some piece of data is being improperly escaped - most likely in the where statement. Try this.

$this->db->where(array("username"=>$post->un, "password"=>sha1($post->pw)), NULL, FALSE);

And see if that helps.

I have, on occasion, when queries are complicated, had to resort to the following check on my results like this.

if($query instanceof CI_DB_result && $query->num_rows() == 1) {...

just to make sure I'm not trying to "Call to a member function num_rows() on boolean"


问:
How to replace any text between html tags
i have text between html tags. For example:

```<code><td>vip</td>
</code>```

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

答:
You can try this:

```<code>sed -i -e 's/\(<td>\).*\(<\/td>\)/<td>TEXT_TO_REPLACE_BY<\/td>/g' test.txt
</code>```

Note that it will only work for the  tags. It will replace everything between tags  (actually with them together and put the tags back) with TEXT_TO_REPLACE_BY.

Body:
i have text between html tags. For example:

vip

I will have any text between tags
How can i cut any text from these tags and put any text between these tags.
I need to do it via bash/shell.
How can i do this ?
First of all, i tried to get this text, but without success
sed -n "//,/<\/td>/p" test.txt. But in a result i have
vip	. but according to documentation, i should get only vip

Body:
You can try this:

sed -i -e 's/\(<td>\).*\(<\/td>\)/<td>TEXT_TO_REPLACE_BY<\/td>/g' test.txt

Note that it will only work for the <td> tags. It will replace everything between tags <td> (actually with them together and put the tags back) with TEXT_TO_REPLACE_BY.


问:
how to read a single number as a single character at a time not alphabets
I'm doing the accessibility, where I have a address eg :3156 Stock Avenue Ln B, Stockland, CA 95209. Where I want it to read only digits one at a time means a single character and read the address as it is.
How can I define in Java.
Appreciate your help.</p>

答:
Try this way:

```<code> public static String ExtractNumberFromString(String cnvrtdDate){
        String [] dateArray = cnvrtdDate.split("|");
        //System.out.println(dateArray);
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<dateArray.length;i++)
        {
            boolean ItIs = isNumeric(dateArray[i]);
            if(ItIs)
            {

                sb.append(dateArray[i]);
            }

        }
        return  sb.toString();
    }
</code>```

Also, to check number:

```<code>public static boolean isNumeric(String str)  {
    try
    {
        int d = Integer.parseInt(str);
    }
    catch(Exception nfe)
    {
        return false;
    }
    return true;
}
</code>```

Body:
Try this way:

 public static String ExtractNumberFromString(String cnvrtdDate){
        String [] dateArray = cnvrtdDate.split("|");
        //System.out.println(dateArray);
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<dateArray.length;i++)
        {
            boolean ItIs = isNumeric(dateArray[i]);
            if(ItIs)
            {

                sb.append(dateArray[i]);
            }

        }
        return  sb.toString();
    }

Also, to check number:

public static boolean isNumeric(String str)  {
    try
    {
        int d = Integer.parseInt(str);
    }
    catch(Exception nfe)
    {
        return false;
    }
    return true;
}


问:
ExpertPDF - How to know page number based on content in HTML
```<code>Suppose I have a HTML that have some heading & text like:

Heading 1
text......

Heading 2
text.....

Heading 3
text.....
</code>```

Now I have to print this template in PDF, during print out, I have to add index page which actually refer page number with heading. Means print out should be like this.

```<code>Heading 1 ....... 1 [page number]
Heading 2 ....... 2
Heading 3 ....... 3

Heading 1
text......

Heading 2
text.....

Heading 3
text.....
</code>```

So here I want to know, how to know page number based on text in HTML,  like heading 1 belong to which page number & for others.

```<code>Any suggestion or idea really appreciated.
</code>```

答:
This is actually a pretty tricky problem which ExpertPDF would have to provide specific functionality to make possible.

My solution (not expertpdf) for this was to calculate the layout of the PDF first, get the text to be used in the index for each page and then calculate the layout of the index page/s. Then I'm able to number the pages (including the index pages) then update the page numbers in the index.. This is the only way to handle template pages which span multiple pages themselves, index text which wraps to take up more than a single line, and indexes which span multiple pages.

Body:
Suppose I have a HTML that have some heading & text like:

Heading 1
text......

Heading 2
text.....

Heading 3
text.....

Now I have to print this template in PDF, during print out, I have to add index page which actually refer page number with heading. Means print out should be like this.

Heading 1 ....... 1 [page number]
Heading 2 ....... 2
Heading 3 ....... 3

Heading 1
text......

Heading 2
text.....

Heading 3
text.....

So here I want to know, how to know page number based on text in HTML,  like heading 1 belong to which page number & for others.

Any suggestion or idea really appreciated.


问:
How to know that a thread in a Thread Pool hangs/freezes
I have queue of tasks for the ThreadPool, and each task has a tendency to froze locking up all the resources it is using. And these cant be released unless the service is restarted.

Is there a way in the ThreadPool to know that its thread is already frozen? I have an idea of using a time out, (though i still dont know how to write it), but i think its not safe because the length of time for processing is not uniform.

答:
I don't want to be too presumptuous here, but a good dose of actually finding out what the problem is and fixing it is the best course with deadlocks.

Run a debug version of your service and wait until it deadlocks. It will stay deadlocked as this is a wonderful property of deadlocks.

Attach the Visual Studio debugger to the service.

"Break All".

Bring up your threads windows, and start spelunking...

Unless you have a sound architecture\design\reason to choose victims in the first place, don't do it - period. It's pretty much a recipe for disaster to arbitrarily bash threads over the head when they're in the middle of something.

ContentLicense: CC BY-SA 2.5


问:
Dynamic update for different colums using between two date like calendar date
```<code>CREATE PROCEDURE [dbo].[CalendarMonthly]
(
    @FROMDATE VARCHAR(25)
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @ADate DATETIME
DECLARE @MonthCount INT

SET @ADate = @FROMDATE
SET @MonthCount = (SELECT DAY(EOMONTH(@ADate)))

DECLARE @tmpTable TABLE
    (
    TRoomID INT,    DAY1 INT,   DAY2 INT,       DAY3 INT,   DAY4 INT,           DAY5 INT,   DAY6 INT,       DAY7 INT
    )

    INSERT INTO @tmpTable

    SELECT RM.ROOMID,
            0,0,0,0,0,0,0

        FROM RoomMaster AS RM
        LEFT JOIN RoomTypes AS RT ON RM.RoomTypeID = RT.RoomTypeID
             WHERE RM.RoomMasterStatus <> 99

DECLARE @RoomID INT
DECLARE @ForDate DATE
DECLARE @dtFromDate DATE
DECLARE @dtToDate DATE

SET @dtFromDate = CONVERT(DATE,@FromDate)
SET @ForDate = @dtFromDate
SET @dtToDate = CONVERT(DATE,CONVERT(VARCHAR,YEAR(@dtFromDate)) +'-'+ CONVERT(VARCHAR,MONTH(DATEADD(M,1,@dtFromDate)))+'-1')
SET @dtToDate = DATEADD(D,-1,@dtToDate)

DECLARE @DayCount INT

WHILE  @ForDate <= @dtToDate
    BEGIN

        SET @DayCount = DAY(@ForDate)

        IF @DayCount = 1
            BEGIN
                    -- Checkin
                    UPDATE @tmpTable SET DAY1 = 1

                    FROM @tmpTable TT
                    JOIN RoomCheckinDetails AS RCD ON RCD.RoomID = TT.TRoomID
                    JOIN RoomCheckinMaster AS RCM ON RCM.CheckinID = RCD.CheckinID
                        WHERE CONVERT(DATE,RCD.CheckinDate) = @ForDate
                                AND  RCD.RoomID = TT.TRoomID

                    -- Expected Checkin
                    UPDATE @tmpTable SET DAY1 = 8

                    FROM @tmpTable TT
                    JOIN RoomBookingDetails AS RBD ON RBD.RoomID = TT.TRoomID
                    JOIN RoomBookingMaster AS RBM ON RBM.ReservationID = RBD.ReservationID
                        WHERE CONVERT(DATE,RBD.ExpectedCheckinDate) = @ForDate
                                AND  RBD.RoomID = TT.TRoomID

            END
            ELSE IF @DayCount = 2
            .
            .
            .
            .
            .
            .
            ---upto Day count 7

        SET @ForDate = DATEADD(Day,1,@ForDate)

    END

    SELECT * FROM @tmpTable

END
</code>```

My question is:

ex: checkindate = 04/06/2017,  checoutdate = 9/06/2017 in compare two date I have update to columns day1 to columns day6 values is 0.

答:
Instead of creating a temporary table and using a cursor to update each set of columns, this is a set based solution that avoids all of that.

For the first part, if you just need 7 days then you can use a simple values tally table with a common table expression and the Table Value Constructor (Transact-SQL):

```<code>declare @fromdate date = '20170605';
;with dates as (
  select
      [Date]=convert(date,dateadd(day,rn-1,@fromdate))
    , rn
  from (values (1),(2),(3),(4),(5),(6),(7)) t(rn)
)
</code>```

Otherwise, you can generate an adhoc table of dates using stacked ctes in a common table expression like this:

```<code>declare @fromdate date = '20170605';
declare @thrudate date = dateadd(day,6,@fromdate)

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
    , rn = row_number() over(order by (select 1))
  from n as deka cross join n as hecto cross join n as kilo
                 cross join n as tenK cross join n as hundredK
   order by [Date]
)
</code>```

Then cross join the dates with roommaster, and left join both the checkin and booking tables to see if a room has a reservation or is currently occupied:

```<code>, cte as (
select
    rm.roomid
  , d.rn
  , Value = case
      when rcd.roomid is not null then 1
      when rbd.roomid is not null then 8
      else 0
      end
from dates d
  cross join roommaster rm
  left join roomcheckindetails rcd
    on rm.roomid = rcd.roomid
   and d.date >= rcd.checkindate
   and d.date <= rcd.checkoutdate
  left join roombookingdetails rbd
    on rm.roomid = rbd.roomid
   and d.date >= rbd.expectedcheckindate
   and d.date <= rbd.expectedcheckoutdate
where rm.roommasterstatus <> 99
)
</code>```

Then for the last piece, you can use conditional aggregation or pivot() (pick one) like so:

```<code>select
    roomid
  , Day1 = min(case when rn = 1 then value end)
  , Day2 = min(case when rn = 2 then value end)
  , Day3 = min(case when rn = 3 then value end)
  , Day4 = min(case when rn = 4 then value end)
  , Day5 = min(case when rn = 5 then value end)
  , Day6 = min(case when rn = 6 then value end)
  , Day7 = min(case when rn = 7 then value end)
from cte
group by roomid
</code>```

```<code>select
    roomid
  , Day1 = [1]
  , Day2 = [2]
  , Day3 = [3]
  , Day4 = [4]
  , Day5 = [5]
  , Day6 = [6]
  , Day7 = [7]
from cte
  pivot (min(value) for rn in ([1],[2],[3],[4],[5],[6],[7]))p
</code>```

rextester demo with conditional aggregation: http://rextester.com/RUJ98491

rextester demo with pivot(): http://rextester.com/YNKU89188

both return the same results for my demo data:

```<code>+--------+------+------+------+------+------+------+------+
| roomid | Day1 | Day2 | Day3 | Day4 | Day5 | Day6 | Day7 |
+--------+------+------+------+------+------+------+------+
|      2 |    1 |    1 |    1 |    1 |    0 |    0 |    0 |
|      3 |    0 |    8 |    8 |    8 |    8 |    0 |    0 |
+--------+------+------+------+------+------+------+------+
</code>```

Number and Calendar table reference:

Generate a set or sequence without loops - 2 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in sql Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in sql Server - Aaron Bertrand

Body:
CREATE PROCEDURE [dbo].[CalendarMonthly]
(
    @FROMDATE VARCHAR(25)
)
AS
BEGIN
SET NOCOUNT ON

DECLARE @ADate DATETIME
DECLARE @MonthCount INT

SET @ADate = @FROMDATE
SET @MonthCount = (SELECT DAY(EOMONTH(@ADate)))

DECLARE @tmpTable TABLE
    (
    TRoomID INT,    DAY1 INT,   DAY2 INT,       DAY3 INT,   DAY4 INT,           DAY5 INT,   DAY6 INT,       DAY7 INT
    )

    INSERT INTO @tmpTable

    SELECT RM.ROOMID,
            0,0,0,0,0,0,0

        FROM RoomMaster AS RM
        LEFT JOIN RoomTypes AS RT ON RM.RoomTypeID = RT.RoomTypeID
             WHERE RM.RoomMasterStatus <> 99

DECLARE @RoomID INT
DECLARE @ForDate DATE
DECLARE @dtFromDate DATE
DECLARE @dtToDate DATE

SET @dtFromDate = CONVERT(DATE,@FromDate)
SET @ForDate = @dtFromDate
SET @dtToDate = CONVERT(DATE,CONVERT(VARCHAR,YEAR(@dtFromDate)) +'-'+ CONVERT(VARCHAR,MONTH(DATEADD(M,1,@dtFromDate)))+'-1')
SET @dtToDate = DATEADD(D,-1,@dtToDate)

DECLARE @DayCount INT

WHILE  @ForDate <= @dtToDate
    BEGIN

        SET @DayCount = DAY(@ForDate)

        IF @DayCount = 1
            BEGIN
                    -- Checkin
                    UPDATE @tmpTable SET DAY1 = 1

                    FROM @tmpTable TT
                    JOIN RoomCheckinDetails AS RCD ON RCD.RoomID = TT.TRoomID
                    JOIN RoomCheckinMaster AS RCM ON RCM.CheckinID = RCD.CheckinID
                        WHERE CONVERT(DATE,RCD.CheckinDate) = @ForDate
                                AND  RCD.RoomID = TT.TRoomID

                    -- Expected Checkin
                    UPDATE @tmpTable SET DAY1 = 8

                    FROM @tmpTable TT
                    JOIN RoomBookingDetails AS RBD ON RBD.RoomID = TT.TRoomID
                    JOIN RoomBookingMaster AS RBM ON RBM.ReservationID = RBD.ReservationID
                        WHERE CONVERT(DATE,RBD.ExpectedCheckinDate) = @ForDate
                                AND  RBD.RoomID = TT.TRoomID

            END
            ELSE IF @DayCount = 2
            .
            .
            .
            .
            .
            .
            ---upto Day count 7

        SET @ForDate = DATEADD(Day,1,@ForDate)

    END

    SELECT * FROM @tmpTable

END

My question is:

ex: checkindate = 04/06/2017,  checoutdate = 9/06/2017 in compare two date I have update to columns day1 to columns day6 values is 0.

Body:
Instead of creating a temporary table and using a cursor to update each set of columns, this is a set based solution that avoids all of that.

For the first part, if you just need 7 days then you can use a simple values tally table with a common table expression and the Table Value Constructor (Transact-SQL):

declare @fromdate date = '20170605';
;with dates as (
  select
      [Date]=convert(date,dateadd(day,rn-1,@fromdate))
    , rn
  from (values (1),(2),(3),(4),(5),(6),(7)) t(rn)
)

Otherwise, you can generate an adhoc table of dates using stacked ctes in a common table expression like this:

declare @fromdate date = '20170605';
declare @thrudate date = dateadd(day,6,@fromdate)

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1)
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
    , rn = row_number() over(order by (select 1))
  from n as deka cross join n as hecto cross join n as kilo
                 cross join n as tenK cross join n as hundredK
   order by [Date]
)

Then cross join the dates with roommaster, and left join both the checkin and booking tables to see if a room has a reservation or is currently occupied:

, cte as (
select
    rm.roomid
  , d.rn
  , Value = case
      when rcd.roomid is not null then 1
      when rbd.roomid is not null then 8
      else 0
      end
from dates d
  cross join roommaster rm
  left join roomcheckindetails rcd
    on rm.roomid = rcd.roomid
   and d.date >= rcd.checkindate
   and d.date <= rcd.checkoutdate
  left join roombookingdetails rbd
    on rm.roomid = rbd.roomid
   and d.date >= rbd.expectedcheckindate
   and d.date <= rbd.expectedcheckoutdate
where rm.roommasterstatus <> 99
)

Then for the last piece, you can use conditional aggregation or pivot() (pick one) like so:

select
    roomid
  , Day1 = min(case when rn = 1 then value end)
  , Day2 = min(case when rn = 2 then value end)
  , Day3 = min(case when rn = 3 then value end)
  , Day4 = min(case when rn = 4 then value end)
  , Day5 = min(case when rn = 5 then value end)
  , Day6 = min(case when rn = 6 then value end)
  , Day7 = min(case when rn = 7 then value end)
from cte
group by roomid

select
    roomid
  , Day1 = [1]
  , Day2 = [2]
  , Day3 = [3]
  , Day4 = [4]
  , Day5 = [5]
  , Day6 = [6]
  , Day7 = [7]
from cte
  pivot (min(value) for rn in ([1],[2],[3],[4],[5],[6],[7]))p

rextester demo with conditional aggregation: http://rextester.com/RUJ98491

rextester demo with pivot(): http://rextester.com/YNKU89188

both return the same results for my demo data:

+--------+------+------+------+------+------+------+------+
| roomid | Day1 | Day2 | Day3 | Day4 | Day5 | Day6 | Day7 |
+--------+------+------+------+------+------+------+------+
|      2 |    1 |    1 |    1 |    1 |    0 |    0 |    0 |
|      3 |    0 |    8 |    8 |    8 |    8 |    0 |    0 |
+--------+------+------+------+------+------+------+------+

Number and Calendar table reference:

Generate a set or sequence without loops - 2 - Aaron Bertrand

The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden

Creating a Date Table/Dimension in sql Server 2008 - David Stein

Calendar Tables - Why You Need One - David Stein

Creating a date dimension or calendar table in sql Server - Aaron Bertrand


问:
Jetbrains Datagrip 2017.1.3, force columns exported when dumping data to sql inserts file
I have an SQL server database with a lot of tables and data. I need to reproduce it locally in a docker container.
I have successfully exported the schema and reproduced it. When I dump data to an SQL file, it does not export automatically generated fields (Like ids or uuids for example)

Here is the schema for the user table:

```<code> create table user (
    id_user bigint identity constraint PK_user primary key,
    uuid uniqueidentifier default newsequentialid() not null,
    id_salarie bigint constraint FK_user_salarie references salarie,
    date_creation datetime,
    login nvarchar(100)
)
</code>```

When it exports and element from this table, I get this kind of insert:

```<code>INSERT INTO user(id_salarie, date_creation, login) VALUES (1, null, "example")
</code>```

As a consequence, most of my inserts give me foreign key errors, because the ids generated by my new database are not the same as the ones in the old database. I can't change everything manually as there is way too much data.

Instead, I would like to have this kind of insert:

```<code>INSERT INTO user(id_user, uuid, id_salarie, date_creation, login) VALUES (1, 1, "manuallyentereduuid" null, "example")
</code>```

Is there any way to do this with Datagrid directly? Or maybe a specific SQL server way of generating insert statements this way?

Don't hesitate to ask for more details in comments.

答: You need the option 'Skip generated columns' while configuring INSERT extractor.

Body:
I have an SQL server database with a lot of tables and data. I need to reproduce it locally in a docker container.
I have successfully exported the schema and reproduced it. When I dump data to an SQL file, it does not export automatically generated fields (Like ids or uuids for example)

Here is the schema for the user table:

 create table user (
    id_user bigint identity constraint PK_user primary key,
    uuid uniqueidentifier default newsequentialid() not null,
    id_salarie bigint constraint FK_user_salarie references salarie,
    date_creation datetime,
    login nvarchar(100)
)

When it exports and element from this table, I get this kind of insert:

INSERT INTO user(id_salarie, date_creation, login) VALUES (1, null, "example")

As a consequence, most of my inserts give me foreign key errors, because the ids generated by my new database are not the same as the ones in the old database. I can't change everything manually as there is way too much data.

Instead, I would like to have this kind of insert:

INSERT INTO user(id_user, uuid, id_salarie, date_creation, login) VALUES (1, 1, "manuallyentereduuid" null, "example")

Is there any way to do this with Datagrid directly? Or maybe a specific SQL server way of generating insert statements this way?

Don't hesitate to ask for more details in comments.


问:
Unable to locate Spring NamespaceHandler for XML schema namespace spring-batch
I have to run a Spring batch job in a loop.

So my Main class is as below:

```<code>package com.mypackage.batch;

public class myApp {
public static void main(String[] args) {

    String[] springConfig  = {"spring/batch/jobs/myJob.xml"};

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    Job job = (Job) context.getBean("myJob");

     // read the file containing accountIds
    try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
        String account;
        while ((account = br.readLine()) != null) {

            JobParameters param = new JobParametersBuilder().addString("someParam", someParam).toJobParameters();
            JobExecution execution = jobLauncher.run(job, param);
            System.out.println("Exit Status : " + execution.getStatus());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    context.close();
}
}
</code>```

This works perfectly fine in Eclipse.

Now I want to run this on server. For this I want to create an executable jar.

I am creating it as below using maven assembly plugin:

```<code><plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
    <archive>
      <manifest>
        <mainClass>com.mypackage.batch.myApp</mainClass>
      </manifest>
    </archive>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
  </configuration>
</plugin>
</code>```

This creates a jar with dependencies say myBatch-jar-with-dependencies.jar

However, when I run the following command:

```<code>java -jar myBatch-jar-with-dependencies.jar abc.txt
</code>```

I get the following error:

```<code>    Jun 04, 2017 12:25:40 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4edde6e5: startup date [Sun Jun 04 12:25:40 AWST 2017]; root of context hierarchy
Jun 04, 2017 12:25:40 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/batch/jobs/myJob.xml]
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/batch]
Offending resource: class path resource [spring/batch/jobs/myJob.xml]

        at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:301)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1408)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1401)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:172)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:142)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
        at com.mypackage.batch.myApp.main(myApp.java:17)
</code>```

My schema definitions in spring batch xml is:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
    http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
</code>```

And the dependencies in my pom is:

```<code><properties>
        <jdk.version>1.8</jdk.version>
        <spring.version>4.3.8.RELEASE</spring.version>
        <spring.batch.version>3.0.7.RELEASE</spring.batch.version>
    </properties>

    <dependencies>

        <!-- Spring Core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring jdbc, for database -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring Batch dependencies -->
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-infrastructure</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.1.0.jre8</version>
            <exclusions>
                <exclusion>
                    <groupId>com.microsoft.azure</groupId>
                    <artifactId>azure-keyvault</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>
</code>```

What am I doing wrong ?

答:
In your namespace declaration, just change:
http://www.springframework.org/schema/batch/spring-batch.xsd  to be:
http://www.springframework.org/schema/batch/spring-batch-3.0.xsd, and it should work fine.

Otherwise you'll need to bake in custom spring.schemas files into your META-INF folder.

In the custom spring.schemas file you'd need something along the lines of this to map spring-batch.xsd to spring-batch-3.0.xsd:

```<code>http\://www.springframework.org/schema/batch/spring-batch.xsd=org/springframework/batch/core/configuration/xml/spring-batch-3.0.xsd
</code>```

Body:
I have to run a Spring batch job in a loop.

So my Main class is as below:

package com.mypackage.batch;

public class myApp {
public static void main(String[] args) {

    String[] springConfig  = {"spring/batch/jobs/myJob.xml"};

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    Job job = (Job) context.getBean("myJob");

     // read the file containing accountIds
    try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) {
        String account;
        while ((account = br.readLine()) != null) {

            JobParameters param = new JobParametersBuilder().addString("someParam", someParam).toJobParameters();
            JobExecution execution = jobLauncher.run(job, param);
            System.out.println("Exit Status : " + execution.getStatus());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    context.close();
}
}

This works perfectly fine in Eclipse.

Now I want to run this on server. For this I want to create an executable jar.

I am creating it as below using maven assembly plugin:

<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
    <archive>
      <manifest>
        <mainClass>com.mypackage.batch.myApp</mainClass>
      </manifest>
    </archive>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
  </configuration>
</plugin>

This creates a jar with dependencies say myBatch-jar-with-dependencies.jar

However, when I run the following command:

java -jar myBatch-jar-with-dependencies.jar abc.txt

I get the following error:

    Jun 04, 2017 12:25:40 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4edde6e5: startup date [Sun Jun 04 12:25:40 AWST 2017]; root of context hierarchy
Jun 04, 2017 12:25:40 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/batch/jobs/myJob.xml]
Exception in thread "main" org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/batch]
Offending resource: class path resource [spring/batch/jobs/myJob.xml]

        at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
        at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:301)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1408)
        at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1401)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:172)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:142)
        at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:94)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:508)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:392)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:336)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
        at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
        at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
        at com.mypackage.batch.myApp.main(myApp.java:17)

My schema definitions in spring batch xml is:

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
    http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

And the dependencies in my pom is:

<properties>
        <jdk.version>1.8</jdk.version>
        <spring.version>4.3.8.RELEASE</spring.version>
        <spring.batch.version>3.0.7.RELEASE</spring.batch.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-infrastructure</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.1.0.jre8</version>
            <exclusions>
                <exclusion>
                    <groupId>com.microsoft.azure</groupId>
                    <artifactId>azure-keyvault</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>

What am I doing wrong ?

Body:
In your namespace declaration, just change:
http://www.springframework.org/schema/batch/spring-batch.xsd  to be:
http://www.springframework.org/schema/batch/spring-batch-3.0.xsd, and it should work fine.

Otherwise you'll need to bake in custom spring.schemas files into your META-INF folder.

In the custom spring.schemas file you'd need something along the lines of this to map spring-batch.xsd to spring-batch-3.0.xsd:

http\://www.springframework.org/schema/batch/spring-batch.xsd=org/springframework/batch/core/configuration/xml/spring-batch-3.0.xsd


问:
Adding values of strings containing a specific string in Javascript
I have an object called guild, that has the following array:

```<code>members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.
</code>```

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

```<code> var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }
</code>```

答:
```<code>var members=guild.members.map(function(el){
  return {
        uuid: el.uuid,
        rank: el.rank,
        joined: el.joined,
        coins: Object.keys(el).filter(str=>str.includes("dailyCoins")).reduce((c,str)=>c+el[str],0)
    };
});
</code>```

You can simplify it using Array.filter / reduce...

Body:
I have an object called guild, that has the following array:

members: [
{
uuid: "6afc724d566746c796d13b233c9960ea",
rank: "MEMBER",
joined: 1492733608170,
dailyCoins-1-5-2017: 920,
dailyCoins-2-5-2017: 790,
dailyCoins-3-5-2017: 260,
dailyCoins-4-5-2017: 790
},
{
uuid: "fa014557f1ac4325b23940fb872031a4",
rank: "MEMBER",
joined: 1493332956351
},
etc.

How can I add together the value of each string that contains the string "dailyCoins" ?

Here is my current attempt:

 var guildMembers = [];
 var memberCoins = 0;
    for (i = 0; i < guild.members.length; i++) {
        for (j = 0; j < Object.keys(guild.members[i]).length; j++)
            console.log(Object.keys(guild.members[i]));
            if (Object.keys(guild.members[i])[j].includes("dailyCoins")) {
                var memberCoins = memberCoins + Object.values(guild.members[i])[j];
            }
        var member = {
            uuid: guild.members[i].uuid,
            rank: guild.members[i].rank,
            joined: guild.members[i].joined,
            coins: memberCoins
        };
        guildMembers.push(member);
    }

Body:
var members=guild.members.map(function(el){
  return {
        uuid: el.uuid,
        rank: el.rank,
        joined: el.joined,
        coins: Object.keys(el).filter(str=>str.includes("dailyCoins")).reduce((c,str)=>c+el[str],0)
    };
});

You can simplify it using Array.filter / reduce...


问:
Python DataFrame Copy
I am trying to create a new dataframe based on some criteria based on an original dataframe.

```<code>df = pandas.io.sql.read_sql(sql, conn)

Count_Row = df.shape[0]
for j in range(Count_Row - 1):

    if df.iloc[j, 0] == df.iloc[j + 1, 0]:
        print(df.iloc[j, 2] + df.iloc[j + 1, 2], df.iloc[j, 4], df.iloc[j, 6], df.iloc[j, 3])
</code>```

However instead of printing I want to add that data to a new dataframe.

How is this possible?

答:
Instead of printing out the data you can append it to a new data frame

```<code>import pandas as pd

df = pandas.io.sql.read_sql(sql, conn)
Count_Row = df.shape[0]

results = pd.DataFrame() # create data frame to store results

for j in range(Count_Row - 1):
    if df.iloc[j, 0] == df.iloc[j + 1, 0]:
        # create row of values to append
        row = pd.Series([df.iloc[j, 2] + df.iloc[j + 1, 2],
                        df.iloc[j, 4],
                        df.iloc[j, 6],
                        df.iloc[j, 3]])
        results = results.append([row])

results.columns = ['v1', 'v2', 'v3', 'v4'] # the variables
</code>```

This will give you a data frame with the desired output

Title: Python DataFrame Copy

Body:
I am trying to create a new dataframe based on some criteria based on an original dataframe.

df = pandas.io.sql.read_sql(sql, conn)

Count_Row = df.shape[0]
for j in range(Count_Row - 1):

    if df.iloc[j, 0] == df.iloc[j + 1, 0]:
        print(df.iloc[j, 2] + df.iloc[j + 1, 2], df.iloc[j, 4], df.iloc[j, 6], df.iloc[j, 3])

However instead of printing I want to add that data to a new dataframe.

How is this possible?

Body:
Instead of printing out the data you can append it to a new data frame

import pandas as pd

df = pandas.io.sql.read_sql(sql, conn)
Count_Row = df.shape[0]

results = pd.DataFrame() # create data frame to store results

for j in range(Count_Row - 1):
    if df.iloc[j, 0] == df.iloc[j + 1, 0]:
        # create row of values to append
        row = pd.Series([df.iloc[j, 2] + df.iloc[j + 1, 2],
                        df.iloc[j, 4],
                        df.iloc[j, 6],
                        df.iloc[j, 3]])
        results = results.append([row])

results.columns = ['v1', 'v2', 'v3', 'v4'] # the variables

This will give you a data frame with the desired output


问:
Use code to disable player input unreal engine
I have seen a lot of ways to use the node based visual scripts to stop player input; However, I have not seen a single example of how to disable the player input in visual studio?</p>

答:
You can disable player input using the function:

AActor::DisableInput(APlayerController* PlayerController)

This should be called on the actor you wish to disable input for. You need to have a pointer to the current player controller, and pass this as the function's argument. You can easily get the first (and usually only, in single player game) player controller from the current world:

UWorld::GetFirstPlayerController();

Quick example, with PlayerPawn being a pointer to the AActor that you wish to disable input for:

```<code>APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
PlayerPawn->DisableInput(PlayerController);
</code>```

Body:
You can disable player input using the function:

AActor::DisableInput(APlayerController* PlayerController)

This should be called on the actor you wish to disable input for. You need to have a pointer to the current player controller, and pass this as the function's argument. You can easily get the first (and usually only, in single player game) player controller from the current world:

UWorld::GetFirstPlayerController();

Quick example, with PlayerPawn being a pointer to the AActor that you wish to disable input for:

APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
PlayerPawn->DisableInput(PlayerController);


问:
Pandas: multiply starting value for one column through each value in another within group
I have a starting value and some future expected growth rates for a number of customers.

Here is a simple sample dataframe:

```<code>df = pd.DataFrame([['A',1,10,np.nan],['A',2,10,1.2],['A',3,10,1.15],
                  ['B',1,20,np.nan],['B',2,20,1.05],['B',3,20,1.2]],columns = ['Cust','Period','startingValue','Growth'])
print df

  Cust  Period  startingValue  Growth
0    A       1             10     NaN
1    A       2             10    1.20
2    A       3             10    1.15
3    B       1             20     NaN
4    B       2             20    1.05
5    B       3             20    1.20
</code>```

For each Cust, I want to multiply the starting value by the growth rate, then carry that value forward to the next period. I could do this with groupby-apply or an ugly for loop, but I'm hoping there's some faster vectorized method for doing this. I had hoped there would be some .fill() magic, where you could multiply by another column as it fills downwards. Here's what the output should look like:

```<code> Cust  Period  startingValue  Growth  Pred_val
0    A       1             10     NaN      10.0
1    A       2             10    1.20      12.0
2    A       3             10    1.15      13.8
3    B       1             20     NaN      20.0
4    B       2             20    1.05      21.0
5    B       3             20    1.20      25.2
</code>```

Thoughts?

答:
You can do a cumulative product using cumprod function:

```<code>df['Pred_val'] = df.Growth.fillna(1).groupby(df.Cust).cumprod()*df.startingValue
</code>```

Body:
I have a starting value and some future expected growth rates for a number of customers.

Here is a simple sample dataframe:

df = pd.DataFrame([['A',1,10,np.nan],['A',2,10,1.2],['A',3,10,1.15],
                  ['B',1,20,np.nan],['B',2,20,1.05],['B',3,20,1.2]],columns = ['Cust','Period','startingValue','Growth'])
print df

  Cust  Period  startingValue  Growth
0    A       1             10     NaN
1    A       2             10    1.20
2    A       3             10    1.15
3    B       1             20     NaN
4    B       2             20    1.05
5    B       3             20    1.20

For each Cust, I want to multiply the starting value by the growth rate, then carry that value forward to the next period. I could do this with groupby-apply or an ugly for loop, but I'm hoping there's some faster vectorized method for doing this. I had hoped there would be some .fill() magic, where you could multiply by another column as it fills downwards. Here's what the output should look like:

 Cust  Period  startingValue  Growth  Pred_val
0    A       1             10     NaN      10.0
1    A       2             10    1.20      12.0
2    A       3             10    1.15      13.8
3    B       1             20     NaN      20.0
4    B       2             20    1.05      21.0
5    B       3             20    1.20      25.2

Thoughts?

Body:
You can do a cumulative product using cumprod function:

df['Pred_val'] = df.Growth.fillna(1).groupby(df.Cust).cumprod()*df.startingValue


问:
MVVM bind IsEnabled to multiple bools in ViewModel
I have the button below which has it's IsEnabled property bound to a bool in the ViewModel called EnableBtn.

If I have another bool called EnableMail how would I amend this so that the IsEnabled is bound to both?

```<code>    <Button IsEnabled="{Binding EnableBtn, Converter={StaticResource InvertBooleanConverter}}" x:Name="SaveSendButton" Grid.Row="0" Grid.Column="1" Text="{i18n:Translate SaveAndSend}" Style="{StaticResource bottomButtonsBlue}" Command="{Binding EmailPlanCommand}"></Button>
</code>```

答:
Alternative to the valid solution from meq, you could use a multi binding:

The XAML code would look like:

```<code><Button.IsEnabled>
    <MultiBinding Converter="{StaticResource AreAllTrueMultiValueConverter}">
        <Binding Path="EnableBtn" />
        <Binding Path="EnableMail" />
    </MultiBinding>
</TextBox.IsEnabled>
</code>```

However, you need a MultiValueConverter similar to:

```<code>public class AreAllTrueMultiValueConverter: IMultiValueConverter
{
    public object Convert(object[] values, Type targetType,
           object parameter, System.Globalization.CultureInfo culture)
    {
        return values.OfType<bool>().All();
    }
    public object[] ConvertBack(object value, Type[] targetTypes,
           object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException("Cannot convert back");
    }
}
</code>```

I would prefer the MultiBinding to the additional view model property because it doesn't require "dependent properties" that has to be notified if another property changed. Therefore it results in simpler view model logic.

Body:
I have the button below which has it's IsEnabled property bound to a bool in the ViewModel called EnableBtn.

If I have another bool called EnableMail how would I amend this so that the IsEnabled is bound to both?

    <Button IsEnabled="{Binding EnableBtn, Converter={StaticResource InvertBooleanConverter}}" x:Name="SaveSendButton" Grid.Row="0" Grid.Column="1" Text="{i18n:Translate SaveAndSend}" Style="{StaticResource bottomButtonsBlue}" Command="{Binding EmailPlanCommand}"></Button>

Body:
Alternative to the valid solution from meq, you could use a multi binding:

The XAML code would look like:

<Button.IsEnabled>
    <MultiBinding Converter="{StaticResource AreAllTrueMultiValueConverter}">
        <Binding Path="EnableBtn" />
        <Binding Path="EnableMail" />
    </MultiBinding>
</TextBox.IsEnabled>

However, you need a MultiValueConverter similar to:

public class AreAllTrueMultiValueConverter: IMultiValueConverter
{
    public object Convert(object[] values, Type targetType,
           object parameter, System.Globalization.CultureInfo culture)
    {
        return values.OfType<bool>().All();
    }
    public object[] ConvertBack(object value, Type[] targetTypes,
           object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException("Cannot convert back");
    }
}

I would prefer the MultiBinding to the additional view model property because it doesn't require "dependent properties" that has to be notified if another property changed. Therefore it results in simpler view model logic.


问:
geocoder.getFromLocationName error
Getting "always true" result on if (location != null || !location.equals("")) and when I search something like "sldjfuhsdhfj" it closes the app, but when I enter something like "Central Park" it works correctly.
What am I doing wrong?
Code I am using

```<code>public void onMapSearch(View view) {
    EditText locationSearch = (EditText) findViewById(R.id.editText1);
    String location = locationSearch.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 3s
                mMap.clear();
            }
        }, 3000);
    }
}
</code>```

答:
Address address = addressList.get(0)

You gave it junk so it is returning no results. addressList is empty. You are accessing the 0 element of something that is empty. You should have seen a message in the Android Monitor window of Android Studio that pointed you to this exact line / issue.

Title: geocoder.getFromLocationName error

Body:
Getting "always true" result on if (location != null || !location.equals("")) and when I search something like "sldjfuhsdhfj" it closes the app, but when I enter something like "Central Park" it works correctly.
What am I doing wrong?
Code I am using

public void onMapSearch(View view) {
    EditText locationSearch = (EditText) findViewById(R.id.editText1);
    String location = locationSearch.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 3s
                mMap.clear();
            }
        }, 3000);
    }
}


问:
Javascript get data attribute from selected option in a table
I got the following html:

```<code><td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>
</code>```

I need to get data attribute of the selected option. I am trying to do it that way:

```<code>var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
    localobj[dataattr] = selectObject[0].getAttribute('data-key');//val(); previously it was val() here but now I want data-key
}
</code>```

I tried with this:

```<code>$(selectObject/*need to insert something here*/ + ' option:selected').data('key');
</code>```

but it is showing me an error saying that it is an object Object. I need to insert something after selectObject. Any ideas how to fix that?

Thank you.

答:
$('.form-control').change(function(){
alert($('.form-control').find(':selected').attr('data-key'));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td></code>```

Body:
I got the following html:

<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>

I need to get data attribute of the selected option. I am trying to do it that way:

var cell = $row.find(':nth-child(4)');
dataattr = cell[0].getAttribute('data-id');
var selectObject = cell.find("select");
if(selectObject.length){// if it is a select
    localobj[dataattr] = selectObject[0].getAttribute('data-key');//val(); previously it was val() here but now I want data-key
}

I tried with this:

$(selectObject/*need to insert something here*/ + ' option:selected').data('key');

but it is showing me an error saying that it is an object Object. I need to insert something after selectObject. Any ideas how to fix that?

Thank you.

Body:
$('.form-control').change(function(){
alert($('.form-control').find(':selected').attr('data-key'));
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="" data-id="46" contenteditable="true">
<select class="form-control">
   <option data-key="end" selected>Opt1</option>
   <option data-key="operator_transfer">Opt2</option>
   <option data-key="process_script">Opt3</option>
</select>
</td>


问:
How to swap keys and values in a Map elegantly
I already know how to do it the hard way and got it working - iterating over entries and swapping "manually". But i wonder if, like so many tasks,  this one can be solved in a more elegant way.

I have read this post, unfortunately it does not feature elegant solutions. I also have no possibility to use any fancy Guava BiMaps or anything outside the jdk (project stack is already defined).

I can assume that my map is bijective, btw :)

答:
Maps are not like lists, which can be reversed by swapping head with tail.

Objects in maps have a computed position, and using the value as key and the key as value would requiere to re-compute the storage place, essentialy building another map. There is no elegant way.

There are, however, bidirectional maps. Those may suit your needs. I'd reconsider using third-party libraries.


问:
White space between slides bootstrap carousel
I am using the bootstrap carousel for a slider on the home page of a website.

When the carousel slides automatically there is no problem but as soon as I click the next and prev arrows a ±140px wide white space appears between the slides.

I have inspected the css and removed all white space in the HTML but I'm having no luck at all.

Carousel HTML:

```<code><div class="clearfix row slider">
<div class="clearfix carousel slide col-lg-12 col-md-12 col-sm-12 col-xs-12" data-ride="carousel" id="carousel-example-generic">
    <div class="carousel-inner">
        <div class="clearfix item active" style='background: url("/Content/Images/media/carousel/hero-test.jpg") no-repeat;'>
            <div class="clearfix max-width carousel-caption">
                <h2>Hello. I'm Lorem. I'm a Slow
                Cooker.</h2><span class="clearfix">And I'm quickly
                changing the world</span>
                <a class='fresco cta' data-fresco-caption="Lorem | How It Works" data-fresco-group='example' href='https://vimeo.com/105705114'>How It Works</a>
            </div>
            <video autoplay="" class="bgvid" loop="" poster="/Content/Images/default/video-bg.jpg">
                <source src="/Content/Images/media/bkvideo/1_Lorem-marquee.mp4" type="video/webm">
                <source src="polina.html" type="video/mp4">
            </video>
        </div>
        <div class="clearfix item" style='background: url("/Content/Images/media/carousel/1_marquee-2.jpg ") no-repeat;'>
            <div class="clearfix max-width carousel-caption">
                <h2>Get to know Lorem.</h2><span class="clearfix">And learn the Lorem Story</span>
                <a class="cta" href="/Pages/SarahsStory">Meet Lorem</a>
            </div>
        </div>
    </div>
    <a class="left carousel-control" data-slide="prev" href="#carousel-example-generic"><span><img alt=" " src="/Content/Images/default/arrow-slider.svg"></span></a>
    <a class="right carousel-control" data-slide="next" href="#carousel-example-generic"><span><img alt=" " src="/Content/Images/default/arrow-slider.svg"></span></a>
</div>
</code>```

Link to website: http://bit.ly/1BcaEb8 - Click on South Africa and its the main carousel / slider

答:
set carousel-inner overflow to visible.</p>
```<code>.carousel-inner{overflow:visible}
</code>```

Body:
I am using the bootstrap carousel for a slider on the home page of a website.

When the carousel slides automatically there is no problem but as soon as I click the next and prev arrows a ±140px wide white space appears between the slides.

I have inspected the css and removed all white space in the HTML but I'm having no luck at all.

Carousel HTML:

Hello. I'm Lorem. I'm a Slow
                Cooker.
And I'm quickly
                changing the world
                How It Works

            <video autoplay="" class="bgvid" loop="" poster="/Content/Images/default/video-bg.jpg">
                <source src="/Content/Images/media/bkvideo/1_Lorem-marquee.mp4" type="video/webm">
                <source src="polina.html" type="video/mp4">
            </video>

Get to know Lorem.
And learn the Lorem Story
                Meet Lorem

Link to website: http://bit.ly/1BcaEb8 - Click on South Africa and its the main carousel / slider

Body:
set carousel-inner overflow to visible.

.carousel-inner{overflow:visible}

ContentLicense: CC BY-SA 4.0


问:
Plotting asymmetric error bars for a single point using errorbar
Goal: To plot asymmetric x error bars for a single point using errorbar. I want to display the inter quartile range (IQR) for a data set.

Code:

```<code>import numpy as np
import matplotlib.pyplot as plt

y = 1.0
data = np.random.rand(100)

median = np.median(data)
upper_quartile = np.percentile(data, 75)
lower_quartile = np.percentile(data, 25)
IQR = upper_quartile - lower_quartile

plt.errorbar(median, y, xerr=[lower_quartile ,upper_quartile], fmt='k--')

plt.savefig('IQR.eps')
plt.show()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "IQR.py", line 15, in <module>
    plt.errorbar(median, y, xerr=[0.5,0.75], fmt='k--')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2251, in errorbar
    ret = ax.errorbar(x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 5327, in errorbar
    in cbook.safezip(x,xerr)]
  File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 1294, in safezip
    raise ValueError(_safezip_msg % (Nx, i+1, len(arg)))
ValueError: In safezip, len(args[0])=1 but len(args[1])=2
</code>```

My issue is that I am unable to create asymmetric error bars for a single point, where the point will represent the mean and the upper and lower limits of the error bars will be the upper and lower quartile.

答:
Make sure xerr gets a list of lists. If it's only one list, it'll assume it contains symmetrical error bars for two Y's. But there's only one Y, which is why you get the error.

Also your errorbars are wrong. Change the errorbar call to

plt.errorbar(median, y, xerr=[[median-lower_quartile ,upper_quartile-median]], fmt='k--')

Body:
Goal: To plot asymmetric x error bars for a single point using errorbar. I want to display the inter quartile range (IQR) for a data set.

Code:

import numpy as np
import matplotlib.pyplot as plt

y = 1.0
data = np.random.rand(100)

median = np.median(data)
upper_quartile = np.percentile(data, 75)
lower_quartile = np.percentile(data, 25)
IQR = upper_quartile - lower_quartile

plt.errorbar(median, y, xerr=[lower_quartile ,upper_quartile], fmt='k--')

plt.savefig('IQR.eps')
plt.show()

Error:

Traceback (most recent call last):
  File "IQR.py", line 15, in <module>
    plt.errorbar(median, y, xerr=[0.5,0.75], fmt='k--')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2251, in errorbar
    ret = ax.errorbar(x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 5327, in errorbar
    in cbook.safezip(x,xerr)]
  File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 1294, in safezip
    raise ValueError(_safezip_msg % (Nx, i+1, len(arg)))
ValueError: In safezip, len(args[0])=1 but len(args[1])=2

My issue is that I am unable to create asymmetric error bars for a single point, where the point will represent the mean and the upper and lower limits of the error bars will be the upper and lower quartile.