问:
Internal table isn't modified from table control
I have an table control (ctrl) and an internal table (snctab).
I want to add items snctab from the table control. I can add but not modify a record from snctab. Here are my PBO and PAI modules:

```<code>PROCESS BEFORE OUTPUT.
    MODULE status_0100.

    LOOP AT snctab WITH CONTROL ctrl CURSOR ctrl-current_line.
    ENDLOOP.

PROCESS AFTER INPUT.

    LOOP AT snctab.
        MODULE update.
    ENDLOOP.

    MODULE user_command_0100.

    MODULE update INPUT.    "my update module
        READ TABLE snctab INDEX ctrl-current_line.
        IF sy-subrc <> 0.
            APPEND snctab.
        ELSE.
            MODIFY snctab INDEX ctrl-current_line.
        ENDIF.
    ENDMODULE.                 " UPDATE  INPUT
</code>```

答: Your LOOP statement in the PAI module does not take the table control into account - you are using an obsolete variant that was used to process step loops there. Check the demo program DEMO_DYNPRO_TABCONT_LOOP in your system to see a working example.

Body:
I have an table control (ctrl) and an internal table (snctab).
I want to add items snctab from the table control. I can add but not modify a record from snctab. Here are my PBO and PAI modules:

PROCESS BEFORE OUTPUT.
    MODULE status_0100.

    LOOP AT snctab WITH CONTROL ctrl CURSOR ctrl-current_line.
    ENDLOOP.

PROCESS AFTER INPUT.

    LOOP AT snctab.
        MODULE update.
    ENDLOOP.

    MODULE user_command_0100.

    MODULE update INPUT.    "my update module
        READ TABLE snctab INDEX ctrl-current_line.
        IF sy-subrc <> 0.
            APPEND snctab.
        ELSE.
            MODIFY snctab INDEX ctrl-current_line.
        ENDIF.
    ENDMODULE.                 " UPDATE  INPUT


来源: stackexchange

问:
Center image using text-align center?
Is the property text-align: center; a good way to center an image using CSS?

```<code>img {
    text-align: center;
}
</code>```

答:
I discovered that if I have an image and some text inside a div, then I can use text-align:center to align the text and the image in one swoop.

HTML:

```<code>    <div class="picture-group">
        <h2 class="picture-title">Picture #1</h2>
        <img src="http://lorempixel.com/99/100/" alt="" class="picture-img" />
        <p class="picture-caption">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus sapiente fuga, quia?</p>
    </div>
</code>```

CSS:

```<code>.picture-group {
  border: 1px solid black;
  width: 25%;
  float: left;
  height: 300px;
  #overflow:scroll;
  padding: 5px;
  text-align:center;
}
</code>```

CodePen:
https://codepen.io/artforlife/pen/MoBzrL?editors=1100

ContentLicense: CC BY-SA 3.0

Title: Center image using text-align center?

Body:
Is the property text-align: center; a good way to center an image using CSS?

img {
    text-align: center;
}

Body:
I discovered that if I have an image and some text inside a div, then I can use text-align:center to align the text and the image in one swoop.

HTML:

    <div class="picture-group">
        <h2 class="picture-title">Picture #1</h2>
        <img src="http://lorempixel.com/99/100/" alt="" class="picture-img" />
        <p class="picture-caption">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus sapiente fuga, quia?</p>
    </div>

CSS:

.picture-group {
  border: 1px solid black;
  width: 25%;
  float: left;
  height: 300px;
  #overflow:scroll;
  padding: 5px;
  text-align:center;
}

CodePen:
https://codepen.io/artforlife/pen/MoBzrL?editors=1100


问:
MySQL UNION not working
I'm attempting a mysql union but nothing is returned?  Below is an example.  In total there is 16 select queries

```<code>$url_array = array(
   "euro-gbp","euro-aud","euro-usd",
   "euro-jpy","gbp-jpy","euro-cad",
   "usd-cad","usd-jpy","cad-jpy",
   "gbp-usd","aud-usd","gbp-cad",
   "aud-cad","aud-jpy","aud-nzd",
   "euro-nzd","gbp-aud","gbp-nzd",
   "nzd-usd","nzd-cad","nzd-jpy");

foreach($url_array as $urls) {
   $sql[]= "SELECT *
     FROM `data_analysis_child`
     WHERE type='".$urls."'
     ORDER BY id DESC
     LIMIT 2";

}

$sql = implode(" UNION ",$sql);
</code>```

The sql result

```<code>SELECT * FROM `data_analysis_child` WHERE type='euro-gbp' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='cad-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-jpy' ORDER BY id DESC LIMIT 2
</code>```

How do i solve?  Is there a better way to restructure this query?

答:
if you need  order by and limit for each select you should use ()  around each select  </p>

```<code>  foreach($url_array as $urls) {
        $sql[]= " (  SELECT * FROM `data_analysis_child` WHERE type='".$urls."' ORDER BY id DESC LIMIT 2  )";
        break;
    }
</code>```

Title: MySQL UNION not working

Body:
I'm attempting a mysql union but nothing is returned?  Below is an example.  In total there is 16 select queries

$url_array = array(
   "euro-gbp","euro-aud","euro-usd",
   "euro-jpy","gbp-jpy","euro-cad",
   "usd-cad","usd-jpy","cad-jpy",
   "gbp-usd","aud-usd","gbp-cad",
   "aud-cad","aud-jpy","aud-nzd",
   "euro-nzd","gbp-aud","gbp-nzd",
   "nzd-usd","nzd-cad","nzd-jpy");

foreach($url_array as $urls) {
   $sql[]= "SELECT *
     FROM `data_analysis_child`
     WHERE type='".$urls."'
     ORDER BY id DESC
     LIMIT 2";

}

$sql = implode(" UNION ",$sql);

The sql result

SELECT * FROM `data_analysis_child` WHERE type='euro-gbp' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='usd-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='cad-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-jpy' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='aud-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='euro-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-aud' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='gbp-nzd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-usd' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-cad' ORDER BY id DESC LIMIT 2 UNION SELECT * FROM `data_analysis_child` WHERE type='nzd-jpy' ORDER BY id DESC LIMIT 2

How do i solve?  Is there a better way to restructure this query?

Body:
if you need  order by and limit for each select you should use ()  around each select

  foreach($url_array as $urls) {
        $sql[]= " (  SELECT * FROM `data_analysis_child` WHERE type='".$urls."' ORDER BY id DESC LIMIT 2  )";
        break;
    }


问:
Pip error: Microsoft Visual C++ 14.0 is required
I just ran the following command:

```<code>pip install -U steem
</code>```

and the installation worked well until it failed to install pycrypto.
Afterwards I did the

```<code>pip install cryptography
</code>```

command because I thought it was the missing package.
So my question is, how I can install steem without the pycrypto-error (or the pycrypto-package in addition) and how to uninstall the cryptography-Package which I don't need.
(I'm using Windows 7 and Python 3)

```<code>Requirement already up-to-date: python-dateutil in c:\users\***\appdata\lo
cal\programs\python\python36\lib\site-packages (from dateparser->maya->steem)
...
Installing collected packages: urllib3, idna, chardet, certifi, requests, pycryp
to, funcy, w3lib, voluptuous, diff-match-patch, scrypt, prettytable, appdirs, la
ngdetect, ruamel.yaml, humanize, tzlocal, regex, dateparser, pytzdata, pendulum,
maya, ecdsa, pylibscrypt, ujson, toolz, steem
Running setup.py install for pycrypto ... error
Complete output from command c:\users\***\appdata\local\programs\pytho
n\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\
***~1\\AppData\\Local\\Temp\\pip-build-k6flhu5k\\pycrypto\\setup.py';f=getattr(
tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();
exec(compile(code, __file__, 'exec'))" install --record C:\Users\***N~1\AppDat
a\Local\Temp\pip-igpkll6u-record\install-record.txt --single-version-externally-
managed --compile:
running install
running build
running build_py
...
building 'Crypto.Random.OSRNG.winrandom' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

----------------------------------------
Command "c:\users\***\appdata\local\programs\python\python36\python.exe -u
-c "import setuptools, tokenize;__file__='C:\\Users\\***N~1\\AppData\\Local\\
Temp\\pip-build-k6flhu5k\\pycrypto\\setup.py';f=getattr(tokenize, 'open', open)(
__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code,   __fil
e__, 'exec'))" install --record C:\Users\***N~1\AppData\Local\Temp\pip-igpkll6
u-record\install-record.txt --single-version-externally-managed --compile"   faile
d with error code 1 in C:\Users\***N~1\AppData\Local\Temp\pip-build-    k6flhu5k\p
ycrypto\
</code>```

答:
You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

Alternate link: https://wiki.python.org/moin/WindowsCompilers#Microsoft_Visual_C.2B-.2B-_14.2_standalone:_Build_Tools_for_Visual_Studio_2019_.28x86.2C_x64.2C_ARM.2C_ARM64.29

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem
```
<p>To find out what the various install options mean, run this command:</p>
<pre class="lang-none prettyprint-override"><code>pip help install
</code>```

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.
```

If you do not already have the steem library installed, you can run the command without the -U option.

ContentLicense: CC BY-SA 4.0

Body:
I just ran the following command:

pip install -U steem

and the installation worked well until it failed to install pycrypto.
Afterwards I did the

pip install cryptography

command because I thought it was the missing package.
So my question is, how I can install steem without the pycrypto-error (or the pycrypto-package in addition) and how to uninstall the cryptography-Package which I don't need.
(I'm using Windows 7 and Python 3)

Requirement already up-to-date: python-dateutil in c:\users\***\appdata\lo
cal\programs\python\python36\lib\site-packages (from dateparser->maya->steem)
...
Installing collected packages: urllib3, idna, chardet, certifi, requests, pycryp
to, funcy, w3lib, voluptuous, diff-match-patch, scrypt, prettytable, appdirs, la
ngdetect, ruamel.yaml, humanize, tzlocal, regex, dateparser, pytzdata, pendulum,
maya, ecdsa, pylibscrypt, ujson, toolz, steem
Running setup.py install for pycrypto ... error
Complete output from command c:\users\***\appdata\local\programs\pytho
n\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\
***~1\\AppData\\Local\\Temp\\pip-build-k6flhu5k\\pycrypto\\setup.py';f=getattr(
tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();
exec(compile(code, __file__, 'exec'))" install --record C:\Users\***N~1\AppDat
a\Local\Temp\pip-igpkll6u-record\install-record.txt --single-version-externally-
managed --compile:
running install
running build
running build_py
...
building 'Crypto.Random.OSRNG.winrandom' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

----------------------------------------
Command "c:\users\***\appdata\local\programs\python\python36\python.exe -u
-c "import setuptools, tokenize;__file__='C:\\Users\\***N~1\\AppData\\Local\\
Temp\\pip-build-k6flhu5k\\pycrypto\\setup.py';f=getattr(tokenize, 'open', open)(
__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code,   __fil
e__, 'exec'))" install --record C:\Users\***N~1\AppData\Local\Temp\pip-igpkll6
u-record\install-record.txt --single-version-externally-managed --compile"   faile
d with error code 1 in C:\Users\***N~1\AppData\Local\Temp\pip-build-    k6flhu5k\p
ycrypto\

Body:
You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

Alternate link: https://wiki.python.org/moin/WindowsCompilers#Microsoft_Visual_C.2B-.2B-_14.2_standalone:_Build_Tools_for_Visual_Studio_2019_.28x86.2C_x64.2C_ARM.2C_ARM64.29

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem

To find out what the various install options mean, run this command:

pip help install

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.


问:
C# Ashx Google xml sitemap generation error
I'm using a ashx to deliver my websites sitemap for Google. Its all worked perfectly until I recently.

When requesting the sitemap in Google at http://www.naughtyfancydress.com/sitemap.ashx I get:
    XML Parsing Error: not well-formed
    Location: http://naughtyfancydress.com/sitemap.ashx
    Line Number 1, Column 1:`I�%&/m�{J�

My stripped down code in the ashx looks like:

```<code>context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
context.Response.Cache.SetCacheability(HttpCacheability.Public);

var writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;

writer.WriteStartDocument();
writer.WriteStartElement("urlset");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

writer.WriteStartElement("url");
writer.WriteElementString("loc", "http://www.naughtyfancydress.com/");
writer.WriteElementString("changefreq", "daily");
writer.WriteElementString("priority", "1.0");
writer.WriteEndElement();

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
</code>```

Any ideas on how to resolve would be welcomed.

EDIT: If you check the link above in Chrome nothing will display, I believe this is a Chrome issue, please check the link with FireFox.

答:
For anyone else, the issue was that in the Global.asax, in the Application_PreRequestHandlerExecute method I was gzip'in my content.

This obviously changes the content encoding to gzip from utf-8 even though it was specified above. That's the fix, ensure the sitemap handler doesn't send content as gzip.

ContentLicense: CC BY-SA 2.5

Body:
I'm using a ashx to deliver my websites sitemap for Google. Its all worked perfectly until I recently.

When requesting the sitemap in Google at http://www.naughtyfancydress.com/sitemap.ashx I get:
    XML Parsing Error: not well-formed
    Location: http://naughtyfancydress.com/sitemap.ashx
    Line Number 1, Column 1:`I�%&/m�{J�

My stripped down code in the ashx looks like:

context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(3600));
context.Response.Cache.SetCacheability(HttpCacheability.Public);

var writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;

writer.WriteStartDocument();
writer.WriteStartElement("urlset");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xsi:schemaLocation", "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

writer.WriteStartElement("url");
writer.WriteElementString("loc", "http://www.naughtyfancydress.com/");
writer.WriteElementString("changefreq", "daily");
writer.WriteElementString("priority", "1.0");
writer.WriteEndElement();

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();

Any ideas on how to resolve would be welcomed.

EDIT: If you check the link above in Chrome nothing will display, I believe this is a Chrome issue, please check the link with FireFox.


问:
Function accepting a generic Collection and returning an array of indices
I'm trying to write a function that accepts a generic Collection and a single element, then returns the index or indices of this element as an array. However, I'm getting an error at the return statement.

func findAll<T: Collection, U: Equatable>(_ items: T, _ find: U) -> [U] where T.Iterator.Element == U {
    var found = [Int]()
    for (index, item) in items.enumerated() {
        if item == find {
        found.append(index)
        }
    }
    return found
}```

答:
Since you would like to return the indices of the found elements, you should return an array of Ints instead of [U].  Here's the updated code:

```<code>func findAll<T: Collection, U: Equatable>(_ items: T, _ find: U)
  -> [Int] where T.Iterator.Element == U {

    var found = [Int]()
    for (index, item) in items.enumerated() {
        if item == find {
            found.append(index)
        }
    }
    return found
}
</code>```

And here's a test case:

```<code>let numbers = [1,0,1,0,0,1,1]
let indicesOfOnes = findAll(numbers, 1)
print(indicesOfOnes)
</code>```

Which will print:

```<code>[0, 2, 5, 6]
</code>```

Body:
Since you would like to return the indices of the found elements, you should return an array of Ints instead of [U].  Here's the updated code:

func findAll<T: Collection, U: Equatable>(_ items: T, _ find: U)
  -> [Int] where T.Iterator.Element == U {

    var found = [Int]()
    for (index, item) in items.enumerated() {
        if item == find {
            found.append(index)
        }
    }
    return found
}

And here's a test case:

let numbers = [1,0,1,0,0,1,1]
let indicesOfOnes = findAll(numbers, 1)
print(indicesOfOnes)

Which will print:

[0, 2, 5, 6]


问:
When should I use setDT() instead of data.table() to create a data.table?
I am having difficulty grasping the essence of the setDT() function. As I read code on SO, I frequently come across the use of setDT() to create a data.table. Of course the use of data.table() is ubiquitous. I feel like I solidly comprehend the nature of data.table() yet the relevance of setDT() eludes me. ?setDT tells me this:

setDT converts lists (both named and unnamed) and data.frames to data.tables by reference.

as well as:

In data.table parlance, all set* functions change their input by reference. That is, no copy is made at all, other than temporary working memory, which is as large as one column.

So this makes me think I should only use setDT() to make a data.table, right? Is setDT() simply a list to data.table converter?

```<code>library(data.table)

a <- letters[c(19,20,1,3,11,15,22,5,18,6,12,15,23)]
b <- seq(1,41,pi)
ab <- data.frame(a,b)
d <- data.table(ab)
e <- setDT(ab)

str(d)
#Classes ‘data.table’ and 'data.frame': 13 obs. of  2 variables:
# $ a: Factor w/ 12 levels "a","c","e","f",..: 9 10 1 2 5 7 11 3 8 4 ...
# $ b: num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>

str(e)
#Classes ‘data.table’ and 'data.frame': 13 obs. of  2 variables:
# $ a: Factor w/ 12 levels "a","c","e","f",..: 9 10 1 2 5 7 11 3 8 4 ...
# $ b: num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>
</code>```

Seemingly no difference in this instance. In another instance the difference is evident:

```<code>ba <- list(a,b)
f <- data.table(ba)
g <- setDT(ba)

str(f)
#Classes ‘data.table’ and 'data.frame': 2 obs. of  1 variable:
# $ ba:List of 2
#  ..$ : chr  "s" "t" "a" "c" ...
#  ..$ : num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>

str(g)
#Classes ‘data.table’ and 'data.frame': 13 obs. of  2 variables:
# $ V1: chr  "s" "t" "a" "c" ...
# $ V2: num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>
</code>```

When should I use setDT()? What makes setDT() relevant? Why not just make the original data.table() function capable of doing what setDT() is able to do?

答:
setDT() is not a replacement for data.table(). It's a more efficient replacement for as.data.table() which can be used with certain types of objects.

mydata <- as.data.table(mydata) will copy the object behind mydata, convert the copy to a data.table, then change the mydata symbol to point to the copy.

setDT(mydata) will change the object behind mydata to a data.table. No copying is done.

So what's a realistic situation to use setDT()?  When you can't control the class of the original data. For instance, most packages for working with databases give data.frame output. In that case, your code would be something like

```<code>mydata <- dbGetQuery(conn, "SELECT * FROM mytable")  # Returns a data.frame
setDT(mydata)                                        # Make it a data.table
</code>```

When should you use as.data.table(x)? Whenever x isn't a list or data.frame. The most common use is for matrices.

Body:
I am having difficulty grasping the essence of the setDT() function. As I read code on SO, I frequently come across the use of setDT() to create a data.table. Of course the use of data.table() is ubiquitous. I feel like I solidly comprehend the nature of data.table() yet the relevance of setDT() eludes me. ?setDT tells me this:

setDT converts lists (both named and unnamed) and data.frames to data.tables by reference.

as well as:

In data.table parlance, all set* functions change their input by reference. That is, no copy is made at all, other than temporary working memory, which is as large as one column.

So this makes me think I should only use setDT() to make a data.table, right? Is setDT() simply a list to data.table converter?

library(data.table)

a <- letters[c(19,20,1,3,11,15,22,5,18,6,12,15,23)]
b <- seq(1,41,pi)
ab <- data.frame(a,b)
d <- data.table(ab)
e <- setDT(ab)

str(d)
#Classes ‘data.table’ and 'data.frame': 13 obs. of  2 variables:
# $ a: Factor w/ 12 levels "a","c","e","f",..: 9 10 1 2 5 7 11 3 8 4 ...
# $ b: num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>

str(e)
#Classes ‘data.table’ and 'data.frame': 13 obs. of  2 variables:
# $ a: Factor w/ 12 levels "a","c","e","f",..: 9 10 1 2 5 7 11 3 8 4 ...
# $ b: num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>

Seemingly no difference in this instance. In another instance the difference is evident:

ba <- list(a,b)
f <- data.table(ba)
g <- setDT(ba)

str(f)
#Classes ‘data.table’ and 'data.frame': 2 obs. of  1 variable:
# $ ba:List of 2
#  ..$ : chr  "s" "t" "a" "c" ...
#  ..$ : num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>

str(g)
#Classes ‘data.table’ and 'data.frame': 13 obs. of  2 variables:
# $ V1: chr  "s" "t" "a" "c" ...
# $ V2: num  1 4.14 7.28 10.42 13.57 ...
# - attr(*, ".internal.selfref")=<externalptr>

When should I use setDT()? What makes setDT() relevant? Why not just make the original data.table() function capable of doing what setDT() is able to do?

Body:
setDT() is not a replacement for data.table(). It's a more efficient replacement for as.data.table() which can be used with certain types of objects.

mydata <- as.data.table(mydata) will copy the object behind mydata, convert the copy to a data.table, then change the mydata symbol to point to the copy.

setDT(mydata) will change the object behind mydata to a data.table. No copying is done.

So what's a realistic situation to use setDT()?  When you can't control the class of the original data. For instance, most packages for working with databases give data.frame output. In that case, your code would be something like

mydata <- dbGetQuery(conn, "SELECT * FROM mytable")  # Returns a data.frame
setDT(mydata)                                        # Make it a data.table

When should you use as.data.table(x)? Whenever x isn't a list or data.frame. The most common use is for matrices.


问:
Android - Read JSON from POST request
I need to catch the JSON response from a POST request in Android.

This is my code so far:

```<code>String data = null;
    try {
        data = URLEncoder.encode("Field1", "UTF-8")
                + "=" + URLEncoder.encode(field1, "UTF-8");
        data += "&" + URLEncoder.encode("Field2", "UTF-8") + "="
                   + URLEncoder.encode(field2, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

       String text = "";
       BufferedReader reader=null;

       // Send data
          try
          {

              // Defined URL  where to send data
              URL url = new URL(Constants.URL_EMAIL_LOGIN);

           // Send POST data request

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            int number = conn.getResponseCode();

            // Get the server response

          reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line = null;

          // Read Server Response
          while((line = reader.readLine()) != null)
              {
                     // Append server response in string
                     sb.append(line + "\n");
              }

              text = sb.toString();
          }
          catch(Exception ex)
          {

          }
          finally
          {
              try
              {

                  reader.close();
              }

              catch(Exception ex) {}
          }
</code>```

If the ResponseCode is 200 (all OK), the server sends me a string with the data I need. No problem with that, the code I have posted deals with it with no problem. A 200 response:

```<code>"{\r\n  \"user\": \"AAAA\",\r\n  \"token\": \" \",\r\n  \"email\": \"test@test.com\" \r\n}"
</code>```

But I also need to catch the errors. In that case, the server returns a JSON. This is the response from an error (I have got it using the Poster extension of Firefox):

```<code>{"Message":"Field1 is not correct."}
</code>```

With that response, my app crashes in this line:

```<code>reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
</code>```

This is the caught error:

```<code>java.io.FileNotFoundException: [url]
</code>```

Does anyone know how can I read the JSON from the server?

答:
The error is caused by the conn.getInputStream() method. HttpUrlConnection is known to throw a FileNotFoundException exception on getInputStream() if the server returns a response code greater than or equal to 400

Use conn.getErrorStream() to get the input stream when the response status is not 200

Check this:

```<code>BufferedInputStream inputStream = null;

int status = conn.getResponseCode();

if (status != HttpURLConnection.HTTP_OK) {
    inputStream = conn.getErrorStream();
} else {
    inputStream = conn.getInputStream();
}
</code>```

And use it in your reader as:

```<code>reader = new BufferedReader(new InputStreamReader(inputStream));
</code>```

Title: Android - Read JSON from POST request

Body:
I need to catch the JSON response from a POST request in Android.

This is my code so far:

String data = null;
    try {
        data = URLEncoder.encode("Field1", "UTF-8")
                + "=" + URLEncoder.encode(field1, "UTF-8");
        data += "&" + URLEncoder.encode("Field2", "UTF-8") + "="
                   + URLEncoder.encode(field2, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

       String text = "";
       BufferedReader reader=null;

       // Send data
          try
          {

              // Defined URL  where to send data
              URL url = new URL(Constants.URL_EMAIL_LOGIN);

           // Send POST data request

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            int number = conn.getResponseCode();

            // Get the server response

          reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line = null;

          // Read Server Response
          while((line = reader.readLine()) != null)
              {
                     // Append server response in string
                     sb.append(line + "\n");
              }

              text = sb.toString();
          }
          catch(Exception ex)
          {

          }
          finally
          {
              try
              {

                  reader.close();
              }

              catch(Exception ex) {}
          }

If the ResponseCode is 200 (all OK), the server sends me a string with the data I need. No problem with that, the code I have posted deals with it with no problem. A 200 response:

"{\r\n  \"user\": \"AAAA\",\r\n  \"token\": \" \",\r\n  \"email\": \"test@test.com\" \r\n}"

But I also need to catch the errors. In that case, the server returns a JSON. This is the response from an error (I have got it using the Poster extension of Firefox):

{"Message":"Field1 is not correct."}

With that response, my app crashes in this line:

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

This is the caught error:

java.io.FileNotFoundException: [url]

Does anyone know how can I read the JSON from the server?

Body:
The error is caused by the conn.getInputStream() method. HttpUrlConnection is known to throw a FileNotFoundException exception on getInputStream() if the server returns a response code greater than or equal to 400

Use conn.getErrorStream() to get the input stream when the response status is not 200

Check this:

BufferedInputStream inputStream = null;

int status = conn.getResponseCode();

if (status != HttpURLConnection.HTTP_OK) {
    inputStream = conn.getErrorStream();
} else {
    inputStream = conn.getInputStream();
}

And use it in your reader as:

reader = new BufferedReader(new InputStreamReader(inputStream));


问:
Batch Processing in Apache Beam with large overhead
I'm currently working on a larger Apache Beam pipeline with the Python API which reads data from BigQuery and in the end writes it back to another BigQuery task.

One of the transforms needs to use a binary program to transform the data, and for that it needs to load a 23GB file with binary lookup data. So starting and running the program takes a lot of overhead (takes about 2 minutes to load/run each time) and RAM, and it wouldn't make sense to start it up for just a single record. Plus the 23GB file would need to be copied locally from Cloud Storage every time.

The workflow for the binary would be:

Copy 23GB file from cloud storage if it's not there already

Save records to a file

run the binary with call()

read the output of the binary and return it

The amount of records the program can process at a time is basically unlimited, so it would be nice to get a somewhat-distributed Beam Transform, where I could specify a number of records to be processed at once (say 100'000 at a time), but still have it distributed so it can run it for 100'000 records at a time on multiple nodes.

I don't see Beam supporting this behaviour, it might be possible to hack something together as a KeyedCombineFn operation that collects records based on some split criterion/key and then runs the binary in the merge_accumulators step over the accumulated records. But this seems very hackish to me.

Or is it possible to GroupByKey and process groups as batches? Does this guarantee that each group is processed at once, or can groups be split behind the scenes by Beam?

I also saw there's a GroupIntoBatches in the Java API, which sounds like what I'd need, but isn't available in the Python SDK as far as I can tell.

My two question are, what's the best way (performance-wise) to achieve this use-case in Apache Beam, and if there isn't a good solution, is there some other Google Cloud service that might be better suited that could be used like Beam --> Other Service --> Beam ?

答:
Groups cannot be split behind the scenes, so using a GroupByKey should work. In fact, this is a requirement since each individual element must be processed on a single machine and after a GroupByKey all values with a given key are part of the same element.

You will likely want to assign random keys. Keep in mind that if there are too many values with a given key it may also be difficult to pass all of those values to your program -- so you may also want to limit how many of the values you pass to the program at a time and/or adjust how you assign keys.

One trick for assigning random keys is to generate the random number in start bundle (say 1 to 1000) and then in process element just increment this and wrap 1001 to 1000. This avoids generating a random number for every element, and still ensures a good distribution of keys.

You could create a PTransform for both this logic (divide a PCollection<T> into PCollection<List<T>> chunks for processing), and that would be potentially reusable in similar situations.


问:
How to remove single file from html input type file multiple?
HTML:

```<code><div class="filesdiv">
        <input type="file" name="files" id="files" style="display: none;" multiple
      required>
        <label for="files" class="btn btn-xs">Upload files</label>
        <div class="filenames"></div>
</div>
</code>```

JQUERY:

```<code>var filelist = [];

$('#files').change(function(event) {
    files = this.files;
    console.log(files);
    filelist.push(files);
    console.log(filelist[0]);
    $('.filenames').empty()
    $.each(files, function(index) {
        $('.filenames').append('<div style="overflow: hidden;">'+this.name+'</div>');
    });
    $('#files').val('')
    console.log(this.files)
    console.log(filelist[0])
});
</code>```

My consoles output:

My basic need is to delete a single file from multiple input. I have read few stackoverflow answers and blogs that, files are in FileList Object and it is read only. So, I am trying to make a local copy and try to manipulate it. Once the FileList object is deleted so is the array filelist.

答:
You may want to use a lib to make life easier.

Some thing like uploadify: http://www.uploadify.com/documentation/uploadifive/implementing-uploadifive/

Body:
HTML:

        <input type="file" name="files" id="files" style="display: none;" multiple
      required>
        Upload files

JQUERY:

var filelist = [];

$('#files').change(function(event) {
    files = this.files;
    console.log(files);
    filelist.push(files);
    console.log(filelist[0]);
    $('.filenames').empty()
    $.each(files, function(index) {
        $('.filenames').append('
'+this.name+'
');
    });
    $('#files').val('')
    console.log(this.files)
    console.log(filelist[0])
});

My consoles output:

My basic need is to delete a single file from multiple input. I have read few stackoverflow answers and blogs that, files are in FileList Object and it is read only. So, I am trying to make a local copy and try to manipulate it. Once the FileList object is deleted so is the array filelist.


问:
Remove duplicate attribute from HTMLString through regex
I am having a HtmlString where the some tag is having multiple "href" attribute. I have to remove one of them. If href attribute is more then 1 then have to remove blank href attribute through regex. </p>

```<code><p>
  Contrary to popular belief, Lorem Ipsum is not simply random text.It has
  <a title="Test PDF for RTF" href="" title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
     Test PDF
  </a>
  roots in a piece of classical Latin literature from 45 BC, making
  <a title="Learn More" href="test.html" title="Learn More" >
    Learn More
  </a>
  it over 2000 years old. Richard McClintock,
  <a title="Test Page" href="" >
    Test Page
  </a>
  Latin professor at Hampden-Sydney College in Virginia,
  <a title="Test PDF for RTF" href="" title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
    Test PDF
  </a>
  looked up one of the more obscure Latin words, consectetur
</p>
</code>```

答:
I think you want: match first herf in a line or text when it has two href and as with your comment: I have to keep one href, doesn't matter if it is empty. So you want to remove duplicate href and if so, you can apply:

```<code>(?=href.+?href)[^"]+""
</code>```

this part: (?=href.+?href) is a lookahead assertion and match a zero-length just before the first href if it found twice, and this part: [^"]+"" matches that empty href=""

(?=href.+?href)[^"]+""

A fest test of your input in a file:

```<code>perl -lne 'print $& while/(?=href.+?href)[^"]+""/g' file
</code>```

It outputs:

```<code>href=""
href=""
</code>```

and for removing:

```<code>perl -lpe 's/(?=href.+?href)[^"]+""/==>Removed<==/g' file
</code>```

And it outputs:

```<code>  <p>
  Contrary to popular belief, Lorem Ipsum is not simply random text.It has
  <a title="Test PDF for RTF" ==>Removed<== title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
     Test PDF
  </a>
  roots in a piece of classical Latin literature from 45 BC, making
  <a title="Learn More" href="test.html" title="Learn More" >
    Learn More
  </a>
  it over 2000 years old. Richard McClintock,
  <a title="Test Page" href="" >
    Test Page
  </a>
  Latin professor at Hampden-Sydney College in Virginia,
  <a title="Test PDF for RTF" ==>Removed<== title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
    Test PDF
  </a>
  looked up one of the more obscure Latin words, consectetur
</p>
</code>```

Also you can apply this pattern to java and just set the substitution to "" empty

Body:
I am having a HtmlString where the some tag is having multiple "href" attribute. I have to remove one of them. If href attribute is more then 1 then have to remove blank href attribute through regex.

  Contrary to popular belief, Lorem Ipsum is not simply random text.It has

     Test PDF

  roots in a piece of classical Latin literature from 45 BC, making

    Learn More

  it over 2000 years old. Richard McClintock,

    Test Page

  Latin professor at Hampden-Sydney College in Virginia,

    Test PDF

  looked up one of the more obscure Latin words, consectetur

Body:
I think you want: match first herf in a line or text when it has two href and as with your comment: I have to keep one href, doesn't matter if it is empty. So you want to remove duplicate href and if so, you can apply:

(?=href.+?href)[^"]+""

this part: (?=href.+?href) is a lookahead assertion and match a zero-length just before the first href if it found twice, and this part: [^"]+"" matches that empty href=""

(?=href.+?href)[^"]+""

A fest test of your input in a file:

perl -lne 'print $& while/(?=href.+?href)[^"]+""/g' file

It outputs:

href=""
href=""

and for removing:

perl -lpe 's/(?=href.+?href)[^"]+""/==>Removed<==/g' file

And it outputs:

  <p>
  Contrary to popular belief, Lorem Ipsum is not simply random text.It has
  <a title="Test PDF for RTF" ==>Removed<== title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
     Test PDF
  </a>
  roots in a piece of classical Latin literature from 45 BC, making
  <a title="Learn More" href="test.html" title="Learn More" >
    Learn More
  </a>
  it over 2000 years old. Richard McClintock,
  <a title="Test Page" href="" >
    Test Page
  </a>
  Latin professor at Hampden-Sydney College in Virginia,
  <a title="Test PDF for RTF" ==>Removed<== title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
    Test PDF
  </a>
  looked up one of the more obscure Latin words, consectetur
</p>

Also you can apply this pattern to java and just set the substitution to "" empty


问:
Mocha/Chai issue with http get request
i'm having trouble with http response in chai tests, i don't know how can i get the length of the res.body unless by console.log.

it's the test i'm trying to run:

```<code>it('It should have a length of 3061', function(){

        chai.request('http://localhost:8080')
        .get('/api/pac/')
        .end(function(err,res){

            console.log(res.body.length); //it shows 3061
            expect(res.body).to.have.lengthOf(3061); //it causes error "Cannot read property 'body' of undefined"

        });
    });
</code>```

if i try to do an expect with res.body, it returns "Cannot read property 'body' of undefined". But a console.log works.

A console.log(res.body) shows a json with 3061 objects. Each Object have this structure:

```<code>iid : {type : Number},

dnas : [{ _id : Number,
        col : Date,
        reproved : {type : Boolean},
        wave : {type: Number,
                index: true}
        }],
name : { type : String,
       uppercase: true,
       index: true}
</code>```

答:
You need to pass done to your it callback because chai.request('http://localhost:8080').get() is asynchronous. Without it, you're trying to run an assertion after it has finished. In other words, you need to tell it to wait until the HTTP get request completes. Note, I'm using some es6. Replace my arrows with callback functions if your project doesn't support es6.

```<code>it('should have a length of 3061', done => {
    chai.request('http://localhost:8080')
    .get('/api/pac/')
    .end((err, res) => {
        if (err) done(err);

        expect(res.body).to.have.lengthOf(3061);
        done();
    });
});
</code>```

Title: Mocha/Chai issue with http get request

Body:
i'm having trouble with http response in chai tests, i don't know how can i get the length of the res.body unless by console.log.

it's the test i'm trying to run:

it('It should have a length of 3061', function(){

        chai.request('http://localhost:8080')
        .get('/api/pac/')
        .end(function(err,res){

            console.log(res.body.length); //it shows 3061
            expect(res.body).to.have.lengthOf(3061); //it causes error "Cannot read property 'body' of undefined"

        });
    });

if i try to do an expect with res.body, it returns "Cannot read property 'body' of undefined". But a console.log works.

A console.log(res.body) shows a json with 3061 objects. Each Object have this structure:

iid : {type : Number},

dnas : [{ _id : Number,
        col : Date,
        reproved : {type : Boolean},
        wave : {type: Number,
                index: true}
        }],
name : { type : String,
       uppercase: true,
       index: true}

Body:
You need to pass done to your it callback because chai.request('http://localhost:8080').get() is asynchronous. Without it, you're trying to run an assertion after it has finished. In other words, you need to tell it to wait until the HTTP get request completes. Note, I'm using some es6. Replace my arrows with callback functions if your project doesn't support es6.

it('should have a length of 3061', done => {
    chai.request('http://localhost:8080')
    .get('/api/pac/')
    .end((err, res) => {
        if (err) done(err);

        expect(res.body).to.have.lengthOf(3061);
        done();
    });
});


问:
Java 8 map each field value of a List to another similar List
I have 2 List of objects:

```<code>List<User>
List<UserResource>
</code>```

For User class:

```<code>public class User {

    private int id;

    private String name;

    private String address;

    **SETTERS & GETTERS**
}
</code>```

For UserResource class:

```<code>public class UserResource {

    private String name;

    private String address;

    **SETTERS & GETTERS**
}
</code>```

My List<User> has data and i want to map value in name and address to UserResource's name and address, using java 8 stream and lambda, but i not sure how to do it.

Search online for quite sometime but not able to find similar question. Something like:

```<code>List<User> users = **data inserted**
List<UserResource> resources = users.forEach(u ->{
    u.setName(users.getName());
    u.setAddress(users.getAddress());
});
</code>```

I tried something like following, but im not using constructor, not really sure how to fix it.

```<code>List<UserResource> userResources = users.stream().map(u -> new UserResource(u.getName(), u.getAddress())).collect(Collectors.toList());
</code>```

答:
Your edit is logically correct, I assume you want to do it via setters, in this case define a lambda body and perform the operations there...    </p>

```<code>.map(u -> {
     UserResource ur = new UserResource();
     ur.setName(u.getName());
     ur.setAddress(u.getAddress());
     return ur;
 }).collect(...)
</code>```

Body:
I have 2 List of objects:

List<User>
List<UserResource>

For User class:

public class User {

    private int id;

    private String name;

    private String address;

    **SETTERS & GETTERS**
}

For UserResource class:

public class UserResource {

    private String name;

    private String address;

    **SETTERS & GETTERS**
}

My List<User> has data and i want to map value in name and address to UserResource's name and address, using java 8 stream and lambda, but i not sure how to do it.

Search online for quite sometime but not able to find similar question. Something like:

List<User> users = **data inserted**
List<UserResource> resources = users.forEach(u ->{
    u.setName(users.getName());
    u.setAddress(users.getAddress());
});

I tried something like following, but im not using constructor, not really sure how to fix it.

List<UserResource> userResources = users.stream().map(u -> new UserResource(u.getName(), u.getAddress())).collect(Collectors.toList());

Body:
Your edit is logically correct, I assume you want to do it via setters, in this case define a lambda body and perform the operations there...

.map(u -> {
     UserResource ur = new UserResource();
     ur.setName(u.getName());
     ur.setAddress(u.getAddress());
     return ur;
 }).collect(...)


问:
UITableView cell selected not loading another View
Hey everbody, im getting a curious problem here. Im trying to make my table push another view, called 'productviewcontroller'.

Im importing both 'productviewcontroller' and  'myappviewcontroller' on header.

```<code>#import "SearchViewController.h"
#import "MyAppViewController.h"
#import "TBXML.h"
#import "ProductViewController.h"
</code>```

And im setting my table to push the another view.

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ProductViewController *productViewController = [[ProductViewController alloc] initWithNibName:@"ProductViewController" bundle:[NSBundle mainBundle]];

    [self.navigationController pushViewController:productViewController animated:YES];
    [productViewController release];

    NSLog(@"Test.");
}
</code>```

When i selects the cell, it gives me the message 'test'. But dont push the another view.
Im setting the navigationController on app delegate.

What im doing wrong?

Thanks!

答: It looks right. Does the ProductView nib include a navigation controller?</p>

Body:
Hey everbody, im getting a curious problem here. Im trying to make my table push another view, called 'productviewcontroller'.

Im importing both 'productviewcontroller' and  'myappviewcontroller' on header.

#import "SearchViewController.h"
#import "MyAppViewController.h"
#import "TBXML.h"
#import "ProductViewController.h"

And im setting my table to push the another view.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ProductViewController *productViewController = [[ProductViewController alloc] initWithNibName:@"ProductViewController" bundle:[NSBundle mainBundle]];

    [self.navigationController pushViewController:productViewController animated:YES];
    [productViewController release];

    NSLog(@"Test.");
}

When i selects the cell, it gives me the message 'test'. But dont push the another view.
Im setting the navigationController on app delegate.

What im doing wrong?

Thanks!


问:
Laravel SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2
This might be obvious, and I may be completely missing the point, but I've got a table which contains multiple rows with user_id, site_id, e.g.

```<code>ldstaff | ld_site
____________________
   3         1
   3         2
   4         1
</code>```

A MySQL query originally written by an old dev got the staff id find their name and then concat all the sites together to make something like this.

```<code>StaffID | Name | sites
  3       Dave    1,2
</code>```

This query was written initially as

```<code>SELECT `ld_staff` as staffID ,a.name,GROUP_CONCAT(`ld_site`) as sites FROM `lead_distribution` l

LEFT JOIN users a ON a.crm_id = l.ld_staff

WHERE ld_enabled = 1 AND

`account_type` = 1 AND `active` = 1 AND `no_more` = 0 AND network_team > 0 AND renewal_team = 0

GROUP BY `ld_staff`
</code>```

However whenever we try to write it in Laravel as part of a new system to get the same results we have the error SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 no matter how we try to tamper with the query it always comes back to this. Reading up it seems sql_mode only_full_group_by doesn't allow this type of query, so I've changed sql_mode to = " " and this error persists.

Query

$data = DB::table('lead_distribution')
    ->join('users', 'ld_staff', '=', 'users.crm_id')
    ->select("lead_distribution.ld_staff", 'users.name',
        DB::raw("GROUP_CONCAT(`ld_site`) as sites"))
    ->where('users.account_type', '=', 1)
    ->where('users.active', '=', 1)
    ->where('users.no_more', '=', 0)
    ->where('users.network_team', '>', 0)
    ->where('users.renewal_team', '=', 0)
    ->groupBy('lead_distribution.ld_staff')
    ->get();
```

答:
config/database.php

Change 'strict' => true To 'strict' => false

and clear the cache

php artisan config:cache

then issue will be resolved.

Body:
This might be obvious, and I may be completely missing the point, but I've got a table which contains multiple rows with user_id, site_id, e.g.

ldstaff | ld_site
____________________
   3         1
   3         2
   4         1

A MySQL query originally written by an old dev got the staff id find their name and then concat all the sites together to make something like this.

StaffID | Name | sites
  3       Dave    1,2

This query was written initially as

SELECT `ld_staff` as staffID ,a.name,GROUP_CONCAT(`ld_site`) as sites FROM `lead_distribution` l

LEFT JOIN users a ON a.crm_id = l.ld_staff

WHERE ld_enabled = 1 AND

`account_type` = 1 AND `active` = 1 AND `no_more` = 0 AND network_team > 0 AND renewal_team = 0

GROUP BY `ld_staff`

However whenever we try to write it in Laravel as part of a new system to get the same results we have the error SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 no matter how we try to tamper with the query it always comes back to this. Reading up it seems sql_mode only_full_group_by doesn't allow this type of query, so I've changed sql_mode to = " " and this error persists.

Query

$data = DB::table('lead_distribution')
    ->join('users', 'ld_staff', '=', 'users.crm_id')
    ->select("lead_distribution.ld_staff", 'users.name',
        DB::raw("GROUP_CONCAT(`ld_site`) as sites"))
    ->where('users.account_type', '=', 1)
    ->where('users.active', '=', 1)
    ->where('users.no_more', '=', 0)
    ->where('users.network_team', '>', 0)
    ->where('users.renewal_team', '=', 0)
    ->groupBy('lead_distribution.ld_staff')
    ->get();


问:
Multiple positional arguments with Python and argparse
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot of the namespace each time a positional argument is found), but the problem I'm having can be replicated with the append action:

```<code>>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-a', action='store_true')
>>> parser.add_argument('-b', action='store_true')
>>> parser.add_argument('input', action='append')
>>> parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
usage: ipython [-h] [-a] [-b] input
ipython: error: unrecognized arguments: filetwo filethree
</code>```

I'd like this to result in the namespace (a=True, b=True, input=['fileone', 'filetwo', 'filethree']), but cannot see how to do this - if indeed it can. I can't see anything in the docs or Google which says one way or the other if this is possible, although its quite possible (likely?) I've overlooked something. Does anyone have any suggestions?

答:
It seems to me that hpaulj is on the right track but making things a bit more complicated than necessary.  I suspect that Blair is looking for something akin to the behavior of the old optparse module and doesn't really need the list of input arguments in the inputs field of the args object.  He just wants

```<code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_true')
parser.add_argument('-b', action='store_true')
opts, args = parser.parse_known_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
# Namespace(a=True, b=True), ['fileone', 'filetwo', 'filethree']
</code>```

In the vernacular of optparse, the "options" are available in opts, and the list of possibly interspersed other "arguments" are in args.

Body:
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot of the namespace each time a positional argument is found), but the problem I'm having can be replicated with the append action:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-a', action='store_true')
>>> parser.add_argument('-b', action='store_true')
>>> parser.add_argument('input', action='append')
>>> parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
usage: ipython [-h] [-a] [-b] input
ipython: error: unrecognized arguments: filetwo filethree

I'd like this to result in the namespace (a=True, b=True, input=['fileone', 'filetwo', 'filethree']), but cannot see how to do this - if indeed it can. I can't see anything in the docs or Google which says one way or the other if this is possible, although its quite possible (likely?) I've overlooked something. Does anyone have any suggestions?

Body:
It seems to me that hpaulj is on the right track but making things a bit more complicated than necessary.  I suspect that Blair is looking for something akin to the behavior of the old optparse module and doesn't really need the list of input arguments in the inputs field of the args object.  He just wants

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_true')
parser.add_argument('-b', action='store_true')
opts, args = parser.parse_known_args(['fileone', '-a', 'filetwo', '-b', 'filethree'])
# Namespace(a=True, b=True), ['fileone', 'filetwo', 'filethree']

In the vernacular of optparse, the "options" are available in opts, and the list of possibly interspersed other "arguments" are in args.


问:
Find time in milliseconds?
How can I find the time in milliseconds using PowerShell?</p>

答:
The question suggests finding a given datetime in milliseconds (Microsoft epoch time). This is easily solved with:

```<code>[Math]::Round((Get-Date).ToFileTime()/10000)
</code>```

or

```<code>[Math]::Round((Get-Date).ToFileTimeUTC()/10000)
</code>```

To convert this to Unix epoch time in seconds:

```<code>[Math]::Round((Get-Date).ToFileTime() / 10000000 - 11644473600)
</code>```

Where 11644473600 is the number of elapsed seconds between the Microsoft epoch (January 1, 1601 A.D. (C.E.)) and the Unix epoch (January 1, 1970, 12AM UTC/GMT)

https://msdn.microsoft.com/en-us/library/system.datetime.tofiletime(v=vs.110).aspx

Title: Find time in milliseconds?

Body:
The question suggests finding a given datetime in milliseconds (Microsoft epoch time). This is easily solved with:

[Math]::Round((Get-Date).ToFileTime()/10000)

or

[Math]::Round((Get-Date).ToFileTimeUTC()/10000)

To convert this to Unix epoch time in seconds:

[Math]::Round((Get-Date).ToFileTime() / 10000000 - 11644473600)

Where 11644473600 is the number of elapsed seconds between the Microsoft epoch (January 1, 1601 A.D. (C.E.)) and the Unix epoch (January 1, 1970, 12AM UTC/GMT)

https://msdn.microsoft.com/en-us/library/system.datetime.tofiletime(v=vs.110).aspx


问:
Disable input when enter is pressed dynamically
I'm making a website where there will be a lot of input fields. Sort of like a scanner, I would like to disable each input when the enter is pressed.

I now have this:

<input (keyup.enter)="doSomething()"/>

But I would want to pass along the input itself so I can disable these inputs. (f.e. something like: doSomething(input) { input.attr.disabled = true; }

How can I get this input field in my doSomething function?

Note: I do not want to use something like <input #input ... since I have so many input fields. This will only create a lot of work.

All I want is that each time the enter is pressed in an input field, that it gets disabled (using only one function for all).

答:
You can do this : </p>

```<code><input (keyup.enter)="doSomething($event)"/>

doSomething(event) {  event.target.disabled = true; }
</code>```

Body:
You can do this :

<input (keyup.enter)="doSomething($event)"/>

doSomething(event) {  event.target.disabled = true; }


问:
Virtual box error
I download virtual box 5.1.22, create new virtual machine and cant lauch machine.

```<code>    The virtual machine 'Debian' has terminated unexpectedly during startup with exit code 1 (0x1). More details may be available in 'C:\Users\Администратор\VirtualBox VMs\Debian\Logs\VBoxHardening.log'.

Error code:
E_FAIL (0x80004005)
Component:
MachineWrap
Interface:
IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0}
</code>```

VBoxHardening.log last strings:

```<code>5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: Processing 'user32.dll'...
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: 'user32.dll' -> '\Device\HarddiskVolume4\Windows\System32\user32.dll' [rcNtRedir=0xc0150008]
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: Processing 'ole32.dll'...
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: 'ole32.dll' -> '\Device\HarddiskVolume4\Windows\System32\ole32.dll' [rcNtRedir=0xc0150008]
5cc.d74: supR3HardenedScreenImage/Imports: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Windows\System32\ole32.dll
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: Processing 'gdi32.dll'...
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: 'gdi32.dll' -> '\Device\HarddiskVolume4\Windows\System32\gdi32.dll' [rcNtRedir=0xc0150008]
5cc.d74: supR3HardenedMonitor_LdrLoadDll: pName=C:\Program Files\Oracle\VirtualBox\platforms\qwindows.dll (rcNtResolve=0xc0150008) *pfFlags=0x0 pwszSearchPath=00000000008a4af0:C:\Program Files\Oracle\VirtualBox;C:\Windows\system32 [calling]
5cc.d74: supR3HardenedScreenImage/NtCreateSection: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Program Files\Oracle\VirtualBox\platforms\qwindows.dll
5cc.d74: supR3HardenedDllNotificationCallback: load   000007feeb8c0000 LB 0x0012e000 C:\Program Files\Oracle\VirtualBox\platforms\qwindows.dll [fFlags=0x0]
5cc.d74: supR3HardenedScreenImage/LdrLoadDll: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Program Files\Oracle\VirtualBox\platforms\qwindows.dll
5cc.d74: supR3HardenedMonitor_LdrLoadDll: returns rcNt=0x0 hMod=000007feeb8c0000 'C:\Program Files\Oracle\VirtualBox\platforms\qwindows.dll'
5cc.d74: supR3HardenedScreenImage/LdrLoadDll: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Windows\System32\cryptbase.dll
5cc.d74: supR3HardenedMonitor_LdrLoadDll: pName=C:\Windows\system32\CRYPTBASE.dll (Input=CRYPTBASE.dll, rcNtResolve=0xc0150008) *pfFlags=0x0 pwszSearchPath=00000000008a4af0:C:\Program Files\Oracle\VirtualBox;C:\Windows\system32 [calling]
5cc.d74: supR3HardenedMonitor_LdrLoadDll: returns rcNt=0x0 hMod=000007fefc020000 'C:\Windows\system32\CRYPTBASE.dll'
760.654: supR3HardNtChildWaitFor[2]: Quitting: ExitCode=0x1 (rcNtWait=0x0, rcNt1=0x0, rcNt2=0x103, rcNt3=0x103, 2051 ms, the end);
1b14.c7c: supR3HardNtChildWaitFor[1]: Quitting: ExitCode=0x1 (rcNtWait=0x0, rcNt1=0x0, rcNt2=0x103, rcNt3=0x103, 2662 ms, the end);
</code>```

答:
Installed the latest update from Microsoft. Click Here

Did System Reboot?.

Uninstalled the Oracle VM VirtualBox.

Installed it
again after a second Reboot.

Title: Virtual box error

Body:
I download virtual box 5.1.22, create new virtual machine and cant lauch machine.

    The virtual machine 'Debian' has terminated unexpectedly during startup with exit code 1 (0x1). More details may be available in 'C:\Users\Администратор\VirtualBox VMs\Debian\Logs\VBoxHardening.log'.

Error code:
E_FAIL (0x80004005)
Component:
MachineWrap
Interface:
IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0}

VBoxHardening.log last strings:

5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: Processing 'user32.dll'...
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: 'user32.dll' -> '\Device\HarddiskVolume4\Windows\System32\user32.dll' [rcNtRedir=0xc0150008]
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: Processing 'ole32.dll'...
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: 'ole32.dll' -> '\Device\HarddiskVolume4\Windows\System32\ole32.dll' [rcNtRedir=0xc0150008]
5cc.d74: supR3HardenedScreenImage/Imports: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Windows\System32\ole32.dll
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: Processing 'gdi32.dll'...
5cc.d74: supR3HardenedWinVerifyCacheProcessImportTodos: 'gdi32.dll' -> '\Device\HarddiskVolume4\Windows\System32\gdi32.dll' [rcNtRedir=0xc0150008]
5cc.d74: supR3HardenedMonitor_LdrLoadDll: pName=C:\Program Files\Oracle\VirtualBox\platforms\qwindows.dll (rcNtResolve=0xc0150008) *pfFlags=0x0 pwszSearchPath=00000000008a4af0:C:\Program Files\Oracle\VirtualBox;C:\Windows\system32 [calling]
5cc.d74: supR3HardenedScreenImage/NtCreateSection: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Program Files\Oracle\VirtualBox\platforms\qwindows.dll
5cc.d74: supR3HardenedDllNotificationCallback: load   000007feeb8c0000 LB 0x0012e000 C:\Program Files\Oracle\VirtualBox\platforms\qwindows.dll [fFlags=0x0]
5cc.d74: supR3HardenedScreenImage/LdrLoadDll: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Program Files\Oracle\VirtualBox\platforms\qwindows.dll
5cc.d74: supR3HardenedMonitor_LdrLoadDll: returns rcNt=0x0 hMod=000007feeb8c0000 'C:\Program Files\Oracle\VirtualBox\platforms\qwindows.dll'
5cc.d74: supR3HardenedScreenImage/LdrLoadDll: cache hit (VINF_SUCCESS) on \Device\HarddiskVolume4\Windows\System32\cryptbase.dll
5cc.d74: supR3HardenedMonitor_LdrLoadDll: pName=C:\Windows\system32\CRYPTBASE.dll (Input=CRYPTBASE.dll, rcNtResolve=0xc0150008) *pfFlags=0x0 pwszSearchPath=00000000008a4af0:C:\Program Files\Oracle\VirtualBox;C:\Windows\system32 [calling]
5cc.d74: supR3HardenedMonitor_LdrLoadDll: returns rcNt=0x0 hMod=000007fefc020000 'C:\Windows\system32\CRYPTBASE.dll'
760.654: supR3HardNtChildWaitFor[2]: Quitting: ExitCode=0x1 (rcNtWait=0x0, rcNt1=0x0, rcNt2=0x103, rcNt3=0x103, 2051 ms, the end);
1b14.c7c: supR3HardNtChildWaitFor[1]: Quitting: ExitCode=0x1 (rcNtWait=0x0, rcNt1=0x0, rcNt2=0x103, rcNt3=0x103, 2662 ms, the end);


问:
Calculate Text formula (NO VBA and NO Evaluate)
I am using Excel to calculate a string value where Evaluate() works fine but I am not allowed to use evaluate() in the Name Manager and I am not allowed to use it in VB A because the file gets converted to .xls. Here is the issue.

I have 100 s of a long formula example:

```<code>($F$10+0)+($F$11+0.125)+($F$10+0.0625)
</code>```

which i need to evaluate the values between the brackets separately.

I am able to separate the formula to

```<code>A1 is ($F$10+0)
A2 is ($F$11+0.125)
A3 is ($F$10+0.0625)
</code>```

I would like to put an "=" sign in front of this string and calculate the values of A1, A2, and A3.

However I am not allowed to use function EVALUATE() in the File Manager, it does not work in the cells and I am not allowed to use VB A to code the formula.

is there any replacement for evaluate that I can use?

thanks

答:
Welcome to the dark side of Excel.

If you cannot use:

1) VBA

2) Macros

3) Evaluate()

4) File Manager / Define Name

Then there are no simple formulas that can help you (plus you can't make your own).  Microsoft has purposely not addressed this issue for many many years.

So you are left to your own devices to create your own parser in Excel cells.

This can be very difficult if you have varying types of formulas that can change signs, or amount of addressed cells, or any number of other craziness that formulas can take.

However... if you have a minimum number of deviations for how the formula is expressed... you can write something that will do the trick.

This comes with a caveat... the formula must be provided with the same parameters each time.  And what you gave as examples, has the structure defined exactly the same for each formula.

So therefore, using your examples, you can write this code in column A2:

```<code>=INDIRECT(MID(A1,SEARCH("$",A1),SEARCH("+",A1)-SEARCH("$",A1)),TRUE)+MID(A1,SEARCH("+",A1)+1,LEN(A1)-SEARCH("+",A1)-1)
</code>```

Then you can copy that code over to B2 and C2.

This will give you the correct math as if it was a formula.

The structural parameters that are needed for this to work are:

1) The cell address must always start with a dollar sign $

2) The cell address must be immediately followed by a plus sign +

3) Only a single addition is done as the formula

4) The operand after the plus sign must be numeric

5) The formula must end with a Parenthesis )

6) It can't hurt to begin with a Parenthesis either (

And since all of your formulas adhere to this structure... the formula I provided will work.

If you need to change item 3 to also allow for 'subtraction', then you are going to need to add if statements to the formula and it's going to become complicated very quickly.  Impossible? No.  But a huge mess? Yes.

Anyway, this should work with all of your restrictions that you have.  That is... if your formulas don't deviate from the structure that has been provided.  If you have different formula structures, you'd need to let us know about them... or better yet, write your own code.

Hope this helped. :)

Body:
I am using Excel to calculate a string value where Evaluate() works fine but I am not allowed to use evaluate() in the Name Manager and I am not allowed to use it in VB A because the file gets converted to .xls. Here is the issue.

I have 100 s of a long formula example:

($F$10+0)+($F$11+0.125)+($F$10+0.0625)

which i need to evaluate the values between the brackets separately.

I am able to separate the formula to

A1 is ($F$10+0)
A2 is ($F$11+0.125)
A3 is ($F$10+0.0625)

I would like to put an "=" sign in front of this string and calculate the values of A1, A2, and A3.

However I am not allowed to use function EVALUATE() in the File Manager, it does not work in the cells and I am not allowed to use VB A to code the formula.

is there any replacement for evaluate that I can use?

thanks

Body:
Welcome to the dark side of Excel.

If you cannot use:

1) VBA

2) Macros

3) Evaluate()

4) File Manager / Define Name

Then there are no simple formulas that can help you (plus you can't make your own).  Microsoft has purposely not addressed this issue for many many years.

So you are left to your own devices to create your own parser in Excel cells.

This can be very difficult if you have varying types of formulas that can change signs, or amount of addressed cells, or any number of other craziness that formulas can take.

However... if you have a minimum number of deviations for how the formula is expressed... you can write something that will do the trick.

This comes with a caveat... the formula must be provided with the same parameters each time.  And what you gave as examples, has the structure defined exactly the same for each formula.

So therefore, using your examples, you can write this code in column A2:

=INDIRECT(MID(A1,SEARCH("$",A1),SEARCH("+",A1)-SEARCH("$",A1)),TRUE)+MID(A1,SEARCH("+",A1)+1,LEN(A1)-SEARCH("+",A1)-1)

Then you can copy that code over to B2 and C2.

This will give you the correct math as if it was a formula.

The structural parameters that are needed for this to work are:

1) The cell address must always start with a dollar sign $

2) The cell address must be immediately followed by a plus sign +

3) Only a single addition is done as the formula

4) The operand after the plus sign must be numeric

5) The formula must end with a Parenthesis )

6) It can't hurt to begin with a Parenthesis either (

And since all of your formulas adhere to this structure... the formula I provided will work.

If you need to change item 3 to also allow for 'subtraction', then you are going to need to add if statements to the formula and it's going to become complicated very quickly.  Impossible? No.  But a huge mess? Yes.

Anyway, this should work with all of your restrictions that you have.  That is... if your formulas don't deviate from the structure that has been provided.  If you have different formula structures, you'd need to let us know about them... or better yet, write your own code.

Hope this helped. :)


问:
Opposite of lastUnique()
New to Esper and EPL in general, i have two use cases which are basically the opposites of oneanother. First I need to catch all unique events in a timewindow, using firstunique(*parameters*).win:time(*time*).

Now what I need to do is the exact opposite, basically catch all events that arrive in that window and that are NOT thrown by that statement, basically all the duplicates.

How can I achieve this ? Thanks !

答:
You could use a subquery and "not exists". For example:</p>

```<code>select * from Event e1 where not exists (select * from Event#firstunique(*parameters*)#time(*time*) e2 where e1.parameters = e2.parameters)
</code>```

Title: Opposite of lastUnique()

Body:
You could use a subquery and "not exists". For example:

select * from Event e1 where not exists (select * from Event#firstunique(*parameters*)#time(*time*) e2 where e1.parameters = e2.parameters)


问:
Drools - Running a rule with an empty object
I'm trying to write a rule to calculate prices for an insurance product based on conditions. In the 'when' I'm using an object called AdditionalDriver, which contains the details for drivers other than the policy holder. From this, different prices can be calculated based on whether the additional driver is a parent, friend, spouse etc. See below:

```<code>when
    AdditionalDriver($relToProp : relationToProposer)
then
    String relToProp = $relToProp;

    if(!relToProp.equals("P"))
    {
        //prices
    }
end
</code>```

"P" = parent.

This rule works when an additional driver has been added. However, if there is no additional driver, then the object is empty, and so the rule does not run. What do I need to do to get this rule to run, even when the object is empty?

Thanks in advance.

答:
You should write one rule for each of the relative or acquaintance classes:

```<code>when
    PolicyHolder( $phid: id )
    AdditionalDriver( relationToProposer == "P", belongsTo == $phid )
then
    //prices
end
</code>```

For no additional driver being requested, write a rule

```<code>when
    PolicyHolder( $phid: id )
    not AdditionalDriver( belongsTo == $phid )
then
    // cheaper prices
end
</code>```

Don't use conditional statement in your consequences to further distinguish facts. This is a code smell.

Body:
I'm trying to write a rule to calculate prices for an insurance product based on conditions. In the 'when' I'm using an object called AdditionalDriver, which contains the details for drivers other than the policy holder. From this, different prices can be calculated based on whether the additional driver is a parent, friend, spouse etc. See below:

when
    AdditionalDriver($relToProp : relationToProposer)
then
    String relToProp = $relToProp;

    if(!relToProp.equals("P"))
    {
        //prices
    }
end

"P" = parent.

This rule works when an additional driver has been added. However, if there is no additional driver, then the object is empty, and so the rule does not run. What do I need to do to get this rule to run, even when the object is empty?

Thanks in advance.

Body:
You should write one rule for each of the relative or acquaintance classes:

when
    PolicyHolder( $phid: id )
    AdditionalDriver( relationToProposer == "P", belongsTo == $phid )
then
    //prices
end

For no additional driver being requested, write a rule

when
    PolicyHolder( $phid: id )
    not AdditionalDriver( belongsTo == $phid )
then
    // cheaper prices
end

Don't use conditional statement in your consequences to further distinguish facts. This is a code smell.


问:
Find position of last Non Null element in a list in C#
I have the following values in my MySQL DB

```<code>Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null
</code>```

and I have create the a list in the below format

```<code>List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);
</code>```

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

答:
Assuming your data is already in order from the original database query:</p>

```<code>var idx = StockData.Select((data,idx) => new { data, idx})
                   .Where(x => x.data.High_Low_Price != null).FirstOrDefault()?.i;
</code>```

Body:
I have the following values in my MySQL DB

Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null

and I have create the a list in the below format

List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

Body:
Assuming your data is already in order from the original database query:

var idx = StockData.Select((data,idx) => new { data, idx})
                   .Where(x => x.data.High_Low_Price != null).FirstOrDefault()?.i;


问:
Vulkan buffer memory management - When do we need staging buffers?
I read a lot of articles on Vulkan memory management and all of them recommend using staging buffers for transferring to the GPU.
But we can already create memory that is device local and host visible, host coherent. It is readable from GPU as well as writable from CPU.

Here is what I thought would be reasonable - Create one big buffer bound to a memory which is device local, host visible and coherent. Now for all dynamic buffers, we just keep using memory from this buffer and bind the buffer at that offset.

But in most examples, they create one host visible buffer and one gpu visible and use the copyBuffer operation for transferring. What is the advantage of this over using just one buffer which is accessible to both cpu and gpu? I am only talking about buffers, not textures.

答:
As ratchet freak said, devices aren't required to have a memory type that is both device local and host visible. Even though most do, the size might be limited. Maybe things have changed in the last few years, but it used to be that PCI-E and BIOS limitations means 256 MB or maybe 512 MB was as much as you could get. And finally, CPU writes to over PCI-E are going to be lower bandwidth than to the CPU's own memory. So even though using a staging buffer uses twice as much total bandwidth, if it can be done asynchronously on a transfer queue, it minimizes the time that the CPU and graphics pipeline spend on that transfer. So whether using a staging buffer is a net win is going to depend on the specific CPU and GPU combination, and what your application is doing.

However, on SOCs like mobile devices or integrated GPUs, using a staging buffer should seldom if ever be a win. Mobile GPUs shouldn't have limited device-local + host-visible heap sizes. Looking at a couple Windows integrated GPUs on vulkan.gpuinfo.org, it looks like modern Intel integrated GPUs don't have such limits either, but AMD integrated GPUs still do (I only looked at a few random samples, YMMV).

All this makes it hard to give a clear "always do X" recommendation. Personally, I would generally do this:

If I just want one code path that works everywhere and am not worried about performance or memory footprint, use a staging buffer. This is probably a good choice for discrete GPUs, but suboptimal for integrated/SOC GPUs.

Otherwise, keep the staging buffer as a fallback path, but use a shared device-local/host-visible pool when there's a big enough one available.

When I start trying to get every last bit of performance, then tune the above to prefer staging buffers with asynchronous transfers for some kinds of uploads on discrete GPUs, when I have data showing it's a net win.


问:
theano NotImplementedError
I am running some theano code making use of tensor.advanced_subtensor
I am getting the following error :

```<code>NotImplementedError: Could not import inplace_increment, so some advanced indexing features are disabled. They will be available if you update NumPy to version 1.8 or later, or to the latest development version. You may need to clear the cache (theano-cache clear) afterwards.
</code>```

I have the latest version of theano (0.6.0.dev-60b5ccc2bcabb1010714376764daf8a50722cee9) and numpy (1.8.0). Why am I still getting this error? How can I resolve this error? How do I clear theano cache?

答:
You need to clear Theano cache. Cache live in ~/.theano/ folder.
Follow below steps to clear it manually.

```<code> import theano
 print (theano.config.compiledir)
 # and then delete directory returned from above.
</code>```

If you don not want to delete manually then use below command.

```<code>theano-cache purge
</code>```

Title: theano NotImplementedError

Body:
I am running some theano code making use of tensor.advanced_subtensor
I am getting the following error :

NotImplementedError: Could not import inplace_increment, so some advanced indexing features are disabled. They will be available if you update NumPy to version 1.8 or later, or to the latest development version. You may need to clear the cache (theano-cache clear) afterwards.

I have the latest version of theano (0.6.0.dev-60b5ccc2bcabb1010714376764daf8a50722cee9) and numpy (1.8.0). Why am I still getting this error? How can I resolve this error? How do I clear theano cache?

Body:
You need to clear Theano cache. Cache live in ~/.theano/ folder.
Follow below steps to clear it manually.

 import theano
 print (theano.config.compiledir)
 # and then delete directory returned from above.

If you don not want to delete manually then use below command.

theano-cache purge


问:
Indeed API XML feed always returns only 25 results
I'm trying to use the Indeed.com XML Feed API's in a PHP website. I use this script https://github.com/indeedlabs/indeed-php, see how it works on the Github page (very good script, thanks to the author).

It works but Indeed always returns only 25 results for jobs, even when I set the 'limit', 'start' and 'end' parameters.

Here are the parameters I send :

```<code>$aParams = array(
         "q" => "php",
         "l" => "paris",
         "co" => "FR",
         "limit" => 10000,
         "sort" => "date",
         "start" => 0,
         "end" => 100,
         "userip" => $_SERVER["REMOTE_ADDR"],
         "useragent" => $_SERVER["HTTP_USER_AGENT"],
             "v" => 2,
             "format" => "json",
             "publisher" => "123456789"
   );
</code>```

An array is returned and contains :

```<code>[version] = 2
[query] = 'php'
[location] = 'paris'
[dupefilter] = 'true'
[highlight] = 'true'
[start] = 1
[end] = 25
[totalResults] = 2068
[pageNumber] = 0
[results] = an array which contains the jobs informations
</code>```

As we can see, totalResults is equal to 2058 but real the jobs results array always contains only 25 entries.

It seems to be a pagination issue (read here : http://forums.appthemes.com/report-jobroller-bugs/indeed-integration-api-37420) but I don't understand the goal : why proceed like this and not more simply ? So I have to do many requests : one to know first the 'totalResults' and save it (in session for example) and other requests to paginate the results 25 by 25 until the last?

Are there any developers who use this API and how do you proceed?

Thanks

答:
Right Indeed limits the feed to 25 at a time. I have written script to get round this. In the Indeed $params you can specify a 'start' which as default is 0.

I have created a script which using the job count creates a foreach loop and loops the API changing the 'start' to keep getting different results until theres no more left. Then it puts it all into a single PHP array.

Single API request just so we can get totalResults (count of total jobs)

```<code>$client = new Indeed("YOUR_ID");
$args_count = array(
    "q" => "YOUR SEARCH QUERY",
    "l" => "",
    "co" => "GB",
    "userip" => "1.2.3.4",
    "limit" => 10000,
    "useragent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)"
);
</code>```

Once we have the total job count we divide it by 25 and round the result up. This is so we know how many times we need to run our foreach

```<code>$totalResults = $client->search($args_count);
$totalCount = $totalResults['totalResults'] / 25;
$loop_to_count = ceil($totalCount);
</code>```

We create a array starting with 0 and going up in 25s to as many as you require. My below will return 150 results.

```<code>$counter = 0;
$loop_options = array('0', '25', '50', '75', '100', '125', '150');
</code>```

Then we start the main foreach:

```<code>$results = '';

foreach ($loop_options as $options) {

    $params = array(
    "q" => "YOUR SEARCH QUERY",
    "l" => "",
    "co" => "GB",
    "userip" => "1.2.3.4",
    "limit" => 10000,
    "start"  => $options,
    "useragent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)"
    );
    $getResults = $client->search($params);

   foreach ($getResults['results'] as $rawResults) {

       $Subresults[] = array(
        'jobtitle' => $rawResults['jobtitle'],
        'company' => $rawResults['company'],
        'city' => $rawResults['city'],
        'state' => $rawResults['state'],
        'country' => $rawResults['country'],
        'language' => $rawResults['language'],
        'formattedLocation' => $rawResults['formattedLocation'],
        'source' => $rawResults['source'],
        'date' => $rawResults['date'],
        'snippet' => $rawResults['snippet'],
        'url' => $rawResults['url'],
        'onmousedown' => $rawResults['onmousedown'],
        'jobkey' => $rawResults['jobkey'],
        'sponsored' => $rawResults['sponsored'],
        'expired' => $rawResults['expired'],
        'indeedApply' => $rawResults['indeedApply'],
        'formattedLocationFull' => $rawResults['formattedLocationFull'],
        'formattedRelativeTime' => $rawResults['formattedRelativeTime'],
        'stations' => $rawResults['stations']
        );
   }
    $counter++;
    if ($counter == $loop_to_count) { break; }
}
</code>```

Finally all our results are inside this array:

```<code>$results = array ('results' => $Subresults);
</code>```

$results will contains all the jobs you have posted on Indeed

Body:
I'm trying to use the Indeed.com XML Feed API's in a PHP website. I use this script https://github.com/indeedlabs/indeed-php, see how it works on the Github page (very good script, thanks to the author).

It works but Indeed always returns only 25 results for jobs, even when I set the 'limit', 'start' and 'end' parameters.

Here are the parameters I send :

$aParams = array(
         "q" => "php",
         "l" => "paris",
         "co" => "FR",
         "limit" => 10000,
         "sort" => "date",
         "start" => 0,
         "end" => 100,
         "userip" => $_SERVER["REMOTE_ADDR"],
         "useragent" => $_SERVER["HTTP_USER_AGENT"],
             "v" => 2,
             "format" => "json",
             "publisher" => "123456789"
   );

An array is returned and contains :

[version] = 2
[query] = 'php'
[location] = 'paris'
[dupefilter] = 'true'
[highlight] = 'true'
[start] = 1
[end] = 25
[totalResults] = 2068
[pageNumber] = 0
[results] = an array which contains the jobs informations

As we can see, totalResults is equal to 2058 but real the jobs results array always contains only 25 entries.

It seems to be a pagination issue (read here : http://forums.appthemes.com/report-jobroller-bugs/indeed-integration-api-37420) but I don't understand the goal : why proceed like this and not more simply ? So I have to do many requests : one to know first the 'totalResults' and save it (in session for example) and other requests to paginate the results 25 by 25 until the last?

Are there any developers who use this API and how do you proceed?

Thanks

Body:
Right Indeed limits the feed to 25 at a time. I have written script to get round this. In the Indeed $params you can specify a 'start' which as default is 0.

I have created a script which using the job count creates a foreach loop and loops the API changing the 'start' to keep getting different results until theres no more left. Then it puts it all into a single PHP array.

Single API request just so we can get totalResults (count of total jobs)

$client = new Indeed("YOUR_ID");
$args_count = array(
    "q" => "YOUR SEARCH QUERY",
    "l" => "",
    "co" => "GB",
    "userip" => "1.2.3.4",
    "limit" => 10000,
    "useragent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)"
);

Once we have the total job count we divide it by 25 and round the result up. This is so we know how many times we need to run our foreach

$totalResults = $client->search($args_count);
$totalCount = $totalResults['totalResults'] / 25;
$loop_to_count = ceil($totalCount);

We create a array starting with 0 and going up in 25s to as many as you require. My below will return 150 results.

$counter = 0;
$loop_options = array('0', '25', '50', '75', '100', '125', '150');

Then we start the main foreach:

$results = '';

foreach ($loop_options as $options) {

    $params = array(
    "q" => "YOUR SEARCH QUERY",
    "l" => "",
    "co" => "GB",
    "userip" => "1.2.3.4",
    "limit" => 10000,
    "start"  => $options,
    "useragent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)"
    );
    $getResults = $client->search($params);

   foreach ($getResults['results'] as $rawResults) {

       $Subresults[] = array(
        'jobtitle' => $rawResults['jobtitle'],
        'company' => $rawResults['company'],
        'city' => $rawResults['city'],
        'state' => $rawResults['state'],
        'country' => $rawResults['country'],
        'language' => $rawResults['language'],
        'formattedLocation' => $rawResults['formattedLocation'],
        'source' => $rawResults['source'],
        'date' => $rawResults['date'],
        'snippet' => $rawResults['snippet'],
        'url' => $rawResults['url'],
        'onmousedown' => $rawResults['onmousedown'],
        'jobkey' => $rawResults['jobkey'],
        'sponsored' => $rawResults['sponsored'],
        'expired' => $rawResults['expired'],
        'indeedApply' => $rawResults['indeedApply'],
        'formattedLocationFull' => $rawResults['formattedLocationFull'],
        'formattedRelativeTime' => $rawResults['formattedRelativeTime'],
        'stations' => $rawResults['stations']
        );
   }
    $counter++;
    if ($counter == $loop_to_count) { break; }
}

Finally all our results are inside this array:

$results = array ('results' => $Subresults);

$results will contains all the jobs you have posted on Indeed