问:
Matching lines in a text-file with a starting identifer
So I'm a bit stumped on this, I'm reading a file with two types of lines that contain data, and they are started by a number followed by a comma. I need a way in order to match the lines with the same starting digit into a single line and output that. How would I even get started?</p>

答:
I'd do this by reading each line in two parts: the stuff before the comma, and the stuff after it.

Then I'd have a map (or unordered_map) with the value before the comma as the key, and the rest as the value associated with it.

```<code>std::map<std::string, std::string> data;

std::string key, value;

while (std::getline(infile, key, ',')) {
    std::getline(infile, value);
    data[key] += value;
}
</code>```

Then (presumably) you'd want to write out the values:

```<code>for (auto const &v : data)
    std::cout << v.first << ":" << v.second << "\n";
</code>```

Body:
I'd do this by reading each line in two parts: the stuff before the comma, and the stuff after it.

Then I'd have a map (or unordered_map) with the value before the comma as the key, and the rest as the value associated with it.

std::map<std::string, std::string> data;

std::string key, value;

while (std::getline(infile, key, ',')) {
    std::getline(infile, value);
    data[key] += value;
}

Then (presumably) you'd want to write out the values:

for (auto const &v : data)
    std::cout << v.first << ":" << v.second << "\n";


来源: stackexchange

问:
Convert all words from text file to UpperCase using cmd or vbsscript
I have a text file called C:\Test.txt. I would like to convert all words inside the text file to UpperCases using cmd. Could you please help me?

I tried with

```<code>@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (%1) do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo !line!
)
</code>```

but i do not see where to put the location of the test.txt file

答:
As Stephan already pointed out in a comment, %1 constitutes an argument reference that points to the first command line argument. Therefore, supposing your batch file is called upper-case.bat and your text file is C:\test.txt, you must call your batch file like this:

upper-case.bat C:\test.txt
```

<p>However, in case your test file contains white-spaces or special characters in its path, like <code>C:\test file.txt</code>, for example, you must put it in between quotation marks, like this:</p>

<pre class="lang-cmd prettyprint-override"><code>upper-case.bat "C:\test file.txt"
</code>```

For your batch file to not fail, you must modify it like this to handle quoted arguments properly:

@echo off
setlocal EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%~1") do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo(!line!
)
```

<p>Instead of <code>%1</code> I wrote <code>"%~1"</code>, which first removes potential surrounding quotes (<code>~</code>), then places quotes around the result. That way, we always have exactly a pair of quotes. To make <code>for /F</code> handle quotes correctly, so to not treat the quoted file path as a literal string, I added its <code>usebackq</code> option.</p>

<p>Note that <code>for /F</code> ignores empty lines, hence such become lost. It also ignores lines beginning with a semicolon (<code>;</code>), because of its default <code>eol</code> option; to avoid that, replace <code>"usebackq delims="</code> by the odd-looking unquoted syntax <code>usebackq^ delims^=^ eol^=</code> (you cannot state <code>"usebackq delims= eol="</code>, because this would define <code>"</code> as the <code>eol</code> character).</p>

<p>To prevent <code>echo</code> from returning <code>ECHO is {on|off}.</code> in case white-space-only lines are encountered, I replaced the <kbd>SPACE</kbd> behind <code>echo</code> by <code>(</code>, because this is the only way to safely return the given string.</p>

<p>By the way, to write the output to another text file, use redirection, like in the following command line:</p>

<pre class="lang-cmd prettyprint-override"><code>upper-case.bat "C:\test.txt" > "C:\return.txt"
</code>```

Regard that you must specify a different file than the input file.

ContentLicense: CC BY-SA 3.0

Body:
I have a text file called C:\Test.txt. I would like to convert all words inside the text file to UpperCases using cmd. Could you please help me?

I tried with

@echo off
setlocal EnableDelayedExpansion
for /F "delims=" %%a in (%1) do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo !line!
)

but i do not see where to put the location of the test.txt file

Body:
As Stephan already pointed out in a comment, %1 constitutes an argument reference that points to the first command line argument. Therefore, supposing your batch file is called upper-case.bat and your text file is C:\test.txt, you must call your batch file like this:

upper-case.bat C:\test.txt

However, in case your test file contains white-spaces or special characters in its path, like C:\test file.txt, for example, you must put it in between quotation marks, like this:

upper-case.bat "C:\test file.txt"

For your batch file to not fail, you must modify it like this to handle quoted arguments properly:

@echo off
setlocal EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%~1") do (
   set "line=%%a"
   for %%b in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      set "line=!line:%%b=%%b!"
   )
   echo(!line!
)

Instead of %1 I wrote "%~1", which first removes potential surrounding quotes (~), then places quotes around the result. That way, we always have exactly a pair of quotes. To make for /F handle quotes correctly, so to not treat the quoted file path as a literal string, I added its usebackq option.

Note that for /F ignores empty lines, hence such become lost. It also ignores lines beginning with a semicolon (;), because of its default eol option; to avoid that, replace "usebackq delims=" by the odd-looking unquoted syntax usebackq^ delims^=^ eol^= (you cannot state "usebackq delims= eol=", because this would define " as the eol character).

To prevent echo from returning ECHO is {on|off}. in case white-space-only lines are encountered, I replaced the SPACE behind echo by (, because this is the only way to safely return the given string.

By the way, to write the output to another text file, use redirection, like in the following command line:

upper-case.bat "C:\test.txt" > "C:\return.txt"

Regard that you must specify a different file than the input file.


问:
Python - skip empty lines and print 3 lines after a match
I cannot seem to skip the empty line-

```<code>import re

with open('list.txt', 'r+') as f:
      line = f.readline()
      while(line):
        if line != ['']:
            if " win" in line:
                print(f.readline(),end="")
            # 2nd line
                print(f.readline(),end="")
            # 3rd line
                print(f.readline(),end="")
            line = f.readline()
</code>```

list.txt

```<code>You tell yourself...
That should have been my big win.

It's a kick in the gut.
Knowing in your heart the reason.
While you're stuck on the outside.
Grinning.
</code>```

It prints with like below instead-
Lines shows up after an empty line.

    It's a kick in the gut.
    Knowing in your heart the reason.

答:
You need to tell it to skip blank lines when printing (comments are inline):</p>

```<code>if " win" in line:
    for _ in range(3):  # do three times
        line = f.readline()  # get next line
        # skip blank lines
        while not line.strip():
            line = f.readline()
        # Print the non-blank line
        print(line, end="")
line = f.readline()
</code>```

Body:
I cannot seem to skip the empty line-

import re

with open('list.txt', 'r+') as f:
      line = f.readline()
      while(line):
        if line != ['']:
            if " win" in line:
                print(f.readline(),end="")
            # 2nd line
                print(f.readline(),end="")
            # 3rd line
                print(f.readline(),end="")
            line = f.readline()

list.txt

You tell yourself...
That should have been my big win.

It's a kick in the gut.
Knowing in your heart the reason.
While you're stuck on the outside.
Grinning.

It prints with like below instead-
Lines shows up after an empty line.

    It's a kick in the gut.
    Knowing in your heart the reason.

Body:
You need to tell it to skip blank lines when printing (comments are inline):

if " win" in line:
    for _ in range(3):  # do three times
        line = f.readline()  # get next line
        # skip blank lines
        while not line.strip():
            line = f.readline()
        # Print the non-blank line
        print(line, end="")
line = f.readline()


问:
Efficient querying for equality of ranges in an integer array
Given an positive integer array of size n, it is expected to find whether two ranges gives as queries are equal or not. Two ranges are considered equal if the all the elements present in range 1 are present in range 2 and in the same count as well.

Example:

```<code>1 2 5 3 5 1 2
</code>```

Queries:

```<code>[1,3] and [5,7]
[2,4] and [3,5]
</code>```

Answers:

```<code>Yes
No
</code>```

A naive solution can be suggested in the following way:

1. For every query, make two copies of the array that store each of the ranges O(n).

2. Then sort each of them. O(n*logn)

3. Then compare element by element and return true or false. O(n)

So the complexity of the solution is O(q*n*logn), where q is the number of queries. Is it possible for an efficient solution to this problem?

PS: The constraints of all the variables n, q and the array elements are <=10^5.

答:
Okay, let's start with the array: 1 2 5 3 5 1 2

This array has four distinct elements (let's call this number d), and we can pre-calculate four lists like this:

```<code>D[1]: 1 1 1 1 1 2 2
D[2]: 0 1 1 1 1 1 2
D[3]: 0 0 0 1 1 1 1
D[5]: 0 0 1 1 2 2 2
</code>```

These contain the number of each distinct element encountered up to that point. The size of this list is obviously d*n.

Once that's done, for each query you can simply check how many of each distinct element E there is in the range (x,y) by calculating D[E][y]-D[E][x]). Two ranges will contain exactly the same elements iff for all distinct elements this difference is identical.

Obviously this solution works best if the number of distinct elements is relatively low compared to n, with the per-query cost being O(distinct values).

I also omitted a couple of fairly simple optimisations, like if the two ranges aren't of equal length, or bailing out early if any of the differences is found to be different.

Update:

You can also store the same map like this:

```<code>D'[1]: 0 5
D'[2]: 1 6
D'[3]: 3
D'[5]: 2 4
</code>```

This map only contains the indices of where the original D[] would change. The size of this map is always n, but calculating D[E][y] - D[E][x] now involves a binary search, which still maintains an O(n) worst case per-query cost.

But it still isn't ideal for queries of short ranges, where the naive comparison of each item will yield a better result.

Body:
Given an positive integer array of size n, it is expected to find whether two ranges gives as queries are equal or not. Two ranges are considered equal if the all the elements present in range 1 are present in range 2 and in the same count as well.

Example:

1 2 5 3 5 1 2

Queries:

[1,3] and [5,7]
[2,4] and [3,5]

Answers:

Yes
No

A naive solution can be suggested in the following way:

1. For every query, make two copies of the array that store each of the ranges O(n).

2. Then sort each of them. O(n*logn)

3. Then compare element by element and return true or false. O(n)

So the complexity of the solution is O(q*n*logn), where q is the number of queries. Is it possible for an efficient solution to this problem?

PS: The constraints of all the variables n, q and the array elements are <=10^5.

Body:
Okay, let's start with the array: 1 2 5 3 5 1 2

This array has four distinct elements (let's call this number d), and we can pre-calculate four lists like this:

D[1]: 1 1 1 1 1 2 2
D[2]: 0 1 1 1 1 1 2
D[3]: 0 0 0 1 1 1 1
D[5]: 0 0 1 1 2 2 2

These contain the number of each distinct element encountered up to that point. The size of this list is obviously d*n.

Once that's done, for each query you can simply check how many of each distinct element E there is in the range (x,y) by calculating D[E][y]-D[E][x]). Two ranges will contain exactly the same elements iff for all distinct elements this difference is identical.

Obviously this solution works best if the number of distinct elements is relatively low compared to n, with the per-query cost being O(distinct values).

I also omitted a couple of fairly simple optimisations, like if the two ranges aren't of equal length, or bailing out early if any of the differences is found to be different.

Update:

You can also store the same map like this:

D'[1]: 0 5
D'[2]: 1 6
D'[3]: 3
D'[5]: 2 4

This map only contains the indices of where the original D[] would change. The size of this map is always n, but calculating D[E][y] - D[E][x] now involves a binary search, which still maintains an O(n) worst case per-query cost.

But it still isn't ideal for queries of short ranges, where the naive comparison of each item will yield a better result.


问:
How to make smaller a background circle in a font awesome icon?
I need to produce the following warning sign using Font Awesome:

However, I am not able to make it exactly as it is because I have like an extra border:

This is my HTML:

```<code><div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation-circle extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>
</div>
</code>```

This is my CSS (SCSS):

```<code>$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    font-size: 100px;
    color: #ff91a5;
    background: white;
    border-radius: 50%;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size:3em;
}
</code>```

This is my CodePen link.

答:
Using flexbox:

div {
  color: white;
  text-align: center;
  background-color: #db2b4b;
}

#exclamation-mark {
  font-size: 80px;
  color: white;
  background: #ff91a5;
  border-radius: 50%;
  padding:8px;
  margin: 5px 20px;
  height: 1em;
  width: 1em;
}

.extraClass{
     font-size:3em;
}

#close {
  font-size: 80px;
  color: white;
  background: #transparent;
  border-radius: 50%;
  padding:8px;
  margin: 5px 20px;
  height: 1em;
  width: 1em;
}

.alert {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

p{
  line-height: 0.8em;
}

p.bold {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation extraClass" aria-hidden="true"></i>
  <div>
  <p class="bold">Oops! Something went horribly wrong.</p>
  <p>We’re really sorry. Please try that again.</p>
  </div>
  <i id="close" class="fa fa-close extraClass" aria-hidden="true"></i>
</div></code>```

Body:
I need to produce the following warning sign using Font Awesome:

However, I am not able to make it exactly as it is because I have like an extra border:

This is my HTML:

    Oops! Something went horribly wrong.  We’re really sorry. Please try that again.

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>

This is my CSS (SCSS):

$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    font-size: 100px;
    color: #ff91a5;
    background: white;
    border-radius: 50%;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size:3em;
}

This is my CodePen link.

Body:
Using flexbox:

div {
  color: white;
  text-align: center;
  background-color: #db2b4b;
}

#exclamation-mark {
  font-size: 80px;
  color: white;
  background: #ff91a5;
  border-radius: 50%;
  padding:8px;
  margin: 5px 20px;
  height: 1em;
  width: 1em;
}

.extraClass{
     font-size:3em;
}

#close {
  font-size: 80px;
  color: white;
  background: #transparent;
  border-radius: 50%;
  padding:8px;
  margin: 5px 20px;
  height: 1em;
  width: 1em;
}

.alert {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

p{
  line-height: 0.8em;
}

p.bold {
  font-weight: bold;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation extraClass" aria-hidden="true"></i>
  <div>
  <p class="bold">Oops! Something went horribly wrong.</p>
  <p>We’re really sorry. Please try that again.</p>
  </div>
  <i id="close" class="fa fa-close extraClass" aria-hidden="true"></i>
</div>


问:
Connect Qt application to PostgreSQL DB without driver
Subj: is it possible?
If yes:
1) Is it acceptable programming strategy?
2) How to do it?</p>

答:
No You cannot connect to any database without proper driver. For PostgreSQL 7.3 and later you should use QPSQL. If you want you can create your own database driver.

Here you can find description of all supported sql drivers for qt and instructions how to create a new one:

http://doc.qt.io/qt-5/sql-driver.html

ContentLicense: CC BY-SA 2.5


问:
Twilio TwimlResponse not a constructor
I have followed the other answers to this and have simplified my call down to this:

```<code>var http = require('http');
var twilio = require('twilio');
http.createServer(function (req, res) {
var resp = new twilio.TwimlResponse();
     resp.say({voice:'woman'}, 'ahoy hoy! Testing Twilio and node.js');
     res.writeHead(200, {
      'Content-Type':'text/xml'
     });
     res.end(resp.toString());
}).listen(1337);
</code>```

This returns:

```<code>TypeError: twilio.TwimlResponse is not a constructor
at Server.<anonymous> (C:\Users\jmmann\Projects\node-sms\server.js:9:14)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:548:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
</code>```

Any idea/suggestions?

答:
I think you are trying to use the old deprecated version 2.X code with the current version 3.X SDK.
Here is some demo code from Twilio's website to do this using the current 3.X version of the SDK:

```<code>const http = require('http');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

http.createServer((req, res) => {
    // Create TwiML response
    const twiml = new VoiceResponse();

    twiml.say('Hello from your pals at Twilio! Have fun.');

    res.writeHead(200, {'Content-Type': 'text/xml'});
    res.end(twiml.toString());
})
.listen(1337, '127.0.0.1');

console.log('TwiML server running at http://127.0.0.1:1337/');
</code>```

If you are using the old 2.X version of the SDK you can switch their example using the selector near the top right of the page.

Title: Twilio TwimlResponse not a constructor

Body:
I have followed the other answers to this and have simplified my call down to this:

var http = require('http');
var twilio = require('twilio');
http.createServer(function (req, res) {
var resp = new twilio.TwimlResponse();
     resp.say({voice:'woman'}, 'ahoy hoy! Testing Twilio and node.js');
     res.writeHead(200, {
      'Content-Type':'text/xml'
     });
     res.end(resp.toString());
}).listen(1337);

This returns:

TypeError: twilio.TwimlResponse is not a constructor
at Server.<anonymous> (C:\Users\jmmann\Projects\node-sms\server.js:9:14)
at emitTwo (events.js:106:13)
at Server.emit (events.js:191:7)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:548:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)

Any idea/suggestions?

Body:
I think you are trying to use the old deprecated version 2.X code with the current version 3.X SDK.
Here is some demo code from Twilio's website to do this using the current 3.X version of the SDK:

const http = require('http');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

http.createServer((req, res) => {
    // Create TwiML response
    const twiml = new VoiceResponse();

    twiml.say('Hello from your pals at Twilio! Have fun.');

    res.writeHead(200, {'Content-Type': 'text/xml'});
    res.end(twiml.toString());
})
.listen(1337, '127.0.0.1');

console.log('TwiML server running at http://127.0.0.1:1337/');

If you are using the old 2.X version of the SDK you can switch their example using the selector near the top right of the page.


问:
NSAutolayoutConstraint - Apply constant before multiplier
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)
</code>```

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)
</code>```

Because I end up losing the constraint.constant that comes from the storyboard.

答:
In these images, Purple is the "SuperView" ... Orange is the "OuterView" ... Blue is the "InnerView"

For your use, Purple and Orange will likely have .clear background color.

The Width Constraint of "SuperView" controls the width of its two subviews - in this example, Orange will be -2 of Purple's width, and Blue will be 90% of Orange's width (0.9 multiplier).

"SuperView" is simply set to a Width and Height, and centered in its parent view.

"OuterView" is set Equal Width to its superview (Purple / "SuperView"), with a Constant of -2 (no multiplier)

"InnerView" is set Equal Width to its superview (Orange / "OuterView"), with desired Multiplier - I used 0.9 in this example.

Body:
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)

Because I end up losing the constraint.constant that comes from the storyboard.


问:
How to Style Divs which are not material components angular2 material
I'm using angular2 material in my application. I wish to style my app in material theme. Places where i'm using material components directly(like md-button, md-card), everything is fine. But I'm not sure how to style regular divs using the same theme. I don't want to import any other materialize css. So far, I could find only one class(mat-elevation-z*) which i can use to elevate divs. But i'm not able what all classes are available for me to use.</p>

答:
Here is a link to the different components that can be used: material 2 component docs and this is a link to the Github: github/material2

Hope this helps!


问:
Relations - One to many in Parse
Data Structure in Parse Server:

Objects - objectId:String, userPointer:Pointer, title:String, image:File, description:String, verified:Bool, comments:Relations (relations so that when I click on the comments class it loads associated comments)

Comments - objectId:String, userPointer:Pointer, imagePointer:Pointer, comment:String

I am trying to save a comment to the comments class.
At the same time I need to add the Relation to the Objects Class
 ............with the aim being that when you query the relation, you get all of the comments associated with it.

so far I've tried:

```<code>// Create the comment
    let myComment = PFObject(className:"Comments")
    myComment["comment"] = "kgvhgv"

    // Add a relation between the Post and Comment
    myComment["userPointer"] = PFObject(withoutDataWithClassName: "_User", objectId: "nnnnnnnnn")
    myComment["imagePointer"] = PFObject(withoutDataWithClassName: "Objects", objectId: "nnnnnnnnn")

    let query = PFQuery(className:"Objects")
    query.whereKey("objectId", equalTo: "tJP0kskNxQ")
    query.findObjectsInBackground { (objects, error) -> Void in

        if (error == nil) {

            for object in objects! {
                print(object)
                             var relation = object.relation(forKey: "comments")
                relation.add(myComment)

                relation.saveInBackground(block: { (success:Bool, error:Error?) -> Void in
                    if (success) {
                        print("Saved relation")
                        // The post has been added to the user's likes relation.
                    } else {
                        print(error)
                        // There was a problem, check error.description
                    }

                })
             }
        }
   }

    // This will save both myPost and myComment
    myComment.saveInBackground()

}
</code>```

AND

```<code>let object = PFObject(withoutDataWithClassName: "Objects", objectId: "nnnnnnnnn")

   var relation = object.relationForKey("comment")
relation.addObject(myComment)
m.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The post has been added to the user's likes relation.
  } else {
    // There was a problem, check error.description
  }
}
</code>```

The comment saves with the pointers correctly HOWEVER the relation does not.

All tutorials I can can find are related to saving relations to a User however this is not what I want.

Help greatly appreciated.

答:
.....turns out the fix is to put

```<code>var relation = object.relationForKey("comment")
relation.addObject(myComment)
</code>```

inside the saveInBackGround block!

Title: Relations - One to many in Parse

Body:
Data Structure in Parse Server:

Objects - objectId:String, userPointer:Pointer, title:String, image:File, description:String, verified:Bool, comments:Relations (relations so that when I click on the comments class it loads associated comments)

Comments - objectId:String, userPointer:Pointer, imagePointer:Pointer, comment:String

I am trying to save a comment to the comments class.
At the same time I need to add the Relation to the Objects Class
 ............with the aim being that when you query the relation, you get all of the comments associated with it.

so far I've tried:

// Create the comment
    let myComment = PFObject(className:"Comments")
    myComment["comment"] = "kgvhgv"

    // Add a relation between the Post and Comment
    myComment["userPointer"] = PFObject(withoutDataWithClassName: "_User", objectId: "nnnnnnnnn")
    myComment["imagePointer"] = PFObject(withoutDataWithClassName: "Objects", objectId: "nnnnnnnnn")

    let query = PFQuery(className:"Objects")
    query.whereKey("objectId", equalTo: "tJP0kskNxQ")
    query.findObjectsInBackground { (objects, error) -> Void in

        if (error == nil) {

            for object in objects! {
                print(object)
                             var relation = object.relation(forKey: "comments")
                relation.add(myComment)

                relation.saveInBackground(block: { (success:Bool, error:Error?) -> Void in
                    if (success) {
                        print("Saved relation")
                        // The post has been added to the user's likes relation.
                    } else {
                        print(error)
                        // There was a problem, check error.description
                    }

                })
             }
        }
   }

    // This will save both myPost and myComment
    myComment.saveInBackground()

}

AND

let object = PFObject(withoutDataWithClassName: "Objects", objectId: "nnnnnnnnn")

   var relation = object.relationForKey("comment")
relation.addObject(myComment)
m.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The post has been added to the user's likes relation.
  } else {
    // There was a problem, check error.description
  }
}

The comment saves with the pointers correctly HOWEVER the relation does not.

All tutorials I can can find are related to saving relations to a User however this is not what I want.

Help greatly appreciated.

Body:
.....turns out the fix is to put

var relation = object.relationForKey("comment")
relation.addObject(myComment)

inside the saveInBackGround block!


问:
How to deploy msi through jenkins
i want to deploy MSi through jenkins,can anyone tell me about this how will do it.i have installed MS build plugin,but not sure if this can be
used only to build MSI or deploy as well

thanks
Robinder singh

答:
You can create a command line call and use this for reference:
http://helpnet.installshield.com/installshield21helplib/helplibrary/IHelpCmdLineMSI.htm

Once you have your command working within the particular ISE(powershell) or CMD prompt create a new job and paste the code within one of the build events with the respective execution method selected.

Title: How to deploy msi through jenkins


问:
Simplest CSS equivalent for two-column one-row table?
What is the simplest CSS equivalent for this HTML code:

```<code><table><tr><td>
One<br>
Two
</td><td>
Three<br>
Four
</td></tr></table>
</code>```

Background:

I've been asked to modify an existing website that uses CSS extensively.  My knowledge of CSS is rudimentary at best, but the changes being requested were fairly straightforward, mainly just text edits.  However, one edit involved adding a bullet list that was too long to fit in its assigned area.  I decided to use a table to break it into two lists, but when I input a rudimentary HTML table, it was offset downwards by several lines and displayed in a different font than the rest of the paragraph.  So, is there a way I can make a "table" with CSS that will inherit all the properties of the area (or is DIV the correct term) that it is in?

答:
Perhaps you're looking for something like the example below.

display: flex will align children items side-by-side. By applying flex-grow: 1 to these children, they will grow to equal widths to fit the parent container.

We can also use
 for an unordered list, with each
 representing a bulleted item.

The result is essentially identical to a single-row, two-column table, with a list in either cell.

.table-div {
    display: flex;
}

.table-div > div {
    border: 1px solid black;
    flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table-div">
    <div>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
        </ul>
    </div>
    <div>
        <ul>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </div>
</div></code>```

Body:
What is the simplest CSS equivalent for this HTML code:

One

Two

Three

Four

Background:

I've been asked to modify an existing website that uses CSS extensively.  My knowledge of CSS is rudimentary at best, but the changes being requested were fairly straightforward, mainly just text edits.  However, one edit involved adding a bullet list that was too long to fit in its assigned area.  I decided to use a table to break it into two lists, but when I input a rudimentary HTML table, it was offset downwards by several lines and displayed in a different font than the rest of the paragraph.  So, is there a way I can make a "table" with CSS that will inherit all the properties of the area (or is DIV the correct term) that it is in?

Body:
Perhaps you're looking for something like the example below.

display: flex will align children items side-by-side. By applying flex-grow: 1 to these children, they will grow to equal widths to fit the parent container.

We can also use <ul> for an unordered list, with each <li> representing a bulleted item.

The result is essentially identical to a single-row, two-column table, with a list in either cell.

.table-div {
    display: flex;
}

.table-div > div {
    border: 1px solid black;
    flex-grow: 1;
}

<div class="table-div">
    <div>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
        </ul>
    </div>
    <div>
        <ul>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
    </div>
</div>


问:
Java cannot send email with html with images
I am trying to send email with html which has two images. The two images are sent from the AngularJS client side as base64 strings and looks like:

```<code>data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAALuCAYAAAA9jTxNAAAgAElEQ
</code>```

Note that I have truncated the base64 string as its too long.

```<code>String temp = baseString.split(",")[1];
byte[] tile = DatatypeConverter.parseBase64Binary(temp);

BodyPart messageBodyPart = new MimeBodyPart();
InputStream inputStream = new ByteArrayInputStream(tile);
DataHandler dataHandler = new DataHandler(new InputStreamDataSource(inputStream));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);
</code>```

The InputStreamDataSource:

```<code>public class InputStreamDataSource implements DataSource {

    private InputStream inputStream;

    public InputStreamDataSource(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    public String getContentType() {
        return "*/*";
    }

    public String getName() {
        return "InputStreamDataSource";
    }
}
</code>```

The image does not show up in the mail.

But it works perfectly fine when I use a FileDataSource instead of base64 string:

```<code>    DataSource fds = new FileDataSource("D:\\Projects\\Extras\\sofa1.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");
    multipart.addBodyPart(messageBodyPart);
</code>```

This works fine and shows the images.

Someone please help me fix this.

答:
For anyone else having this issue. I have fixed it using @Bill Shannon's answer. This will set the image src using the base64 string in the html email.

```<code>String temp = base64String.split(",")[1];
byte[] tile = DatatypeConverter.parseBase64Binary(temp);
BodyPart messageBodyPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(tile, "image/png"));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);
</code>```

The html string is something like:

```<code>"<img style=\"height: 100px; width: 100px;\" src=\"cid:image\" alt=\"Tile\" title=\"Tile\">\r\n"
</code>```

Body:
I am trying to send email with html which has two images. The two images are sent from the AngularJS client side as base64 strings and looks like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAALuCAYAAAA9jTxNAAAgAElEQ

Note that I have truncated the base64 string as its too long.

String temp = baseString.split(",")[1];
byte[] tile = DatatypeConverter.parseBase64Binary(temp);

BodyPart messageBodyPart = new MimeBodyPart();
InputStream inputStream = new ByteArrayInputStream(tile);
DataHandler dataHandler = new DataHandler(new InputStreamDataSource(inputStream));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);

The InputStreamDataSource:

public class InputStreamDataSource implements DataSource {

    private InputStream inputStream;

    public InputStreamDataSource(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    public String getContentType() {
        return "*/*";
    }

    public String getName() {
        return "InputStreamDataSource";
    }
}

The image does not show up in the mail.

But it works perfectly fine when I use a FileDataSource instead of base64 string:

    DataSource fds = new FileDataSource("D:\\Projects\\Extras\\sofa1.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");
    multipart.addBodyPart(messageBodyPart);

This works fine and shows the images.

Someone please help me fix this.

Body:
For anyone else having this issue. I have fixed it using @Bill Shannon's answer. This will set the image src using the base64 string in the html email.

String temp = base64String.split(",")[1];
byte[] tile = DatatypeConverter.parseBase64Binary(temp);
BodyPart messageBodyPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(tile, "image/png"));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);

The html string is something like:

"<img style=\"height: 100px; width: 100px;\" src=\"cid:image\" alt=\"Tile\" title=\"Tile\">\r\n"


问:
Is possible to include files (linking) based on a component property?
Delphi 2007/2009 odd question here:

It's possible, based on a component property defined in design-time, to include files in linking or leave them ?

Example: If I leave SomeProperty true, when compiling, the unit SomeUnit will be included into my project. Otherwise it will not be included.

My second approach to this problem is to deploy a second component, which when dropped in the form (or not) will include the unit in uses clause. But if it can be done with a property, that'll be better.

I want to avoid conditional compilation via IFDEF because that forces the component to be built every time the projects are built. Or not?

I am trying to achieve an easy way of including some units in project, and then those units will provide support for specific databases. Having these into an option, at the connection component, will be ideally easy: Check support and that's done. Uncheck, and get some less KBs in your compiled APP.

edit: I'll stay with the component way for instance. I knew the IFDEF method and things, but that forces the component to be built everytime the projects are built. Or not?

I was trying to achieve an easy way of including some units in project, and then that units will provide support for specific databases. Having these into an option, at the connection component, will be ideally easy: Check support and that's done. Uncheck, and get some less KBs in your compiled APP.

答: Your second approach will not necessarily work the way you want it to. While Delphi will helpfully add the necessary unit to your uses list when you drop the component onto the form, it will not remove the unit when you delete the component. And even if you don't use the component or any other exported entitiy from that unit, it is possible that the unit will be linked to your application anyway, when there is code in the initialization or finalization part of the unit. This is unfortunately very often the case, even when it would be possible to initialize stuff on-demand.

OwnerDisplayName: gto

LastEditorDisplayName: Rob Kennedy

OwnerDisplayName: mghie


问:
What is the right way to include Qt headers?
So far I know several ways to #include Qt classes:

#include <QtModule>

This brings all classes of a specific module, for example QDomDocument, QDomElement, QDomNode and numerous others from #include <QtXml>.

#include <QClassName>

This adds declaration of a specific class one may want to use, e.g. QEvent, QStringList, QFile.

#include <qcstyleheader.h>

This has effect of the previous method, except for differently looking header name.

So I wonder, are there any other ways to #include Qt classes? Are they equivalent, or are some of them preferred to others because of some reasons? Does this depend on #include-ing inside a .cpp or a .h file? Does this influence compilation speed and size of the executable?

In short, what is the best way to go?

答: Personally I've found significant benefits (~30% off compile times?) from including all the Qt includes I use in a precompiled header (example), rather than in each .h/.cpp as needed.  Of course the minor downside is, you can lose sight of which bits of Qt your individual source files specifically depend on, but I haven't found this to be a problem myself.</p>


问:
AWS CLI returning "unknown option" on run-instances
Executing query:

aws ec2 run-instances --image-id ami-7a85a01a --security-group-ids sg-756ae512 --count 1 --instance-type t2.micro --tag-specifications ResourceType=instance,Tags=[{Key=webserver,Value=production}] --subnet-id subnet-cc0b0e8a

Its throwing an error saying:

Unknown options: --tag-specifications, ResourceType=instance,Tags=[{Key=webserver,Value=production}]

Does anybody know if this is depricated, or is the syntax different from expected?  I've been running in circles with this.

Possible solution with new syntax:

```<code>aws ec2 run-instances --image-id ami-xxxxxxxxxx  --security-group-ids sg-ef95c791 --count 1 --instance-type m4.2xlarge --key-name mypemkey --query Reservations[*].Instances[*].[PublicIpAddress,InstanceId]
</code>```

The best I can come up with, seems to be working:

aws ec2 run-instances --image-id ami-7a85a01a --count 1 --instance-type t2.micro --key-name mykeypair --subnet-id sn-756ae512 --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=production}]' --associate-public-ip-address --output=text

答:
I ran into this issue today and figured it out after an hour or so of struggling through the infamously horrendous AWS documentation.

The problem was that the installation instructions (pip install and using the bundled installer) are just wrong: though the commands were copied perfectly and the requirements (specifically the "Python 2 version 2.6.5+ or Python 3 version 3.3+") were met, the aws-cli package would never install/update past 1.11.13.

The solution: use pip3 install instead of pip install. This updated it to 1.11.97, which enabled the --tag-specifications parameter. I don't know if this will solve the problem for you, but I suspect many Ubuntu users will experience this, so I decided to post it anyway.

Body:
Executing query:

aws ec2 run-instances --image-id ami-7a85a01a --security-group-ids sg-756ae512 --count 1 --instance-type t2.micro --tag-specifications ResourceType=instance,Tags=[{Key=webserver,Value=production}] --subnet-id subnet-cc0b0e8a

Its throwing an error saying:

Unknown options: --tag-specifications, ResourceType=instance,Tags=[{Key=webserver,Value=production}]

Does anybody know if this is depricated, or is the syntax different from expected?  I've been running in circles with this.

Possible solution with new syntax:

aws ec2 run-instances --image-id ami-xxxxxxxxxx  --security-group-ids sg-ef95c791 --count 1 --instance-type m4.2xlarge --key-name mypemkey --query Reservations[*].Instances[*].[PublicIpAddress,InstanceId]

The best I can come up with, seems to be working:

aws ec2 run-instances --image-id ami-7a85a01a --count 1 --instance-type t2.micro --key-name mykeypair --subnet-id sn-756ae512 --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=production}]' --associate-public-ip-address --output=text


问:
Get list of all instantiated controls in registry
I understand that OpenUI5's has a registry of instantiated controls and can be queried with sap.ui.getCore().byId.

But, is there a way to get a full list of instances in the control registry?

Something like this:

```<code>var aControls = sap.ui.getCore().allControls();
</code>```

答:
There is no currently documented way of obtaining the complete list of elements. The elements are registered in the mElements private map (object) inside the core instance. You can check this object's usages inside the Core source code. It is never exposed directly to the outside world via a method.

Normally, you would be able to simply go around the 'private' access level which is just a convention in JavaScript and just do sap.ui.getCore().mElements, but this will not work in this case. This is because the core is wrapped into an Interface (through a closure) which only holds proxies to the public methods. This implies that you have no way of getting the real core instance from the sap.ui.getCore() call, so you cannot access the mElements property from there.

I don't know any way of obtaining the 'raw' core instance (and normally it should not be possible - the guys at SAP intended to do defensive programming here and not allow users to meddle with the core internals). If you would manage to obtain it through some way, then you could access this 'private' property and obtain the element list (actually, a map between ID and reference).

Body:
I understand that OpenUI5's has a registry of instantiated controls and can be queried with sap.ui.getCore().byId.

But, is there a way to get a full list of instances in the control registry?

Something like this:

var aControls = sap.ui.getCore().allControls();


问:
fadein element on hovering same or other element?
since I think this isn’t a very complex task I searched stackoverflow several times with different searches. but since I don’t really know how to describe the searched solution in a few words all searches failed.

this is a code I use to bring up a navigation when the page loads, fade it out after 4 seconds and fade it back in when hovering the navigation-div – and fading it out when the mouse leaves:

```<code>$(".navigation").delay(4000).fadeTo(1000, 0);
$(".navigation").on({
    mouseleave: function() {
        $(this).delay(200).fadeTo(100, 0);
    },
    mouseenter: function() {
        $(this).stop().fadeTo(100, 1);
    }
});
</code>```

now I am looking for added code that let the navigation fade in while the navigation-div itself OR another div-element is hovered … and fade out the navigation-div when this div itself or the other one is left with the mouse.

can I beef up this code to achieve this or do I need something different?

thank you very much!
matthias

答:
I'll start by sharing an important piece of information that can help you solve this issue: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget

Here you can see that both mouseenter and mouseleave have a relatedTarget property in their event data. It references the "coming from" or "going to" element respectively.

Below I have prototyped a solution where divs A and B act as "connected" in terms of mousein and mouseout.
During mouseenter I only execute the handler if the "coming from" element is neither A nor B.
During mouseleave I only execute the handler if the "going to" element is neither A nor B.

$('.show-navigation').on('mouseenter', function(e) {
  if (!$(e.relatedTarget).hasClass('show-navigation')) {
    console.log('Show Navigation');
  }
});

$('.show-navigation').on('mouseleave', function(e) {
  if (!$(e.relatedTarget).hasClass('show-navigation')) {
    console.log('Hide Navigation');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a" class="show-navigation">Element A</div>
<div id="b" class="show-navigation">Element B</div>
<div id="c">Element C</div></code>```

Body:
since I think this isn’t a very complex task I searched stackoverflow several times with different searches. but since I don’t really know how to describe the searched solution in a few words all searches failed.

this is a code I use to bring up a navigation when the page loads, fade it out after 4 seconds and fade it back in when hovering the navigation-div – and fading it out when the mouse leaves:

$(".navigation").delay(4000).fadeTo(1000, 0);
$(".navigation").on({
    mouseleave: function() {
        $(this).delay(200).fadeTo(100, 0);
    },
    mouseenter: function() {
        $(this).stop().fadeTo(100, 1);
    }
});

now I am looking for added code that let the navigation fade in while the navigation-div itself OR another div-element is hovered … and fade out the navigation-div when this div itself or the other one is left with the mouse.

can I beef up this code to achieve this or do I need something different?

thank you very much!
matthias

Body:
I'll start by sharing an important piece of information that can help you solve this issue: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget

Here you can see that both mouseenter and mouseleave have a relatedTarget property in their event data. It references the "coming from" or "going to" element respectively.

Below I have prototyped a solution where divs A and B act as "connected" in terms of mousein and mouseout.
During mouseenter I only execute the handler if the "coming from" element is neither A nor B.
During mouseleave I only execute the handler if the "going to" element is neither A nor B.

$('.show-navigation').on('mouseenter', function(e) {
  if (!$(e.relatedTarget).hasClass('show-navigation')) {
    console.log('Show Navigation');
  }
});

$('.show-navigation').on('mouseleave', function(e) {
  if (!$(e.relatedTarget).hasClass('show-navigation')) {
    console.log('Hide Navigation');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a" class="show-navigation">Element A</div>
<div id="b" class="show-navigation">Element B</div>
<div id="c">Element C</div>


问:
What am I doing wrong (Simple Announcer Bot on Discord)
Disclaimer; I've never really looked a cold beyond once or twice prior to today.
The base Bot I got is from here;

but I end up with this in cmd prompt when I try to run it:

```<code>C:\Users\aer\Desktop\discordbotjson>node start
C:\Users\aer\Desktop\discordbotjson\start.js:9
    var channel = client.channels.get("name", "general").id;
                  ^

ReferenceError: client is not defined
at Client.<anonymous> (C:\Users\aer\Desktop\discordbotjson\start.js:9:16)
at emitNone (events.js:67:13)
at Client.emit (events.js:166:7)
at WebSocket.websocket.onmessage (C:\Users\aer\Desktop\discordbotjson\node_modules\discord.js\lib\Client\InternalClient.js:1047:13)
at WebSocket.onMessage (C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\WebSocket.js:414:14)
at emitTwo (events.js:87:13)
at WebSocket.emit (events.js:172:7)
at Receiver.ontext (C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\WebSocket.js:797:10)
at C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\Receiver.js:473:18
at Receiver.applyExtensions (C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\Receiver.js:360:5)
</code>```

This is what the start.json looks like:

```<code>var Discord = require("discord.js");
var schedule = require('node-schedule');
var AuthDetails = require("./auth.json");

var bot = new Discord.Client();

bot.on('ready', () => {
// change channel name to name of channel or just set to equal the     channel ID if you already know it.
var channel = client.channels.get("name", "general").id;

var rule = new schedule.RecurrenceRule(); // Creates new Recurrence Rule
rule.minute = 0; // Must set to 0 or scheduled job will run every minute.
rule.hour = [14, 19, 20]; // Hours are based on your system's time.

var j = schedule.scheduleJob(rule, function() {
    bot.channels.get("id", channel).sendMessage("Testing");
})

/* For different announcements:
rule.hour = 8; // Set different time. Use array like above for multiple hours.

var i = schedule.scheduleJob(rule, function() {
    bot.channels.get("id", channel).sendMessage("Announcement at 8AM");
})

// Repeat for more announcements
*/

console.log("Bot is ready.");
});

//login
bot.login(AuthDetails.email, AuthDetails.password);
</code>```

Help would be appreciated, thanks.

答:
```<code>var Discord = require("discord.js");
var schedule = require('node-schedule');
var AuthDetails = require("./auth.json");
var bot = new Discord.Client();

bot.on('ready', () => {
    var channel = bot.channels.get("name", "general").id;

    var rule = new schedule.RecurrenceRule();
    rule.minute = 0;
    rule.hour = [14, 19, 20];

    var j = schedule.scheduleJob(rule, function() {
        bot.channels.get("id", channel).sendMessage("Testing");
    })

    console.log("Bot is ready.");
});

bot.login(AuthDetails.email, AuthDetails.password);
</code>```

Body:
Disclaimer; I've never really looked a cold beyond once or twice prior to today.
The base Bot I got is from here;

but I end up with this in cmd prompt when I try to run it:

C:\Users\aer\Desktop\discordbotjson>node start
C:\Users\aer\Desktop\discordbotjson\start.js:9
    var channel = client.channels.get("name", "general").id;
                  ^

ReferenceError: client is not defined
at Client.<anonymous> (C:\Users\aer\Desktop\discordbotjson\start.js:9:16)
at emitNone (events.js:67:13)
at Client.emit (events.js:166:7)
at WebSocket.websocket.onmessage (C:\Users\aer\Desktop\discordbotjson\node_modules\discord.js\lib\Client\InternalClient.js:1047:13)
at WebSocket.onMessage (C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\WebSocket.js:414:14)
at emitTwo (events.js:87:13)
at WebSocket.emit (events.js:172:7)
at Receiver.ontext (C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\WebSocket.js:797:10)
at C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\Receiver.js:473:18
at Receiver.applyExtensions (C:\Users\aer\Desktop\discordbotjson\node_modules\ws\lib\Receiver.js:360:5)

This is what the start.json looks like:

var Discord = require("discord.js");
var schedule = require('node-schedule');
var AuthDetails = require("./auth.json");

var bot = new Discord.Client();

bot.on('ready', () => {
// change channel name to name of channel or just set to equal the     channel ID if you already know it.
var channel = client.channels.get("name", "general").id;

var rule = new schedule.RecurrenceRule(); // Creates new Recurrence Rule
rule.minute = 0; // Must set to 0 or scheduled job will run every minute.
rule.hour = [14, 19, 20]; // Hours are based on your system's time.

var j = schedule.scheduleJob(rule, function() {
    bot.channels.get("id", channel).sendMessage("Testing");
})

/* For different announcements:
rule.hour = 8; // Set different time. Use array like above for multiple hours.

var i = schedule.scheduleJob(rule, function() {
    bot.channels.get("id", channel).sendMessage("Announcement at 8AM");
})

// Repeat for more announcements
*/

console.log("Bot is ready.");
});

//login
bot.login(AuthDetails.email, AuthDetails.password);

Help would be appreciated, thanks.


问:
Validating date with Spring Boot or Hibernate Validator
I've built a REST Service using Spring Boot. I'm also using Hibernate Validator to validate data. I have a REST endpoint like this:

```<code>@PostMapping(value = "${apiVersion.v_1}" + "/parameter-dates")
    public ResponseEntity createParameterDate( @RequestBody ParameterDate parameterDate){
// Some code that use parameterDate
}
</code>```

ParameterDate is defined in a class like this:

```<code>public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}
</code>```

I would like to validate parameterDateUnadjusted and parameterDateAdjusted to make sure both of them are valid dates. I've tried with @DateTimeFormat(pattern = "yyyy-MM-dd") but it won't give me a validation error for not validate as long as they stick to yyyy-MM-dd. One example would be 2017-01-40 that it just interpret as 2017-02-09. I guess @DateTimeFormat is rather a formatter than a validator. I also tried using Hibernate Validator's @Pattern and rexexp like @Pattern(regexp="\\t(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d\\t"). But this gives me the error

V000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.util.Date'. Check configuration for 'parameterDateAdjusted'

Any suggestion how I can validate these dates?

答:
Here is an example to implement validator for Date object:</p>

```<code>@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyDateValidator.class)
@Documented
public @interface ValidDate {

    String message() default "some message here";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

public class MyDateValidator implements ConstraintValidator<ValidDate, Date> {
   public void initialize(ValidDate constraint) {
   }

   public boolean isValid(Date value, ConstraintValidatorContext context) {
      // validate the value here.
   }
}
</code>```

Body:
I've built a REST Service using Spring Boot. I'm also using Hibernate Validator to validate data. I have a REST endpoint like this:

@PostMapping(value = "${apiVersion.v_1}" + "/parameter-dates")
    public ResponseEntity createParameterDate( @RequestBody ParameterDate parameterDate){
// Some code that use parameterDate
}

ParameterDate is defined in a class like this:

public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}

I would like to validate parameterDateUnadjusted and parameterDateAdjusted to make sure both of them are valid dates. I've tried with @DateTimeFormat(pattern = "yyyy-MM-dd") but it won't give me a validation error for not validate as long as they stick to yyyy-MM-dd. One example would be 2017-01-40 that it just interpret as 2017-02-09. I guess @DateTimeFormat is rather a formatter than a validator. I also tried using Hibernate Validator's @Pattern and rexexp like @Pattern(regexp="\\t(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d\\t"). But this gives me the error

V000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.util.Date'. Check configuration for 'parameterDateAdjusted'

Any suggestion how I can validate these dates?

Body:
Here is an example to implement validator for Date object:

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyDateValidator.class)
@Documented
public @interface ValidDate {

    String message() default "some message here";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

public class MyDateValidator implements ConstraintValidator<ValidDate, Date> {
   public void initialize(ValidDate constraint) {
   }

   public boolean isValid(Date value, ConstraintValidatorContext context) {
      // validate the value here.
   }
}


问:
Extra character added using {#emit SetupSetting("AppId")} in Inno Setup
I'm having problems using the following code, it's adding an extra "{".

For example:

```<code>[Setup]
AppID={{E643099E-1ECE-474F-B043-1E7A7CE405AA}

[Code]
const
  INSTALL_KEY = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\{#emit SetupSetting("AppId")}_is1';
</code>```

Returns the following:

```<code>INSTALL_KEY = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\{{E643099E-1ECE-474F-B043-1E7A7CE405AA}_is1';
</code>```

Which obviously won't work detecting that key with RegKeyExists(HKLM, INSTALL_KEY) because of the extra "{" that isn't in the real path and the script won't compile if you remove the extra character in [Setup] because then it thinks it's a constant.

答:
You could also define your application ID as a constant and use it like this:</p>

```<code>#define MyAppID "{{E643099E-1ECE-474F-B043-1E7A7CE405AA}"

[Setup]
AppId={#MyAppID}

[Code]
const INSTALL_KEY = '...\Uninstall\' + ExpandConstant('{#MyAppID}') + '_is1';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having problems using the following code, it's adding an extra "{".

For example:

[Setup]
AppID={{E643099E-1ECE-474F-B043-1E7A7CE405AA}

[Code]
const
  INSTALL_KEY = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\{#emit SetupSetting("AppId")}_is1';

Returns the following:

INSTALL_KEY = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\{{E643099E-1ECE-474F-B043-1E7A7CE405AA}_is1';

Which obviously won't work detecting that key with RegKeyExists(HKLM, INSTALL_KEY) because of the extra "{" that isn't in the real path and the script won't compile if you remove the extra character in [Setup] because then it thinks it's a constant.

Body:
You could also define your application ID as a constant and use it like this:

#define MyAppID "{{E643099E-1ECE-474F-B043-1E7A7CE405AA}"

[Setup]
AppId={#MyAppID}

[Code]
const INSTALL_KEY = '...\Uninstall\' + ExpandConstant('{#MyAppID}') + '_is1';


问:
Am I being blocked by a website due to some missing parameters?( Scraping with selenium)
The page I'm trying to scrape (for practice) is the url below. I'm trying to scrape the income-statement (chart) on the bottom of the page

```<code>import time

from PIL import Image
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser.quit()
browser = webdriver.PhantomJS()
browser.implicitly_wait(12)
url = 'https://seekingalpha.com/symbol/OPK/financials/income-statement'

browser.get(url)
time.sleep(9)
#x =browser.find_element_by_class_name('content')
y =browser.find_element_by_xpath("//*[@id='industrial-income-statement']")
</code>```

This code was working just a little while ago; now I"m getting a "No such element" error, for this line  y =browser.find_element_by_xpath("//*[@id='industrial-income-statement']")

If I type browser.page_source:

There is something about access being denied, but I'm not exactly sure why.
I'm only trying to scrape one chart, and I'm using Selenium which I assumed has the appropriate headers.

'0px 25px; padding: 0px; resize: none; "></textarea>

\n
\n            Access to this page has been denied because we believe you are using automation tools to browse the website.\n
\n
\n            This may happen as a result of the following:\n
\n
\n
\n              Javascript is disabled or blocked by an extension (ad blockers for example)\n
\n
\n              Your browser does not support cookies\n
\n
\n
\n            Please make sure that Javascript and cookies are enabled on your browser and that you are not blocking them from loading.\n
\n
\n            Reference ID: #a2a7fe90-4a2a-11e7-be16-a994e7f2d3b8\n
\n
\n
\n
\n        <div class="page-foote

PhantomJS doesn't block Javascript nor block cookies as far as I know.

Is there a way around this?

答:
You should pretend not to be PhantomJS to avoid being detected:

```<code>capabilities = dict(webdriver.DesiredCapabilities.PHANTOMJS)
capabilities["phantomjs.page.settings.userAgent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"

browser = webdriver.PhantomJS(desired_capabilities=capabilities)
</code>```

I would though be careful about scraping this resource without an explicit consent - check out Terms of Use - the "User Conduct" section.

Body:
The page I'm trying to scrape (for practice) is the url below. I'm trying to scrape the income-statement (chart) on the bottom of the page

import time

from PIL import Image
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
browser.quit()
browser = webdriver.PhantomJS()
browser.implicitly_wait(12)
url = 'https://seekingalpha.com/symbol/OPK/financials/income-statement'

browser.get(url)
time.sleep(9)
#x =browser.find_element_by_class_name('content')
y =browser.find_element_by_xpath("//*[@id='industrial-income-statement']")

This code was working just a little while ago; now I"m getting a "No such element" error, for this line  y =browser.find_element_by_xpath("//*[@id='industrial-income-statement']")

If I type browser.page_source:

There is something about access being denied, but I'm not exactly sure why.
I'm only trying to scrape one chart, and I'm using Selenium which I assumed has the appropriate headers.

'0px 25px; padding: 0px; resize: none; "></textarea>

\n
\n            Access to this page has been denied because we believe you are using automation tools to browse the website.\n
\n
\n            This may happen as a result of the following:\n
\n
\n
\n              Javascript is disabled or blocked by an extension (ad blockers for example)\n
\n
\n              Your browser does not support cookies\n
\n
\n
\n            Please make sure that Javascript and cookies are enabled on your browser and that you are not blocking them from loading.\n
\n
\n            Reference ID: #a2a7fe90-4a2a-11e7-be16-a994e7f2d3b8\n
\n
\n
\n
\n        <div class="page-foote

PhantomJS doesn't block Javascript nor block cookies as far as I know.

Is there a way around this?

Body:
You should pretend not to be PhantomJS to avoid being detected:

capabilities = dict(webdriver.DesiredCapabilities.PHANTOMJS)
capabilities["phantomjs.page.settings.userAgent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"

browser = webdriver.PhantomJS(desired_capabilities=capabilities)

I would though be careful about scraping this resource without an explicit consent - check out Terms of Use - the "User Conduct" section.


问:
login variable disappeared from AWSCognitoCredentialsProvider class
I am looking at this Amazon official documentation:

https://aws.amazon.com/blogs/mobile/using-amazon-cognito-with-swift-sample-app-developer-guide-and-more/

In this example code there is a variable callaed logins as part of AWSCognitoCredentialsProvider. Unfortunately, when I try to implement this in my app the logins variable does not exist anymore. I checked the class definition and it is not there. Anyone has an idea on how to get this back?

```<code>let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YOUR_IDENTITY_POOL_ID")
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)

AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

let token = FBSDKAccessToken.currentAccessToken().tokenString
credentialsProvider.logins = [AWSCognitoLoginProviderKey.Facebook.rawValue: token]
</code>```

答:
That API was removed as part of the 2.5.0 release. Changelog

The new API from AWSCognitoCredentialsProvider is:

```<code>- (void)setIdentityProviderManagerOnce:(id<AWSIdentityProviderManager>)identityProviderManager;
</code>```

AWSIdentityProviderManager:

```<code>@protocol AWSIdentityProviderManager <NSObject>

/**
 Each entry in logins represents a single login with an identity provider. The key is the domain of the login provider (e.g. 'graph.facebook.com') and the value is the OAuth/OpenId Connect token that results from an authentication with that login provider.
 */
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins;

@optional
/**
 * If the token contains the role arn and there are multiple roles, return the custom role to assume.  This is currently only supported for SAML identity providers.
 */
@property (nonatomic, readonly) NSString *customRoleArn;

@end
</code>```

Body:
I am looking at this Amazon official documentation:

https://aws.amazon.com/blogs/mobile/using-amazon-cognito-with-swift-sample-app-developer-guide-and-more/

In this example code there is a variable callaed logins as part of AWSCognitoCredentialsProvider. Unfortunately, when I try to implement this in my app the logins variable does not exist anymore. I checked the class definition and it is not there. Anyone has an idea on how to get this back?

let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: "YOUR_IDENTITY_POOL_ID")
let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider)

AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

let token = FBSDKAccessToken.currentAccessToken().tokenString
credentialsProvider.logins = [AWSCognitoLoginProviderKey.Facebook.rawValue: token]

Body:
That API was removed as part of the 2.5.0 release. Changelog

The new API from AWSCognitoCredentialsProvider is:

- (void)setIdentityProviderManagerOnce:(id<AWSIdentityProviderManager>)identityProviderManager;

AWSIdentityProviderManager:

@protocol AWSIdentityProviderManager <NSObject>

/**
 Each entry in logins represents a single login with an identity provider. The key is the domain of the login provider (e.g. 'graph.facebook.com') and the value is the OAuth/OpenId Connect token that results from an authentication with that login provider.
 */
- (AWSTask<NSDictionary<NSString *, NSString *> *> *)logins;

@optional
/**
 * If the token contains the role arn and there are multiple roles, return the custom role to assume.  This is currently only supported for SAML identity providers.
 */
@property (nonatomic, readonly) NSString *customRoleArn;

@end


问:
Howto Cancel Async Download of one file witihn mutiple file downloads?
i use some code to download mutiple files, which works good.
while downloading a lot of files, i would like to be able to cancel them.
Besides the UI with a cancel button i use as global variables:

```<code>private WebClient client = null;
private CancellationToken cts = new CancellationToken();
</code>```

Within the download function i use:

```<code>// The Object SourceId is only used to be able
// to pass the ID (index) of datasource to callback functions
var current = new SourceId();
current.Id = sourceList.IndexOf(current);
cts = new CancellationToken();
//i tried to use (cancellationToken.Register(() => webClient.CancelAsync())
using (client = new WebClient())
using (cts.Register(() => wc_Cancel()))
{
   client.DownloadProgressChanged += wc_DownloadProgressChanged;
   client.DownloadFileCompleted += wc_DownloadFileCompleted;
   client.DownloadFileAsync(new Uri(driver.Filelink), targetFile, current);
}
</code>```

"current" is an object, which contains the source ID of the original Datasource, which i use within wc_DownloadProgressChanged and wc_DownloadFileCompleted to determine the correct Data from my datasource.

Within the function wc_DownloadFileCompleted i use if (e.Cancelled) to determine if the download was canceled.

I try to cancel a specific Download. The cancelDownload Function is called by a button after getting the corresponding source Id.

How can i cancel one specificed async download, which means how to pass the needed argument for cancel function ??

```<code>    private void cancelDownload(int id)
    {
        // Here i would like to send the ID to cancel to specific download
        // and wait for it to finish. How can i do this ?
        wc_Cancel();
    }

    public virtual void wc_Cancel()
    {
        if (this.client != null)
            this.client.CancelAsync();
    }
</code>```

How can i achieve that ?

答:
finally i found a solution for this. For those with the same problem here is my solution.

The use of the CancellationToken is not necessary to get this work. Also the functions cancelDownload and wc_Cancel are not needed. I use a download class, with all needed informations like FileLink, Name etc. I did expand that class with these properties:

```<code>// HelperClass to pass for callbacks
public class DownId
{
   public int Id { get; set; }
}

// DownloadClass with all needed properties. Should be expanded for your needs.
public class Downloads
{
    public Driver()
    {
    }
    public string Title { get; set; }
    public string Filelink { get; set; }
    public string FileName { get; set; }
    public bool IsCanceling { get; set; }
    public WebClient Client { get; set; }
    public int Retry { get; set; }
    public int Progress { get; set; }
    public long valBytesRec { get; set; }
    public long valBytesTotal { get; set; }
}
</code>```

The Class now contains a property for the WebClient and bool parameter for canceling. A global Variable downloadlist of type List<Downloads> is used to access the needed properties within all functions.

In the download function I use a parameter currentdriver, which is the indexnumber of the current download within the list (used as paramter for download):

```<code>DownId currentSourceId = new DownId();
currentSourceId.Id = currentdriver;
using (downloadlist[current].Client = new WebClient())
{
    downloadlist[current].Client.DownloadProgressChanged += wc_DownloadProgressChanged;
    downloadlist[current].Client.DownloadFileCompleted += wc_DownloadFileCompleted;
    downloadlist[current].Client.DownloadFileAsync(new Uri(driver.Filelink), targetFile, currentSourceId);
}
</code>```

To be able to pass the currentdrive to the DownloadFileAsync, it must be used within an object. for this purpose is the DownId Class is used.
This way every download will use its own WebClient, which can be access quite easy.

For canceling it is only necessary to set the IsCanceling property within the button_Click event handler:

```<code>driverlist[currentdriver].IsCanceling = true;
</code>```

In the wc_DownloadProgressChanged, I use this code to determine, if Canceling is necessary:

```<code>var currentDriver = e.UserState as DownId;
if (downloadlist[current].IsCanceling)
{
    downloadlist[current].IsCanceling = false;
    downloadlist[current].Client.CancelAsync();
}
else
{
  //Update progress etc.
  // beware of not using UI Elements here, caused UI Lags
  // and can be a problem within threads
  // if necessary use  Invoke(new MethodInvoker(delegate {  ...}));
}
</code>```

Hope this helps.. I did search for quite a while to find a solution.

Body:
i use some code to download mutiple files, which works good.
while downloading a lot of files, i would like to be able to cancel them.
Besides the UI with a cancel button i use as global variables:

private WebClient client = null;
private CancellationToken cts = new CancellationToken();

Within the download function i use:

// The Object SourceId is only used to be able
// to pass the ID (index) of datasource to callback functions
var current = new SourceId();
current.Id = sourceList.IndexOf(current);
cts = new CancellationToken();
//i tried to use (cancellationToken.Register(() => webClient.CancelAsync())
using (client = new WebClient())
using (cts.Register(() => wc_Cancel()))
{
   client.DownloadProgressChanged += wc_DownloadProgressChanged;
   client.DownloadFileCompleted += wc_DownloadFileCompleted;
   client.DownloadFileAsync(new Uri(driver.Filelink), targetFile, current);
}

"current" is an object, which contains the source ID of the original Datasource, which i use within wc_DownloadProgressChanged and wc_DownloadFileCompleted to determine the correct Data from my datasource.

Within the function wc_DownloadFileCompleted i use if (e.Cancelled) to determine if the download was canceled.

I try to cancel a specific Download. The cancelDownload Function is called by a button after getting the corresponding source Id.

How can i cancel one specificed async download, which means how to pass the needed argument for cancel function ??

    private void cancelDownload(int id)
    {
        // Here i would like to send the ID to cancel to specific download
        // and wait for it to finish. How can i do this ?
        wc_Cancel();
    }

    public virtual void wc_Cancel()
    {
        if (this.client != null)
            this.client.CancelAsync();
    }

How can i achieve that ?

Body:
finally i found a solution for this. For those with the same problem here is my solution.

The use of the CancellationToken is not necessary to get this work. Also the functions cancelDownload and wc_Cancel are not needed. I use a download class, with all needed informations like FileLink, Name etc. I did expand that class with these properties:

// HelperClass to pass for callbacks
public class DownId
{
   public int Id { get; set; }
}

// DownloadClass with all needed properties. Should be expanded for your needs.
public class Downloads
{
    public Driver()
    {
    }
    public string Title { get; set; }
    public string Filelink { get; set; }
    public string FileName { get; set; }
    public bool IsCanceling { get; set; }
    public WebClient Client { get; set; }
    public int Retry { get; set; }
    public int Progress { get; set; }
    public long valBytesRec { get; set; }
    public long valBytesTotal { get; set; }
}

The Class now contains a property for the WebClient and bool parameter for canceling. A global Variable downloadlist of type List<Downloads> is used to access the needed properties within all functions.

In the download function I use a parameter currentdriver, which is the indexnumber of the current download within the list (used as paramter for download):

DownId currentSourceId = new DownId();
currentSourceId.Id = currentdriver;
using (downloadlist[current].Client = new WebClient())
{
    downloadlist[current].Client.DownloadProgressChanged += wc_DownloadProgressChanged;
    downloadlist[current].Client.DownloadFileCompleted += wc_DownloadFileCompleted;
    downloadlist[current].Client.DownloadFileAsync(new Uri(driver.Filelink), targetFile, currentSourceId);
}

To be able to pass the currentdrive to the DownloadFileAsync, it must be used within an object. for this purpose is the DownId Class is used.
This way every download will use its own WebClient, which can be access quite easy.

For canceling it is only necessary to set the IsCanceling property within the button_Click event handler:

driverlist[currentdriver].IsCanceling = true;

In the wc_DownloadProgressChanged, I use this code to determine, if Canceling is necessary:

var currentDriver = e.UserState as DownId;
if (downloadlist[current].IsCanceling)
{
    downloadlist[current].IsCanceling = false;
    downloadlist[current].Client.CancelAsync();
}
else
{
  //Update progress etc.
  // beware of not using UI Elements here, caused UI Lags
  // and can be a problem within threads
  // if necessary use  Invoke(new MethodInvoker(delegate {  ...}));
}

Hope this helps.. I did search for quite a while to find a solution.


问:
customize JMenuBar (e.g. BackgroundImage, highlighting color,...)
I'd like to adapt/customize the appearance of my JMenuBar, so i do a little research. Now i wondering why there are so little information about this issue?!

I just found one good source here: http://forums.sun.com thread.jspa?messageID=4457769#4457769 which allows me to use a BackgroundImage for the MenuBar. The drawback is that i have to create such things like rollover effect (highlight BackgroundColor of JMenuItems), calculation of the jmenu positions by myself.

Did anyone of you knows a better, easier way to approach my goal? All i'd like to do is to customize the background of the JMenuBar by displaying a image instead of a plain color. Further the rollover-Effekts and the normal behaviour of a menu should be obtained.

答:
try something like this for jmenu positioning:

```<code>menuBar.setLayout(null);
openMenu.setBounds(pos_x,pos_y,width,height);
menuBar.add(openMenu);
</code>```

I am also trying to change the background color,but still didnt find any way. :(

OwnerDisplayName: huxendupsel

Body:
try something like this for jmenu positioning:

menuBar.setLayout(null);
openMenu.setBounds(pos_x,pos_y,width,height);
menuBar.add(openMenu);

I am also trying to change the background color,but still didnt find any way. :(


问:
Using the format function to name columns
The line of code below takes columns that represent each months total sales and averages the sales by quarter.

```<code>mdf = tdf[sel_cols].resample('3M',axis=1).mean()
</code>```

What I need to do is title the columns with a str (cannot use pandas .Period function).

I attempting to use the following code, but I cannot get it to work.

```<code>mdf = tdf[sel_cols].resample('3M',axis=1).mean().rename(columns=lambda x: '{:}q{:}'.format(x.year, [1, 2, 3, 4][x.quarter==1]))
</code>```

I want the columns to read... 2000q1, 2000q2, 2000q3, 2000q4, 2001q1,... etc, but keep getting wrong things like 2000q1, 2000q1, 2000q1, 2000q2, 2001q1.

How can I use the .format function to make this work properly.

答:
The easiest way is to perform the quarter function on the datetime list like so</p>

```<code>mdf = tdf[sel_cols].resample('3M',axis=1).mean().rename(columns=lambda x: '{:}q{:}'.format(x.year,x.quarter))
</code>```

Body:
The line of code below takes columns that represent each months total sales and averages the sales by quarter.

mdf = tdf[sel_cols].resample('3M',axis=1).mean()

What I need to do is title the columns with a str (cannot use pandas .Period function).

I attempting to use the following code, but I cannot get it to work.

mdf = tdf[sel_cols].resample('3M',axis=1).mean().rename(columns=lambda x: '{:}q{:}'.format(x.year, [1, 2, 3, 4][x.quarter==1]))

I want the columns to read... 2000q1, 2000q2, 2000q3, 2000q4, 2001q1,... etc, but keep getting wrong things like 2000q1, 2000q1, 2000q1, 2000q2, 2001q1.

How can I use the .format function to make this work properly.

Body:
The easiest way is to perform the quarter function on the datetime list like so

mdf = tdf[sel_cols].resample('3M',axis=1).mean().rename(columns=lambda x: '{:}q{:}'.format(x.year,x.quarter))


问:
GRAILS - How to start using Twitter Bootstrap in Grails 3.2.9 and what's the best way to do it?
What's the way to use Bootstrap in Grails 3.2.9? How to start? Should I use any plugins?</p>

答:
You can use webjars

build.grade

```<code>dependencies {
    ...
    compile "org.webjars:bootstrap:3.3.5"
}
</code>```

grails-app\stylesheets\application.css

```<code>*= require /webjars/bootstrap/3.3.5/css/bootstrap
</code>```

grails-app\javascripts\application.js

```<code>//= require /webjars/bootstrap/3.3.5/js/bootstrap.min
</code>```

Body:
You can use webjars

build.grade

dependencies {
    ...
    compile "org.webjars:bootstrap:3.3.5"
}

grails-app\stylesheets\application.css

*= require /webjars/bootstrap/3.3.5/css/bootstrap

grails-app\javascripts\application.js

//= require /webjars/bootstrap/3.3.5/js/bootstrap.min


问:
Call a Webservice from Visual Studio with an existing XML-file/string
How can I call an existing webservice (somewhere) from Microsoft Visual Studio 2008 (C#) with only a valid xml-string/file?

I receive these xml-files from another system and this system can not call directly this webservice. These xml-files are 100% ok, but I want to know how to make the code.

Do I need to make the proxy classes?

答:
I've used the Webrequest-method and fill the soap-message with the received xml-string and
send it to the webservice.

So my question can be closed.


问:
Repeat state until it doesn't change / is stable
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

```<code>Eq s => State s () -> State s ()
</code>```

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

答:
You can roll-your-own higher level recursive transform, using get and unless

```<code>untilStable :: Eq s => State s () -> State s ()
untilStable stateTransform = do
  before <- get
  stateTransform
  after <- get
  unless (before == after) $ untilStable stateTransform
</code>```

Body:
I'm trying to run a state transform repeatedly until the state doesn't change. I've searched Hoogle for

Eq s => State s () -> State s ()

but found nothing that looks appropriate.

How can I run a state transform repeatedly until it doesn't change?

Body:
You can roll-your-own higher level recursive transform, using get and unless

untilStable :: Eq s => State s () -> State s ()
untilStable stateTransform = do
  before <- get
  stateTransform
  after <- get
  unless (before == after) $ untilStable stateTransform


问:
How to extract a certain amount of char from a long string until the end of the string
Lets say I have the following string:

1111000011001101

How can I extract substrings of 4 chars until the end of the string so that I have the following array ?

```<code>|1111|0000|1100|1101|
</code>```

答:
Because Strings are only char[]'s you can use the String.Substring(int a, int b) method to retrieve the number of characters specified (int b) from a character position in the string (int a).

If you wanted the first four characters of your string you could use

```<code>String s = "1111000011001101";
String firstFourChars = s.Substring(0,4);
</code>```

Body:
Lets say I have the following string:

1111000011001101

How can I extract substrings of 4 chars until the end of the string so that I have the following array ?

|1111|0000|1100|1101|

Body:
Because Strings are only char[]'s you can use the String.Substring(int a, int b) method to retrieve the number of characters specified (int b) from a character position in the string (int a).

If you wanted the first four characters of your string you could use

String s = "1111000011001101";
String firstFourChars = s.Substring(0,4);


问:
testfixtures.StringComparison does not allow regex flags
I'm trying to capture logs for testing purpose and matching it through regex using testfixtures module from python for that and doing logging through logging module.

Here's the replica of what is actually happening essentially:

```<code>import logging, traceback
from testfixtures import LogCapture, StringComparison

exception = None
try:
    raise Exception('test exception')
except Exception as ex:
    exception = ex

traceback_str = '\n'.join(traceback.format_exception(type(exception), exception, exception.__traceback__))

with LogCapture() as capture:
    logging.info(traceback_str)
capture.check(('root', 'INFO', StringComparison(r'.*test exception.*')))
</code>```

But this code gives error and does not match. And I'm not able to put re.DOTALL flag to consider . in regex as new line character also, as it is giving error on number of parameters of StringComparison.

Right now, as a workaround, I'm using the following regex:

```<code>capture.check(('root', 'INFO', StringComparison(r'(.*\n)*.*test exception.*'))
</code>```

Is there any other way of providing flags to compare captured logs, or check logs using different function ?

答:
You may use inline modifier version (?s) that is equal to passing a re.DOTALL / re.S flags to the regex engine:

```<code>r'(?s).*test exception.*'
</code>```

See re documentation:

(?aiLmsux)

  (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.

Body:
I'm trying to capture logs for testing purpose and matching it through regex using testfixtures module from python for that and doing logging through logging module.

Here's the replica of what is actually happening essentially:

import logging, traceback
from testfixtures import LogCapture, StringComparison

exception = None
try:
    raise Exception('test exception')
except Exception as ex:
    exception = ex

traceback_str = '\n'.join(traceback.format_exception(type(exception), exception, exception.__traceback__))

with LogCapture() as capture:
    logging.info(traceback_str)
capture.check(('root', 'INFO', StringComparison(r'.*test exception.*')))

But this code gives error and does not match. And I'm not able to put re.DOTALL flag to consider . in regex as new line character also, as it is giving error on number of parameters of StringComparison.

Right now, as a workaround, I'm using the following regex:

capture.check(('root', 'INFO', StringComparison(r'(.*\n)*.*test exception.*'))

Is there any other way of providing flags to compare captured logs, or check logs using different function ?

Body:
You may use inline modifier version (?s) that is equal to passing a re.DOTALL / re.S flags to the regex engine:

r'(?s).*test exception.*'

See re documentation:

(?aiLmsux)

  (One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.


问:
C# How can I use HashSet values with ListBox?
I'm currently working on a tournament manager for M.U.G.E.N. It reads the fighters from a SQL Server datatable and stores the rows in a ListBox. It should also randomly pick 16 fighters from it.

I've already created a Random generator and a HashSet - to prevent any duplicates - inside a while loop, so this process only stops, when 16 fighters have been picked. This is what I've written so far:

```<code>private void buttonRandom_Click(object sender, EventArgs e)
        /*
         * Randomly pick 16 fighters from the "Registered" ListBox
         * Only unique IDs are allowed
         */
    {
        Random contestantPicker = new Random();
        HashSet<int> fighters = new HashSet<int>();
        while (fighters.Count < 16) // Run Random until 16 fighters have been picked
        {
            fighters.Add(contestantPicker.Next(0, listBoxRegistered.Items.Count));
        }
    }
</code>```

Now the question is: How can I use the numbers stored in a HashSet to copy items with their corresponding indices from one ListBox to another ListBox?

答:
After generating your HashSet, iterate through it and find corresponding items by their index.

Like this:

```<code>//old code
Random contestantPicker = new Random();
HashSet<int> fighters = new HashSet<int>();
while (fighters.Count < 16) // Run Random until 16 fighters have been picked
{
    fighters.Add(contestantPicker.Next(0, listBoxRegistered.Items.Count));
}

//list to hold fighter names
List<string> fightersList = new List<string>();

//iterate through all indexes in hashset
for (int i = 0; i < fighters.Count; i++)
{
    //show in output window
    Diagnostics.Debug.WriteLine("figther number {0}, named: {1}", i + 1, listBoxRegistered.GetItemText(listBoxRegistered.Items[fighters.ElementAt(i)]));

    //add fighters to list...
    fightersList.Add(listBoxRegistered.GetItemText(listBoxRegistered.Items[fighters.ElementAt(i)]));
}

//... and show it in some message box
MessageBox.Show(string.Join(", ", fightersList.ToArray()));
</code>```

Body:
I'm currently working on a tournament manager for M.U.G.E.N. It reads the fighters from a SQL Server datatable and stores the rows in a ListBox. It should also randomly pick 16 fighters from it.

I've already created a Random generator and a HashSet - to prevent any duplicates - inside a while loop, so this process only stops, when 16 fighters have been picked. This is what I've written so far:

private void buttonRandom_Click(object sender, EventArgs e)
        /*
         * Randomly pick 16 fighters from the "Registered" ListBox
         * Only unique IDs are allowed
         */
    {
        Random contestantPicker = new Random();
        HashSet<int> fighters = new HashSet<int>();
        while (fighters.Count < 16) // Run Random until 16 fighters have been picked
        {
            fighters.Add(contestantPicker.Next(0, listBoxRegistered.Items.Count));
        }
    }

Now the question is: How can I use the numbers stored in a HashSet to copy items with their corresponding indices from one ListBox to another ListBox?

Body:
After generating your HashSet, iterate through it and find corresponding items by their index.

Like this:

//old code
Random contestantPicker = new Random();
HashSet<int> fighters = new HashSet<int>();
while (fighters.Count < 16) // Run Random until 16 fighters have been picked
{
    fighters.Add(contestantPicker.Next(0, listBoxRegistered.Items.Count));
}

//list to hold fighter names
List<string> fightersList = new List<string>();

//iterate through all indexes in hashset
for (int i = 0; i < fighters.Count; i++)
{
    //show in output window
    Diagnostics.Debug.WriteLine("figther number {0}, named: {1}", i + 1, listBoxRegistered.GetItemText(listBoxRegistered.Items[fighters.ElementAt(i)]));

    //add fighters to list...
    fightersList.Add(listBoxRegistered.GetItemText(listBoxRegistered.Items[fighters.ElementAt(i)]));
}

//... and show it in some message box
MessageBox.Show(string.Join(", ", fightersList.ToArray()));


问:
Starting second javascript when the first one is finished
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:  </p>

```<code>HTML:
<form method ="post">
    <input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>

Javascript:
<script>
function move() {
    var elem = document.getElementById("myBar");
    var myFunc01 = function() {
    var i = 1;
    while (i < 101) {
        (function(i) {
            setTimeout(function() {
                i++;
                elem.style.width = i + '%';
                elem.innerHTML = i + '%';
            }, 600 * i)
        })(i++)
    }
    };
    myFunc01();
}
</script>
<script>
function finalize() {
    var elem = document.getElementById("myBar");
    var myFunc02 = function() {
                elem.innerHTML = 'Finalizing...';
    };
    setTimeout(myFunc02, 600);
}
</script>
</code>```

答:
var elem = document.querySelector('#myBar');

function done() {
  elem.innerText = 'UPLOAD HAS FINISHED';
}

var upload = function(callback) {

  var width = 1;
  var id;

  var frame = function() {
    if (width >= 100) {
      clearInterval(id);
      callback();
    } else {
      width++;
      elem.style.width = width + '%';
    }
  };

  id = setInterval(frame, 10);
};

/*
upload(function() {
  elem.innerText = 'UPLOAD HAS FINISHED';
});
*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: green;
  text-align: center;
  line-height: 27px;
}</code>```

<button onclick="upload(done)">START UPLOAD</button>

```

Body:
I'm working on a progress bar. It has a label. I want to adjust that label a certain script is finished. After finding some answers of probable solution, I came up with the following script. The first initiates and works as expected. However, the second one doesn't. What's wrong with it? Here's the code:

HTML:
<form method ="post">
    <input class=generate type="submit" value="Upload" onclick="move();finalize()"/>
</form>

Javascript:

Body:
var elem = document.querySelector('#myBar');

function done() {
  elem.innerText = 'UPLOAD HAS FINISHED';
}

var upload = function(callback) {

  var width = 1;
  var id;

  var frame = function() {
    if (width >= 100) {
      clearInterval(id);
      callback();
    } else {
      width++;
      elem.style.width = width + '%';
    }
  };

  id = setInterval(frame, 10);
};

/*
upload(function() {
  elem.innerText = 'UPLOAD HAS FINISHED';
});
*/

#myProgress {
  width: 100%;
  background-color: grey;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: green;
  text-align: center;
  line-height: 27px;
}

<button onclick="upload(done)">START UPLOAD</button>

<div id="myProgress">
  <div id="myBar"></div>
</div>


问:
make app without of multitasking support
my application should not support multitasking , is there any to force app without multitasking support ? </p>

答: Just call applicationWillTerminate in your applicationDidEnterBackground method of your application's delegate. Then the home button will have the same effect as it did on iOS versions prior to 4.0, without multitasking.