问:
T-SQL Window Function
For the sake of example, I have the following data set:
ToyReferenceNumber, Company, CompositeCalculatedField, PermanentRecallDate, ReturnToStoreDate

Basically, there could be 3-4 entries for each item (imaginary company TheToyCompany, or TTC):

```<code>TTC-011-0934, TTC, calculation, NULL, 2017-03-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2014-05-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2011-08-27 12:01:01.00
TTC-994-0132, TTC, calculation, 2017-06-12 12:01:01.00, NULL
TTC-994-0132, TTC, calculation, NULL, 2017-02-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, 2015-03-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, NULL
</code>```

From a business logic standpoint, for the first product (0934), it had a recall multiple times (which printing or prod batch, we don't care), but was fixed and returned to stores after each.

For 0132, it was attempted to fix the defect, but then the company simply decided to scrap the product as it was not selling anyway.

For 0122, a product batch was recalled, fixed, and then sent to stores on 2015-03-01, but a current batch is currently being fixed (hence, the NULL, NULL).

What management wants is a report that current fix-factory billing (e.g. time sheets for guys who fix the toys).

Pseudo-Query:

```<code> For a given product, return only the record with NULL, NULL dates (actively being fixed)
    IF not null, null, return only the record with the PermanentRecallDate
    IF no PermanentRecallDate, return only the record with the latest ReturnToStoreDate
</code>```

The oracle query was basically the same as the following pseudo-code:

```<code>SELECT <normal columns>
,MAX(ts.PermanentRecallDate) KEEP (dense_rank last order by ts.PermanentRecallDate NULLS LAST) PERANENTRECALLDATE
,MAX(ts.ReturnToStoreDate) KEEP (dense_rank last order by ts.ReturnToStoreDate NULLS LAST) RETURNTOSTOREDATE
</code>```

The oracle query is pretty straightforward, but I need it in T-SQL:

```<code>WITH CTE_ToyReferenceExport
AS
(
SELECT ts.ToyReferenceNumber AS TOYNUM
    ,tsh.Company AS COMPANY
    ,MAX(largeSetofCalculations) AS CompositeCalculatedField
    ,MAX(ts.PermanentRecallDate) AS PERMANETRECALL
    ,MAX(ts.ReturnToStoreDate) AS RETURNTOSTORE
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.PermanentRecallDate) as PRDRank
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.(ReturnToStoreDate) AS RTSDRank

    FROM origin.ToyStaging ts
    JOIN origin.ToyOrders to ON ts.ordernumer = to.ordno
    JOIN origin.ToyShipment tsh ON to.packno = tsh.crateno
    LEFT JOIN origin.Shippers sh ON to.packno = sh.cratenum AND 'calcField' = sh.originfield
GROUP BY ts.ToyReferenceNumber, tsh.Company, ts.permanentrecalldate, ts.returntostoredate
)
</code>```

There is a lot more to it, but the main thing that trips me up is getting the result set returned by "MAX..Keep Dense_rank last order by.. NULLS LAST" logic.

Any help would be appreciated.  SQL Server 2012 is the version.

答:
If I understand correctly, you want the maximum date if none are NULL, and NULL if at least one is.  If this is right:

```<code>SELECT <normal columns>,
       (CASE WHEN COUNT(*) <> COUNT(ts.PermanentRecallDate) THEN NULL
             ELSE MAX(ts.PermanentRecallDate)
        END) as PERANENTRECALLDATE,
       (CASE WHEN COUNT(*) <> COUNT(ts.ReturnToStoreDate) THEN NULL
             ELSE MAX(ts.ReturnToStoreDate)
        END) as RETURNTOSTOREDATE
</code>```

Title: T-SQL Window Function

Body:
For the sake of example, I have the following data set:
ToyReferenceNumber, Company, CompositeCalculatedField, PermanentRecallDate, ReturnToStoreDate

Basically, there could be 3-4 entries for each item (imaginary company TheToyCompany, or TTC):

TTC-011-0934, TTC, calculation, NULL, 2017-03-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2014-05-01 12:01:01.00
TTC-011-0934, TTC, calculation, NULL, 2011-08-27 12:01:01.00
TTC-994-0132, TTC, calculation, 2017-06-12 12:01:01.00, NULL
TTC-994-0132, TTC, calculation, NULL, 2017-02-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, 2015-03-01 12:01:01.00
TTC-354-0122, TTC, calculation, NULL, NULL

From a business logic standpoint, for the first product (0934), it had a recall multiple times (which printing or prod batch, we don't care), but was fixed and returned to stores after each.

For 0132, it was attempted to fix the defect, but then the company simply decided to scrap the product as it was not selling anyway.

For 0122, a product batch was recalled, fixed, and then sent to stores on 2015-03-01, but a current batch is currently being fixed (hence, the NULL, NULL).

What management wants is a report that current fix-factory billing (e.g. time sheets for guys who fix the toys).

Pseudo-Query:

 For a given product, return only the record with NULL, NULL dates (actively being fixed)
    IF not null, null, return only the record with the PermanentRecallDate
    IF no PermanentRecallDate, return only the record with the latest ReturnToStoreDate

The oracle query was basically the same as the following pseudo-code:

SELECT <normal columns>
,MAX(ts.PermanentRecallDate) KEEP (dense_rank last order by ts.PermanentRecallDate NULLS LAST) PERANENTRECALLDATE
,MAX(ts.ReturnToStoreDate) KEEP (dense_rank last order by ts.ReturnToStoreDate NULLS LAST) RETURNTOSTOREDATE

The oracle query is pretty straightforward, but I need it in T-SQL:

WITH CTE_ToyReferenceExport
AS
(
SELECT ts.ToyReferenceNumber AS TOYNUM
    ,tsh.Company AS COMPANY
    ,MAX(largeSetofCalculations) AS CompositeCalculatedField
    ,MAX(ts.PermanentRecallDate) AS PERMANETRECALL
    ,MAX(ts.ReturnToStoreDate) AS RETURNTOSTORE
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.PermanentRecallDate) as PRDRank
    ,DENSE_RANK() OVER (PARTITION BY ts.ToyReferenceNumber ORDER BY ts.(ReturnToStoreDate) AS RTSDRank

    FROM origin.ToyStaging ts
    JOIN origin.ToyOrders to ON ts.ordernumer = to.ordno
    JOIN origin.ToyShipment tsh ON to.packno = tsh.crateno
    LEFT JOIN origin.Shippers sh ON to.packno = sh.cratenum AND 'calcField' = sh.originfield
GROUP BY ts.ToyReferenceNumber, tsh.Company, ts.permanentrecalldate, ts.returntostoredate
)

There is a lot more to it, but the main thing that trips me up is getting the result set returned by "MAX..Keep Dense_rank last order by.. NULLS LAST" logic.

Any help would be appreciated.  SQL Server 2012 is the version.

Body:
If I understand correctly, you want the maximum date if none are NULL, and NULL if at least one is.  If this is right:

SELECT <normal columns>,
       (CASE WHEN COUNT(*) <> COUNT(ts.PermanentRecallDate) THEN NULL
             ELSE MAX(ts.PermanentRecallDate)
        END) as PERANENTRECALLDATE,
       (CASE WHEN COUNT(*) <> COUNT(ts.ReturnToStoreDate) THEN NULL
             ELSE MAX(ts.ReturnToStoreDate)
        END) as RETURNTOSTOREDATE


来源: stackexchange

问:
How do I make a web app/apiapp in azure private?
I've done this before but the feature seems to have disappeared. I want to host an API in azure but set it to private so that only other azure entities in my subscription can see it. </p>

<p>It used to be achieved with a "private" switch on the webapp/apiapp settings. </p>

答:
Responding to clean up my unanswered questions.

Turns out you can't just define a webapp/apiapp as private anymore and the way to do it now is to wrap it in a private virtual network. As suggested by Jack Zeng (https://stackoverflow.com/users/5760649/jack-zeng) in the comments.

ContentLicense: CC BY-SA 3.0

Body:
I've done this before but the feature seems to have disappeared. I want to host an API in azure but set it to private so that only other azure entities in my subscription can see it.

It used to be achieved with a "private" switch on the webapp/apiapp settings.


问:
convert html in a vb.net textbox
I have a textbox which I need to enter html code into (like  or  for example).

The trouble is this is causing an error writing this back to the database.

A potentially dangerous Request.Form value was detected from the client (tbVOther="test

Is there a way around this without turning off the request validation setting?

答: It might be easier sanitising the input via Javascript replacing the offending characters with safe ones i.e replacing <> with ^ instead </p>

Title: convert html in a vb.net textbox

ContentLicense: CC BY-SA 2.5


问:
How to retrieve row when null then take above record in table,with out using loop and update
```<code>id  name
--------------
1   ACTIVE
2   NULL
3   NULL
4   NULL
5   COMPLETED
6   NULL
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  NULL
11  ACTIVE
</code>```

Output:

```<code>id  name
--------------
1   ACTIVE
2   ACTIVE
3   ACTIVE
4   ACTIVE
5   COMPLETED
6   COMPLETED
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  ACTIVE
11  ACTIVE
</code>```

Task: retrieve null records with above values without using a loop and update.
in will come select statement.

答:
Assuming window functions are supported in your version of SQL Server, this can be done with classifying consecutive nulls in the name column to the same group as the first occurring name for an id. Then use max to get the name for the group and use it to update.

```<code>with cte as (
select id,name,max(name) over(partition by grp) as new_name
from (select *, sum(case when name is null then 0 else 1 end) over(order by id) as grp
      from tbl
     ) t
)
update cte set name = new_name
where name is null;
</code>```

Body:
id  name
--------------
1   ACTIVE
2   NULL
3   NULL
4   NULL
5   COMPLETED
6   NULL
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  NULL
11  ACTIVE

Output:

id  name
--------------
1   ACTIVE
2   ACTIVE
3   ACTIVE
4   ACTIVE
5   COMPLETED
6   COMPLETED
7   COMPLETED
8   COMPLETED
9   ACTIVE
10  ACTIVE
11  ACTIVE

Task: retrieve null records with above values without using a loop and update.
in will come select statement.

Body:
Assuming window functions are supported in your version of SQL Server, this can be done with classifying consecutive nulls in the name column to the same group as the first occurring name for an id. Then use max to get the name for the group and use it to update.

with cte as (
select id,name,max(name) over(partition by grp) as new_name
from (select *, sum(case when name is null then 0 else 1 end) over(order by id) as grp
      from tbl
     ) t
)
update cte set name = new_name
where name is null;


问:
multiple admin on blogger: how to show each admin in their own post with different description and social icons
I have a blogger blog and my friends are interested to join me on the blog. I made two of them authors. Please how can I show each of their Google+ profile in their own post with different description and social icons?

Here is the code for my Google+ profile box:

```<code><!-- blog_post_author_profile -->
         <b:if cond='data:blog.pageType == "item"'>
           <fieldset><legend><h2>About The Author</h2></legend><br/>
           <div class='authorboxwrap'>
           <div class='authorboxfull'>
           <div class='avatar-container'>
            <a href=''>
             <img class='author_avatar img-circle' expr:alt='data:post.author' expr:src='data:post.authorPhoto.url' height='96' width='96'/>
            </a>
           </div>
           <div class='author_description_container'>
            <h4><a href='https://plus.google.com/u/0/106865899677497908784' rel='author'><data:post.author/></a></h4>
             <p>
          <data:post.authorAboutMe/>
             </p>
          <div class='authorsocial'>
             <a class='img-circle' href='http://facebook.com/munir.a.narogo' target='_blank'><i class='fa fa-facebook'/></a>
             <a class='' href='http://twitter.com/manmunir' target='_blank'><i class='fa fa-twitter'/></a>
             <a class='' href='http://instagram.com/manmunir' target='_blank'><i class='fa fa-instagram'/></a>
            <br/><br/><p>Tech Blogger. He is a Technology Enthusiast with a keen eye on the Cyberspace and other tech related developments.</p>
          <div class='clr'/>
          </div>
          </div>
          </div>
             </div></fieldset>
          </b:if>
</code>```

Here is The CSS

```<code>.authorboxwrap {margin-bottom: 30px;} .avatar-container {width: 100%;float: left;padding: 12px 13px;} .avatar-container img {border-radius: 50%;width: 125px;height: auto;border: 5px solid transparent;box-shadow: 0px 0px 20px -5px #000;-moz-box-shadow: 0px 0px 20px -5px #000;-webkit-box-shadow: 0px 0px 20px -5px #000;-ms-box-shadow: 0px 0px 20px -5px #000;-o-box-shadow: 0px 0px 20px -5px #000;} .author_description_container {margin-right: 70px;} .author_description_container h4 {font-weight:600;font-size: 16px;display: block;margin-bottom: 10px;} .author_description_container h4 a{color: #444;} .author_description_container p {font-size: 12px;line-height: 1.7;margin-bottom: 15px;} .authorsocial a {display: inline-block;margin-right: 5px;text-align: center;float:left;margin-right:2px;} .authorsocial a i {width: 30px;height: 20px;padding: 8px 9px;display: block;background: #E9E9E9!important;color: #555;} .author_description_container {margin-left: 120px;} .avatar-container {width: 120px;} .avatar-container img{width:100%;height:auto;} .clr { clear:both; float:none; }
</code>```

答:
Finally it worked! But here is the conditional tag I used

```<code><b:if cond='data:post.author == "First Author Name"'>
<!-- first author description and social icons -->
<b:elseif cond='data:post.author == "Second Author Name"'/>
<!-- second author description and social icons -->
</b:if>
</code>```

Your code gave me the hint to get this one and it worked. Thanks a lot.

Body:
I have a blogger blog and my friends are interested to join me on the blog. I made two of them authors. Please how can I show each of their Google+ profile in their own post with different description and social icons?

Here is the code for my Google+ profile box:

           <fieldset><legend>
About The Author
</legend>

<data:post.author/>

          <data:post.authorAboutMe/>

Tech Blogger. He is a Technology Enthusiast with a keen eye on the Cyberspace and other tech related developments.

</fieldset>

Here is The CSS

.authorboxwrap {margin-bottom: 30px;} .avatar-container {width: 100%;float: left;padding: 12px 13px;} .avatar-container img {border-radius: 50%;width: 125px;height: auto;border: 5px solid transparent;box-shadow: 0px 0px 20px -5px #000;-moz-box-shadow: 0px 0px 20px -5px #000;-webkit-box-shadow: 0px 0px 20px -5px #000;-ms-box-shadow: 0px 0px 20px -5px #000;-o-box-shadow: 0px 0px 20px -5px #000;} .author_description_container {margin-right: 70px;} .author_description_container h4 {font-weight:600;font-size: 16px;display: block;margin-bottom: 10px;} .author_description_container h4 a{color: #444;} .author_description_container p {font-size: 12px;line-height: 1.7;margin-bottom: 15px;} .authorsocial a {display: inline-block;margin-right: 5px;text-align: center;float:left;margin-right:2px;} .authorsocial a i {width: 30px;height: 20px;padding: 8px 9px;display: block;background: #E9E9E9!important;color: #555;} .author_description_container {margin-left: 120px;} .avatar-container {width: 120px;} .avatar-container img{width:100%;height:auto;} .clr { clear:both; float:none; }

Body:
Finally it worked! But here is the conditional tag I used

<b:if cond='data:post.author == "First Author Name"'>
<!-- first author description and social icons -->
<b:elseif cond='data:post.author == "Second Author Name"'/>
<!-- second author description and social icons -->
</b:if>

Your code gave me the hint to get this one and it worked. Thanks a lot.


问:
Split dictionary of lists into list of dictionaries
What i need to do is to convert something like this

```<code>{'key1': [1, 2, 3], 'key2': [4, 5, 6]}
</code>```

into

```<code>[{'key1': 1, 'key2': 4}, {'key1': 2, 'key2': 5}, {'key1': 3, 'key2': 6}]
</code>```

The length of the value lists can vary!
What's the quickest way to do this (preferably without for loops)?

Body:
What i need to do is to convert something like this

{'key1': [1, 2, 3], 'key2': [4, 5, 6]}

into

[{'key1': 1, 'key2': 4}, {'key1': 2, 'key2': 5}, {'key1': 3, 'key2': 6}]

The length of the value lists can vary!
What's the quickest way to do this (preferably without for loops)?

Body:
How about?

d = {'key1': [1, 2, 3], 'key2': [4, 5, 6]}
[dict(zip(d.keys(),i)) for i in zip(*d.values())]

Returns:

[{'key1': 1, 'key2': 4}, {'key1': 2, 'key2': 5}, {'key1': 3, 'key2': 6}]


问:
Generating an overview of RAM in a list of computers by using wmic and modifying output file
I have become responsible for a couple of dozen PC's, that I need to check for internal hard- and software. Our CMDB system isn't up to date, therefore I need to find out what we actually have. I have spent several hours trying to figure a way to make a batch script that is easy to use and generates easy to read output. I wanted to get started with the physical memory/RAM.

I found the wmic command, and was able to specify it to get only the information I need and use a text file and FOR loop to cycle through a list of SNs and output the RAM of each computer into a text file:

```<code>IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
wmic /node:%%i memorychip get capacity >> output.txt
)
EXIT /B
</code>```

This only works when the PC's are online.

So far, so good.

To also see the serial number of the computer, to - for example - use Excel to warp the text file into a table, I added an ECHO line:

```<code>IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
@Echo Serialnumber %%i >> output.txt
wmic /node:%%i memorychip get capacity >> output.txt
)
EXIT /B
</code>```

But all the wmic output lines got weird spaces between each character and cramped into one line, whereas before they were nicely split into as many lines as there were different "words"  Why does this happen?

If I manually remove all " " characters from the output file, it transforms back into what i would expect: Everything back to neat lines

I hoped I could directly remove the "space" characters from the wmic function's output, but I couldn't.  For example, I found this trick to get the output of wmic into variables, which I though I could then manipulate:

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
@echo off
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`wmic /node:2CMFFY1 memorychip get capacity`) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ECHO %var4%
ECHO %var5%
ENDLOCAL
</code>```

This piece of code neatly creates separate lines if I add a serial number manually

But I can't get it to be filled with the serial numbers from the input.txt file. If I try this code, it still prints the serial number lines, but apparently skips the second FOR loop:

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
@Echo Serialnumber %%i >> output.txt
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`wmic /node:%%i memorychip get capacity`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ECHO %var4%
ECHO %var5%
)
ENDLOCAL
EXIT /B
</code>```

If I look at what is actually happening, it seems that in some cases, the second FOR does get the correct serial number passed into the wmic command, but it still doesn't work, I only get the lines of the first ECHO.

I found another forum's thread about WMIC posting unicode outcomes, which can't be interpreted correctly, and some attempts to solve this. I tried integrating this into my code, but it doesn't work 100%, it now adds extra "Echo is ON" lines to the results.

```<code>IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
ECHO Serialnumber %%i>>output.txt
FOR /F "tokens=*" %%j IN ('wmic /node:%%i memorychip get capacity') DO @echo %%j>>output.txt 2>&1
)
</code>```

If I could get to write the WMIC outcome to separate variables, there might be a way to integrate this line of code to remove the spaces:

```<code>set str=%str: =%
</code>```

A final step would be, to reduce the RAM space in bytes to a more readable GB number. I have seen some things that might achieve that, I only need to get the strings into variables to manipulate them.

But as I said, I'm an utter noob, with only a decade-old knowledge of some visual basic and C++ and some HTML/JAVA/CSS programming. There's probably a simple solution to this problem...

Any help would be immensely appreciated! Also, if anyone can recommend a website or a book that takes you through cmd/batch scripting step by step with general explanation of syntax structure, information how variables work, etc, that would also be immensely helpful :)

答:
It's hard to tell from your story exactly what you want, so here's my best guess:

@Echo Off
(For /F "Delims=" %%A In (input.txt) Do (Echo Serialnumber %%A
    For /F "Skip=1" %%B In ('WMIC /Node:%%A MemoryChip Get Capacity'
    ) Do For /F %%C In ("%%B") Do Echo %%C))>output.txt
Exit/B
```

Body:
I have become responsible for a couple of dozen PC's, that I need to check for internal hard- and software. Our CMDB system isn't up to date, therefore I need to find out what we actually have. I have spent several hours trying to figure a way to make a batch script that is easy to use and generates easy to read output. I wanted to get started with the physical memory/RAM.

I found the wmic command, and was able to specify it to get only the information I need and use a text file and FOR loop to cycle through a list of SNs and output the RAM of each computer into a text file:

IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
wmic /node:%%i memorychip get capacity >> output.txt
)
EXIT /B

This only works when the PC's are online.

So far, so good.

To also see the serial number of the computer, to - for example - use Excel to warp the text file into a table, I added an ECHO line:

IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
@Echo Serialnumber %%i >> output.txt
wmic /node:%%i memorychip get capacity >> output.txt
)
EXIT /B

But all the wmic output lines got weird spaces between each character and cramped into one line, whereas before they were nicely split into as many lines as there were different "words"  Why does this happen?

If I manually remove all " " characters from the output file, it transforms back into what i would expect: Everything back to neat lines

I hoped I could directly remove the "space" characters from the wmic function's output, but I couldn't.  For example, I found this trick to get the output of wmic into variables, which I though I could then manipulate:

SETLOCAL ENABLEDELAYEDEXPANSION
@echo off
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`wmic /node:2CMFFY1 memorychip get capacity`) DO (
SET var!count!=%%F
SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ECHO %var4%
ECHO %var5%
ENDLOCAL

This piece of code neatly creates separate lines if I add a serial number manually

But I can't get it to be filled with the serial numbers from the input.txt file. If I try this code, it still prints the serial number lines, but apparently skips the second FOR loop:

SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
@Echo Serialnumber %%i >> output.txt
SET count=1
FOR /F "tokens=* USEBACKQ" %%F IN (`wmic /node:%%i memorychip get capacity`) DO (
  SET var!count!=%%F
  SET /a count=!count!+1
)
ECHO %var1%
ECHO %var2%
ECHO %var3%
ECHO %var4%
ECHO %var5%
)
ENDLOCAL
EXIT /B

If I look at what is actually happening, it seems that in some cases, the second FOR does get the correct serial number passed into the wmic command, but it still doesn't work, I only get the lines of the first ECHO.

I found another forum's thread about WMIC posting unicode outcomes, which can't be interpreted correctly, and some attempts to solve this. I tried integrating this into my code, but it doesn't work 100%, it now adds extra "Echo is ON" lines to the results.

IF EXIST output.txt DEL /Q output.txt >NUL
FOR /F "tokens=*" %%i IN (input.txt) DO (
ECHO Serialnumber %%i>>output.txt
FOR /F "tokens=*" %%j IN ('wmic /node:%%i memorychip get capacity') DO @echo %%j>>output.txt 2>&1
)

If I could get to write the WMIC outcome to separate variables, there might be a way to integrate this line of code to remove the spaces:

set str=%str: =%

A final step would be, to reduce the RAM space in bytes to a more readable GB number. I have seen some things that might achieve that, I only need to get the strings into variables to manipulate them.

But as I said, I'm an utter noob, with only a decade-old knowledge of some visual basic and C++ and some HTML/JAVA/CSS programming. There's probably a simple solution to this problem...

Any help would be immensely appreciated! Also, if anyone can recommend a website or a book that takes you through cmd/batch scripting step by step with general explanation of syntax structure, information how variables work, etc, that would also be immensely helpful :)


问:
Entity Framework nesting classes inside class
I trying to make a data model that allows users to add companies to a list and then when added, allow further details on the company to be added, this is to allow things like employee information to be added. However, I haven't been able to figure out how to do this without creating multiple class, controller files and view folders.

My current code on the model class file is:

```<code>namespace Intranet.Models
{
    public class AddCustomers
    {
        public int AddCustomersID { get; set; }
        public string CompanyName { get; set; }
        ...

        public class EmployeeInfo
        {
            public int EmployeeInfoID { get; set; }
            public string Forename { get; set; }
            ...
        }

        public class ContactInfo
        {
            public int ContactInfoID { get; set; }
            public string Code { get; set; }
            ...
        }
    }
}
</code>```

Context file:

```<code>public IntranetContext() : base("name=IntranetContext")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

public System.Data.Entity.DbSet<Intranet.Models.AddCustomers> AddCustomers { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.AddCustomers.EmployeeInfo> EmployeeInfo { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.AddCustomers.ContactInfo> ContactInfo { get; set; }
</code>```

This does not work however as the nested classes do not appear anywhere, except in my local database.

Is there a way I can get the nested classes to appear in the details view for each customer? Or is there a completely different way to do this?

答:
```<code>namespace Intranet.Models
{
    public class AddCustomers
    {
        public int AddCustomersID { get; set; }
        public string CompanyName { get; set; }
        public EmployeeInfo EmployeeInfo { get; set; }
        public ContactInfo ContactInfo { get; set; }
        ...
    }

    public class EmployeeInfo
    {
        public int EmployeeInfoID { get; set; }
        public string Forename { get; set; }
        ...
    }

    public class ContactInfo
    {
        public int ContactInfoID { get; set; }
        public string Code { get; set; }
        ...
    }
}
</code>```

Then in your context you would have:

```<code>public System.Data.Entity.DbSet<Intranet.Models.AddCustomers> AddCustomers { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.EmployeeInfo> EmployeeInfo { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.ContactInfo> ContactInfo { get; set; }
</code>```

..and in controller you could do things like:

```<code>var customer = context.AddCustomers
    .FirstOrDefault(c=>c.EmployeeInfo.Forename=="bob");
...
</code>```

Body:
I trying to make a data model that allows users to add companies to a list and then when added, allow further details on the company to be added, this is to allow things like employee information to be added. However, I haven't been able to figure out how to do this without creating multiple class, controller files and view folders.

My current code on the model class file is:

namespace Intranet.Models
{
    public class AddCustomers
    {
        public int AddCustomersID { get; set; }
        public string CompanyName { get; set; }
        ...

        public class EmployeeInfo
        {
            public int EmployeeInfoID { get; set; }
            public string Forename { get; set; }
            ...
        }

        public class ContactInfo
        {
            public int ContactInfoID { get; set; }
            public string Code { get; set; }
            ...
        }
    }
}

Context file:

public IntranetContext() : base("name=IntranetContext")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

public System.Data.Entity.DbSet<Intranet.Models.AddCustomers> AddCustomers { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.AddCustomers.EmployeeInfo> EmployeeInfo { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.AddCustomers.ContactInfo> ContactInfo { get; set; }

This does not work however as the nested classes do not appear anywhere, except in my local database.

Is there a way I can get the nested classes to appear in the details view for each customer? Or is there a completely different way to do this?

Body:
namespace Intranet.Models
{
    public class AddCustomers
    {
        public int AddCustomersID { get; set; }
        public string CompanyName { get; set; }
        public EmployeeInfo EmployeeInfo { get; set; }
        public ContactInfo ContactInfo { get; set; }
        ...
    }

    public class EmployeeInfo
    {
        public int EmployeeInfoID { get; set; }
        public string Forename { get; set; }
        ...
    }

    public class ContactInfo
    {
        public int ContactInfoID { get; set; }
        public string Code { get; set; }
        ...
    }
}

Then in your context you would have:

public System.Data.Entity.DbSet<Intranet.Models.AddCustomers> AddCustomers { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.EmployeeInfo> EmployeeInfo { get; set; }
public System.Data.Entity.DbSet<Intranet.Models.ContactInfo> ContactInfo { get; set; }

..and in controller you could do things like:

var customer = context.AddCustomers
    .FirstOrDefault(c=>c.EmployeeInfo.Forename=="bob");
...


问:
Wildcard when Traversing JSONB Array in Postgres
We're currently trialing JSONB as a data type for order data in a system we're building. As the document is fairly large, Here is the first part of it (the part that matters):

```<code>{
"appMessage": {
    "order": {
        "customerSurname": "Tyreus",
        "shipment": {
            "asnNumber": "CC56477332",
            "shippingStore": "3321"
        },
        "orderNumber": "7991218655",
        "propositionCollectionStoreNumber": "5656",
        "collectionPointId": "4",
        "customerFirstname": "Isaac",
        "orderLine": [{
            "collectionWindowFrom": "2017-01-18T09:00:00+00:00",
            "lineNo": "1",
            "skuNo": "7654321",
            "createdDateTime": "2017-01-17T17:54:31+00:00",
</code>```

The issue we're facing is when it comes to applying a wildcard to something in an array. Using the example above, how would I do a wildcard search to say 'retrieve all records with a skuNo starting with 7'?

Outside of an array I have tested wildcards such as:

```<code>SELECT
    *
FROM
    ORDERS
WHERE
    ORDER_DATA->'appMessage'->'message'->>'enterpriseCode' LIKE 'TU%';
</code>```

With success. But as soon as arrays enter the equation, everything becomes unclear...

Any help would be greatly appreciated.

答:
You can unnest JSONB array using jsonb_array_elements and then filter it:</p>

```<code>--Using 'intermediary' table unnested_json_array
WITH test_data(json_column) AS (

    SELECT
        jsonb_build_array(
            jsonb_build_object('lineNo', '1', 'skuNo', '7654321'),
            jsonb_build_object('lineNo', '2', 'skuNo', '1654321'),
            jsonb_build_object('lineNo', '3', 'skuNo', '7654321')
        )

), unnested_json_array(json_column) AS (
    SELECT jsonb_array_elements((SELECT * FROM test_data))
)
SELECT * FROM unnested_json_array WHERE json_column->>'skuNo' ILIKE '7%';

--Or even simpler using LATERAL JOIN
WITH test_data(json_column) AS (
    SELECT
        jsonb_build_array(
            jsonb_build_object('lineNo', '1', 'skuNo', '7654321'),
            jsonb_build_object('lineNo', '2', 'skuNo', '1654321'),
            jsonb_build_object('lineNo', '3', 'skuNo', '7654321')
        )
)
SELECT
    json_elements.*
FROM
    test_data
    JOIN LATERAL jsonb_array_elements(test_data.json_column) AS json_elements (order_line) ON TRUE
WHERE
    order_line->>'skuNo' ILIKE '7%';

--In your case:
SELECT
    json_elements.*
FROM
    ORDERS
    JOIN LATERAL jsonb_array_elements(ORDER_DATA->'appMessage'->'order'->'orderLine') AS json_elements (order_line) ON TRUE
WHERE
    order_line->>'skuNo' LIKE '7%';
</code>```

Body:
We're currently trialing JSONB as a data type for order data in a system we're building. As the document is fairly large, Here is the first part of it (the part that matters):

{
"appMessage": {
    "order": {
        "customerSurname": "Tyreus",
        "shipment": {
            "asnNumber": "CC56477332",
            "shippingStore": "3321"
        },
        "orderNumber": "7991218655",
        "propositionCollectionStoreNumber": "5656",
        "collectionPointId": "4",
        "customerFirstname": "Isaac",
        "orderLine": [{
            "collectionWindowFrom": "2017-01-18T09:00:00+00:00",
            "lineNo": "1",
            "skuNo": "7654321",
            "createdDateTime": "2017-01-17T17:54:31+00:00",

The issue we're facing is when it comes to applying a wildcard to something in an array. Using the example above, how would I do a wildcard search to say 'retrieve all records with a skuNo starting with 7'?

Outside of an array I have tested wildcards such as:

SELECT
    *
FROM
    ORDERS
WHERE
    ORDER_DATA->'appMessage'->'message'->>'enterpriseCode' LIKE 'TU%';

With success. But as soon as arrays enter the equation, everything becomes unclear...

Any help would be greatly appreciated.

Body:
You can unnest JSONB array using jsonb_array_elements and then filter it:

--Using 'intermediary' table unnested_json_array
WITH test_data(json_column) AS (

    SELECT
        jsonb_build_array(
            jsonb_build_object('lineNo', '1', 'skuNo', '7654321'),
            jsonb_build_object('lineNo', '2', 'skuNo', '1654321'),
            jsonb_build_object('lineNo', '3', 'skuNo', '7654321')
        )

), unnested_json_array(json_column) AS (
    SELECT jsonb_array_elements((SELECT * FROM test_data))
)
SELECT * FROM unnested_json_array WHERE json_column->>'skuNo' ILIKE '7%';

--Or even simpler using LATERAL JOIN
WITH test_data(json_column) AS (
    SELECT
        jsonb_build_array(
            jsonb_build_object('lineNo', '1', 'skuNo', '7654321'),
            jsonb_build_object('lineNo', '2', 'skuNo', '1654321'),
            jsonb_build_object('lineNo', '3', 'skuNo', '7654321')
        )
)
SELECT
    json_elements.*
FROM
    test_data
    JOIN LATERAL jsonb_array_elements(test_data.json_column) AS json_elements (order_line) ON TRUE
WHERE
    order_line->>'skuNo' ILIKE '7%';

--In your case:
SELECT
    json_elements.*
FROM
    ORDERS
    JOIN LATERAL jsonb_array_elements(ORDER_DATA->'appMessage'->'order'->'orderLine') AS json_elements (order_line) ON TRUE
WHERE
    order_line->>'skuNo' LIKE '7%';


问:
Dynamically Filter an Array of Objects in Vue.js
I have a Vue.js app. In this app, I'm trying to dynamically apply filter value to an Array of objects. Each object in the Array has fields. I'm trying to filter these objects by field values. Each field can be filtered by multiple values.

At this time, I have been unsuccessful in figuring out how to do this filtering. I've tried using JavaScript's baked-in filter function. However, that always returned an empty result set for me. I've put together this Fiddle, which includes this code:

```<code>new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',

    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
      var f = this.dataFilters[this.currentFilterProperty];
      if (!f) {
        this.dataFilters = {};
        this.dataFilters[this.currentFilterProperty] = [ this.currentFilterValue ];
      } else {
        this.dataFilters[this.currentFilterProperty].push(this.currentFilterValue);
      }

      // How to apply filter?
    }
  }
})
</code>```

I'm not sure how to apply the filters to the data object.

答:
Here is working solution By checking captaining condition

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: 'name',
    currentFilterValue: '',
    filteredData:[],
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    addFilters:[],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
     if(!this.currentFilterValue){
      return false;
     }
      var obj = {};
      this.addFilters.push({name:this.currentFilterProperty,value:this.currentFilterValue});
      this.currentFilterValue = "";
     var vm = this;
      this.dataFilters = this.data
      //var temp = [];
      for(var i in vm.addFilters){
        this.dataFilters = this.dataFilters.filter(function(a,b){
        return ((a[vm.addFilters[i].name]).toString().toLowerCase()).indexOf((vm.addFilters[i].value).toString().toLowerCase()) !== -1;
        });
      }
      // How to apply filter?
    }
  },
  mounted(){
    this.dataFilters = this.data;
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    <select v-model="currentFilterProperty">
      <option value="name">Name</option>
      <option value="age">Age</option>
      <option value="birthday">Birthdate</option>
    </select>
    <input placeholder="filter value" v-model="currentFilterValue" />

    <button v-on:click="addFilter">
    add filter
    </button>
  </div>
  <div v-for="(filter,index) in addFilters">{{filter.name}} : {{filter.value}}</div>
  <hr />

  <table>
    <tbody>
      <tr v-for="(record, index) in dataFilters">
        <td style="padding-right:18px;">{{ record.name }}</td>
        <td style="padding-right:18px;">{{ record.age }}</td>
        <td>{{ record.birthday }}</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Body:
I have a Vue.js app. In this app, I'm trying to dynamically apply filter value to an Array of objects. Each object in the Array has fields. I'm trying to filter these objects by field values. Each field can be filtered by multiple values.

At this time, I have been unsuccessful in figuring out how to do this filtering. I've tried using JavaScript's baked-in filter function. However, that always returned an empty result set for me. I've put together this Fiddle, which includes this code:

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',

    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
      var f = this.dataFilters[this.currentFilterProperty];
      if (!f) {
        this.dataFilters = {};
        this.dataFilters[this.currentFilterProperty] = [ this.currentFilterValue ];
      } else {
        this.dataFilters[this.currentFilterProperty].push(this.currentFilterValue);
      }

      // How to apply filter?
    }
  }
})

I'm not sure how to apply the filters to the data object.

Body:
Here is working solution By checking captaining condition

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: 'name',
    currentFilterValue: '',
    filteredData:[],
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    addFilters:[],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
     if(!this.currentFilterValue){
      return false;
     }
      var obj = {};
      this.addFilters.push({name:this.currentFilterProperty,value:this.currentFilterValue});
      this.currentFilterValue = "";
     var vm = this;
      this.dataFilters = this.data
      //var temp = [];
      for(var i in vm.addFilters){
        this.dataFilters = this.dataFilters.filter(function(a,b){
        return ((a[vm.addFilters[i].name]).toString().toLowerCase()).indexOf((vm.addFilters[i].value).toString().toLowerCase()) !== -1;
        });
      }
      // How to apply filter?
    }
  },
  mounted(){
    this.dataFilters = this.data;
  }
})

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    <select v-model="currentFilterProperty">
      <option value="name">Name</option>
      <option value="age">Age</option>
      <option value="birthday">Birthdate</option>
    </select>
    <input placeholder="filter value" v-model="currentFilterValue" />

    <button v-on:click="addFilter">
    add filter
    </button>
  </div>
  <div v-for="(filter,index) in addFilters">{{filter.name}} : {{filter.value}}</div>
  <hr />

  <table>
    <tbody>
      <tr v-for="(record, index) in dataFilters">
        <td style="padding-right:18px;">{{ record.name }}</td>
        <td style="padding-right:18px;">{{ record.age }}</td>
        <td>{{ record.birthday }}</td>
      </tr>
    </tbody>
  </table>
</div>


问:
JMeter - modify contents of jtl file
While executing JMeter test cases through command line, system generates jtl file having following header :

timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect

I need results only for timestamp, elapsed, label, responseCode.

How can I achieve this?

答:
Follow the manual about Results file configuration you should mark the properties as false except for the ones you want.

For example keep jmeter.save.saveservice.label=true

And change others as jmeter.save.saveservice.response_message=false

Title: JMeter - modify contents of jtl file


问:
java 8 stream API filter out empty value from map
i have a map, need to operate on each entry's value, and return the modified map. I managed to get it working, but the resulted map contains entries with empty value, and I want to remove those entries but cannot with Java 8 stream API.

here is my original code:

```<code>Map<String, List<Test>> filtered = Maps.newHashMap();
for (String userId : userTests.keySet()) {
    List<Test> tests = userTests.get(userId);
    List<Test> filteredTests = filterByType(tests, supportedTypes);

    if (!CollectionUtils.isEmpty(filteredTests)) {
        filtered.put(userId, filteredTests);
    }
}
return filtered;
</code>```

and here is my Java 8 stream API version:

```<code>userTests.entrySet().stream()
         .forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty());
        return userTests;
</code>```

how can i remove entries with empty/null value from the map?

is there better way to write the code in stream API, so far I don't see it's better than my original code

答:
Try inserting the filter in-line:    </p>

```<code>userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty())
.forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));
</code>```

Body:
i have a map, need to operate on each entry's value, and return the modified map. I managed to get it working, but the resulted map contains entries with empty value, and I want to remove those entries but cannot with Java 8 stream API.

here is my original code:

Map<String, List<Test>> filtered = Maps.newHashMap();
for (String userId : userTests.keySet()) {
    List<Test> tests = userTests.get(userId);
    List<Test> filteredTests = filterByType(tests, supportedTypes);

    if (!CollectionUtils.isEmpty(filteredTests)) {
        filtered.put(userId, filteredTests);
    }
}
return filtered;

and here is my Java 8 stream API version:

userTests.entrySet().stream()
         .forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty());
        return userTests;

how can i remove entries with empty/null value from the map?

is there better way to write the code in stream API, so far I don't see it's better than my original code

Body:
Try inserting the filter in-line:

userTests.entrySet().stream().filter(entry -> !entry.getValue().isEmpty())
.forEach(entry -> entry.setValue(filterByType(entry.getValue(), supportedTypes)));


问:
Logstash doesnt read from configured input file
I am trying to configure my Logstash to read from a specified log file. When I configure it to read from stdin it works as expected, my input results in a message from Logstash and displays in my Kibana UI.

```<code>$ cat /tmp/logstash-stdin.conf
input {
  stdin {}
}
output {
  elasticsearch { hosts => ["localhost:9200"] }
  stdout { codec => rubydebug }

}

$./logstash -f /tmp/logstash-stdin.conf
WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults
Could not find log4j2 configuration at path //usr/share/logstash/config/log4j2.properties. Using default config which logs errors to the console
The stdin plugin is now waiting for input:
hellloooo
{
      "@version" => "1",
          "host" => "myhost.com",
    "@timestamp" => 2017-11-17T16:05:41.595Z,
       "message" => "hellloooo"
}
</code>```

However, when I run Logstash with a file input I get no indication that the file is loaded into Logstash, and it does not show in Kibana.

```<code>$ cat /tmp/logstash-simple.conf
input {
  file {
    path => "/tmp/test_log.txt"
    type => "syslog"
  }
}
output {
  elasticsearch { hosts => ["localhost:9200"] }
  stdout { codec => rubydebug }
}

$ ./logstash -f /tmp/logstash-simple.conf
WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults
Could not find log4j2 configuration at path //usr/share/logstash/config/log4j2.properties. Using default config which logs errors to the console
</code>```

Any suggestions of how I can troubleshoot why my Logstash is not ingesting the configured file?

答: By default the file input plugin starts reading at the end of the file, so only lines added after Logstash starts will be processed. To read all existing lines upon startup add the option "start_position" => "beginning" to the configuration, as explained in documentation.

Body:
I am trying to configure my Logstash to read from a specified log file. When I configure it to read from stdin it works as expected, my input results in a message from Logstash and displays in my Kibana UI.

$ cat /tmp/logstash-stdin.conf
input {
  stdin {}
}
output {
  elasticsearch { hosts => ["localhost:9200"] }
  stdout { codec => rubydebug }

}

$./logstash -f /tmp/logstash-stdin.conf
WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults
Could not find log4j2 configuration at path //usr/share/logstash/config/log4j2.properties. Using default config which logs errors to the console
The stdin plugin is now waiting for input:
hellloooo
{
      "@version" => "1",
          "host" => "myhost.com",
    "@timestamp" => 2017-11-17T16:05:41.595Z,
       "message" => "hellloooo"
}

However, when I run Logstash with a file input I get no indication that the file is loaded into Logstash, and it does not show in Kibana.

$ cat /tmp/logstash-simple.conf
input {
  file {
    path => "/tmp/test_log.txt"
    type => "syslog"
  }
}
output {
  elasticsearch { hosts => ["localhost:9200"] }
  stdout { codec => rubydebug }
}

$ ./logstash -f /tmp/logstash-simple.conf
WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults
Could not find log4j2 configuration at path //usr/share/logstash/config/log4j2.properties. Using default config which logs errors to the console

Any suggestions of how I can troubleshoot why my Logstash is not ingesting the configured file?


问:
collection counter pretty formatting
I have the following code in order count the amount of instances occur in a log file. But i am trying to print it out a little nicer to read, but i can't figure it out. Here is what i have so far

```<code>for key, count in collections.Counter(traffic_list).most_common():
    print ('{}: {}'.format(key,count))
</code>```

And i can't seem to format the first {}

When i print out the collection it looks like this:

```<code>(‘192.168.10.5’, ’10.10.10.10’, ‘http’): 76
(‘192.168.10.6’, ’10.10.10.10’, ‘http’): 34
(‘192.168.10.7’, ’10.10.10.11’, ‘http’): 32
(‘192.168.10.8’, ’10.10.10.10’, ‘http’): 21
</code>```

I am trying to get it to look like this:

```<code>Source: 192.168.10.5 -> Destination: 10.10.10.10 -> Servive: http -> Count: 76
</code>```

But i can't get it look like that

答:
```<code>for key, count in collections.Counter(traffic_list).most_common():
    print ('Source: {} -> Destination: {} -> Service: {} -> Count: {}'.format(key[0], key[1], key[2], count))
</code>```

Title: collection counter pretty formatting

Body:
I have the following code in order count the amount of instances occur in a log file. But i am trying to print it out a little nicer to read, but i can't figure it out. Here is what i have so far

for key, count in collections.Counter(traffic_list).most_common():
    print ('{}: {}'.format(key,count))

And i can't seem to format the first {}

When i print out the collection it looks like this:

(‘192.168.10.5’, ’10.10.10.10’, ‘http’): 76
(‘192.168.10.6’, ’10.10.10.10’, ‘http’): 34
(‘192.168.10.7’, ’10.10.10.11’, ‘http’): 32
(‘192.168.10.8’, ’10.10.10.10’, ‘http’): 21

I am trying to get it to look like this:

Source: 192.168.10.5 -> Destination: 10.10.10.10 -> Servive: http -> Count: 76

But i can't get it look like that


问:
How to privilege escalate www-data when you're logged in as www-data
On Linux, how can I give www-data more permissions/privileges when I am logged in as that user?  whoami = www-data

A bit of background. I have performed an ethical hack on a web application, I have managed to upload a file by bypassing the extension type which allows me to open a remote shell through netcap. The issue is, the default user for netcap is www-data and I cannot change user or escalate as I do not know how.

Any help would be great!

答:
It may be intentional or maybe not, but you're basiclly asking "How to hack". If this is in purpose of homework, please add the homework tag to your questions.

Since you're saying it's a pentest, I'll assume this.

The first thing to do is to see what file do you have access to, and what you can do with them, and then perform the basic task of a pentest like checking the versions of the used packages, softwares or framework and to see if they're any known exploit on them.


问:
How to handle 404s in an observable request Angular
Problem i'm trying to fix:
I'm getting a lot of 404 not found in the console and I want to handle these.

I have these 2 methods in my angular code:

```<code>getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email);
}

isEmailAddressAvailable(email: string) {
    var user: User;
    var response = this.getUserByEmailAddress(email);
    response.subscribe(
       usr => user == usr,
       error => user == undefined);
  if (user === undefined) {
  return true;
  }
  else {
  return false;
  }
}
</code>```

This works as expected, when you call the end point if no user is found a 404 not found it returned.

What I am trying to do

I want to add a .catch() to the .get() request in getUserByEmailAddress()to handle these 404s and mask them from appearing in the console, however when i try to add it, I don't understand what i need to return for the observable, I've tried:

```<code>.catch(err => { return Observable.of(undefined)})
</code>```

but i don't think this is quite right.

Thanks for the help!

答:
You can go ahead with either using map or do methods to check for the status code.

```<code>    getUserByEmailAddress(email: string): Observable<User> {
        return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email).map(res => {
            if(res.status ==404) {
               throw new Error('This request has failed ' + res.status);
            }
           else {
              return res.json();
          }
   }).catch(err =>  {
      //custom logic goes here
      return Observable.throw(err);
      });
    }
</code>```

snippet with 'do'

```<code>getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email).do(res => {
    if(res.status ==404) {
     //custom logic goes here
    }
});
</code>```

Body:
Problem i'm trying to fix:
I'm getting a lot of 404 not found in the console and I want to handle these.

I have these 2 methods in my angular code:

getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email);
}

isEmailAddressAvailable(email: string) {
    var user: User;
    var response = this.getUserByEmailAddress(email);
    response.subscribe(
       usr => user == usr,
       error => user == undefined);
  if (user === undefined) {
  return true;
  }
  else {
  return false;
  }
}

This works as expected, when you call the end point if no user is found a 404 not found it returned.

What I am trying to do

I want to add a .catch() to the .get() request in getUserByEmailAddress()to handle these 404s and mask them from appearing in the console, however when i try to add it, I don't understand what i need to return for the observable, I've tried:

.catch(err => { return Observable.of(undefined)})

but i don't think this is quite right.

Thanks for the help!

Body:
You can go ahead with either using map or do methods to check for the status code.

    getUserByEmailAddress(email: string): Observable<User> {
        return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email).map(res => {
            if(res.status ==404) {
               throw new Error('This request has failed ' + res.status);
            }
           else {
              return res.json();
          }
   }).catch(err =>  {
      //custom logic goes here
      return Observable.throw(err);
      });
    }

snippet with 'do'

getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email).do(res => {
    if(res.status ==404) {
     //custom logic goes here
    }
});


问:
doc,docx file into pdf using shell_exec
i want to convert doc,docx file into pdf using libreofficec .i had found many question related to this but one of these not helpful to me so i post my qwestion over here
here is my code

```<code>     $resume = Input::file('resume');
        $extenstion = 'pdf';
        $datafiles = 'Resume_'.str_random(10).'.'.$extenstion;
          $resume ->move(public_path('datafiles/APPL'), $datafiles);
</code>```

how i can mere above code in this for ex i want to convert a file into pdf and then assign a $datafile after that i want to move this file  to this location datafiles/APPL or is there any way to assign $datafile directly to below code or eg

```<code>  shell_exec('start /wait soffice --headless --convert-to pdf --outdir --savefile name as  $datafiles "./publicapp" "'.$resume.'"'); // is this possible or other correct way

  shell_exec('start /wait soffice --headless --convert-to pdf --outdir "./publicapp" "'.$resume.'"');
</code>```

答:
simplest wy is to use "unoconv":</p>

```<code>sudo apt-get install unoconv
doc2pdf respondus-docx-sample-file.docx
</code>```

Title: doc,docx file into pdf using shell_exec

Body:
i want to convert doc,docx file into pdf using libreofficec .i had found many question related to this but one of these not helpful to me so i post my qwestion over here
here is my code

     $resume = Input::file('resume');
        $extenstion = 'pdf';
        $datafiles = 'Resume_'.str_random(10).'.'.$extenstion;
          $resume ->move(public_path('datafiles/APPL'), $datafiles);

how i can mere above code in this for ex i want to convert a file into pdf and then assign a $datafile after that i want to move this file  to this location datafiles/APPL or is there any way to assign $datafile directly to below code or eg

  shell_exec('start /wait soffice --headless --convert-to pdf --outdir --savefile name as  $datafiles "./publicapp" "'.$resume.'"'); // is this possible or other correct way

  shell_exec('start /wait soffice --headless --convert-to pdf --outdir "./publicapp" "'.$resume.'"');

Body:
simplest wy is to use "unoconv":

sudo apt-get install unoconv
doc2pdf respondus-docx-sample-file.docx


问:
UITableViewCell not always selectable?
I'm in the middle of trying to debug an issue with a new app, and something isn't right.  In the app, I'm setting up custom UITableViewCells by adding 2 UILabels and 1 UIImageView directly to the cell.contentView

In my app, certain table view cells werent selectable ( they werent responding to tap events ).  The 2nd cell on the screen was always never selectable, and then random other cells also werent selectable.

In my effort to debug, I stripped everything down the following bare essentials of code:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"ReviewCell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  }
  cell.textLabel.text = @"foo";
  return cell;
}
</code>```

Even this is generic, boiler plate code, that looks like the following:

not all the cells are selectable.

What am I missing?

update

as an updated here is my row selection code if interested

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ReviewWebViewController *rvc = [[ReviewWebViewController alloc] initWithReview:[self.reviews objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:rvc animated:YES];
    [rvc release], rvc=nil;
}
</code>```

答:
I got hit by a similar sounding bug a few weeks ago. I had buttons in a scroll view that weren't responding to touches. It turned out to be an invisible UILabel that I left in my IB file, never filled with text and forgot about. It was sitting over the buttons and intercepting their touches.

The way I found it was to loop through all the subviews of the scroll view, turning the background color of each view yellow. Could you have a stray view which is interfering with touches?

You could also try sizing the labels and images in your cell to something tiny (10x10) to see if they are interfering.
As a last resort, you could start with fresh code and add back in parts to see where it breaks.

One last point: You say that you're using a custom UITableViewCell, but you initialize the cell with the default type:

```<code>cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:CellIdentifier] autorelease];
</code>```

Shouldn't you be using your custom cell here? Is that just to simplify the example?

Title: UITableViewCell not always selectable?

Body:
I'm in the middle of trying to debug an issue with a new app, and something isn't right.  In the app, I'm setting up custom UITableViewCells by adding 2 UILabels and 1 UIImageView directly to the cell.contentView

In my app, certain table view cells werent selectable ( they werent responding to tap events ).  The 2nd cell on the screen was always never selectable, and then random other cells also werent selectable.

In my effort to debug, I stripped everything down the following bare essentials of code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"ReviewCell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  }
  cell.textLabel.text = @"foo";
  return cell;
}

Even this is generic, boiler plate code, that looks like the following:

not all the cells are selectable.

What am I missing?

update

as an updated here is my row selection code if interested

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ReviewWebViewController *rvc = [[ReviewWebViewController alloc] initWithReview:[self.reviews objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:rvc animated:YES];
    [rvc release], rvc=nil;
}

Body:
I got hit by a similar sounding bug a few weeks ago. I had buttons in a scroll view that weren't responding to touches. It turned out to be an invisible UILabel that I left in my IB file, never filled with text and forgot about. It was sitting over the buttons and intercepting their touches.

The way I found it was to loop through all the subviews of the scroll view, turning the background color of each view yellow. Could you have a stray view which is interfering with touches?

You could also try sizing the labels and images in your cell to something tiny (10x10) to see if they are interfering.
As a last resort, you could start with fresh code and add back in parts to see where it breaks.

One last point: You say that you're using a custom UITableViewCell, but you initialize the cell with the default type:

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:CellIdentifier] autorelease];

Shouldn't you be using your custom cell here? Is that just to simplify the example?


问:
Error: Failed to run "javac -version" while running cordova build
I use the JDK in my NetBeans Java webservice by just pointing the directory where I've downloaded it to the project on NetBeans. Cant I do the same to build my Ionic APK? I tried setting the JAVA_HOME inside .bashrc with this line

```<code>export JAVA_HOME=$HOME/Apps/jdk1.8.0_144
</code>```

But it didnt work, I dont get any return from java -version in terminal.

答:
Not only the JAVA_HOME environment variable should be set, but also JDK binaries should be on your PATH:

```<code>JAVA_HOME=$HOME/Apps/jdk1.8.0_144
export JAVA_HOME
export PATH="${JAVA_HOME}/bin:${PATH}"
</code>```

Body:
I use the JDK in my NetBeans Java webservice by just pointing the directory where I've downloaded it to the project on NetBeans. Cant I do the same to build my Ionic APK? I tried setting the JAVA_HOME inside .bashrc with this line

export JAVA_HOME=$HOME/Apps/jdk1.8.0_144

But it didnt work, I dont get any return from java -version in terminal.

Body:
Not only the JAVA_HOME environment variable should be set, but also JDK binaries should be on your PATH:

JAVA_HOME=$HOME/Apps/jdk1.8.0_144
export JAVA_HOME
export PATH="${JAVA_HOME}/bin:${PATH}"


问:
How to implement this foldl0 function without helper method?
I have following code:

```<code>function foldr0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return func(list[0], foldr0(list.slice(1), func));
  }
}

function foldl0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return ?
  }
}
</code>```

I know it is easy to implement a recursive foldl0 with an iterative logic by defining a helper method iter(list, func, part_result) and store the result as an argument. But how to implement foldl0 without helper method just like foldr0's implementation?

NOTICE: I wrote this problem with Javascript for convenience. Please solve it with car and cdr, thanks.

答:
We're going to look at the computational process evolved by each generic foldr and foldl. Seeing the implementations below, compare how f gets the result of foldr, but foldl gets the result of f

const foldr = ( f , acc , xs ) =>
  isEmpty (xs)
    ? acc
    : f ( foldr ( f , acc , tail ( xs ) )
        , head ( xs )
        )

const foldl = ( f , acc , xs ) =>
  isEmpty (xs)
    ? acc
    : foldl ( f
            , f ( acc , head ( xs ) )
            , tail ( xs )
            )
```

<p>Let's look closer at the process now – in <code>foldr</code>, you can see how <code>acc</code> (<code>0</code>) gets passed all the way down the call stack before any <code>f</code> is ever computed</p>

<pre class="lang-js prettyprint-override"><code>// example call
foldr ( f , 0 , [ 1 , 2 , 3 ] )

// notice we can't run f yet, still waiting for foldr
f ( foldr ( f , 0 , [ 2 , 3 ] )
  , 1
  )

// now 2 f calls pending; still waiting on foldr
f ( f ( foldr ( f , 0 , [ 3 ] )
      , 2
      )
  , 1
  )

// now 3 f calls pending, still waiting on foldr
f ( f ( f ( foldr ( f , 0 , [] )
          , 3
          )
      , 2
      )
  , 1
  )

// now we can compute the inner most f, working our way out
f ( f ( f ( 0
          , 3
          )
      , 2
      )
  , 1
  )

// in other words, foldr traverses your input and creates a stack of f calls
f ( f ( f ( 0 , 3 ) , 2 ) , 1 )
</code>```

The call stack for foldl is much different – notice how the acc is used immediately

// pretend f = ( x , y ) => x + y
foldl ( f
      , 0
      , [ 1 , 2 , 3 ]
      )

// this time f is called first, and the result becomes the next acc
foldl ( f
      , f ( 0 , 1 ) // next acc = 1
      , [ 2 , 3 ]
      )

// f is always computed before recurring
foldl ( f
      , f ( 1 , 2 ) // next acc = 3
      , [ 3 ]
      )

// notice how foldl stays nice and flat (foldl uses a tail call, foldr doesn't)
foldl ( f
      , f ( 3 , 3 ) // next acc = 6
      , []
      )

// when the input is empty, the acc is just returned
foldl ( f
      , 6
      , [] // empty input
      )

// result
6
```

<p>So why are we looking at these generics? Well the point is to show you what the computational process looks like. It's in the visualization of the process that you can see how data moves through the program.</p>

<p>In <code>foldr</code> you can see how <code>acc</code> is immediately passed all the way down the call stack – so you could  effectively drop the <code>acc</code> parameter and replace <code>acc</code> with <code>0</code> and there is your <code>foldr0</code> –  which is precisely what you have</p>

<pre class="lang-js prettyprint-override"><code>const foldr0 = ( f , xs ) =>
  isEmpty (xs)
    ? 0
    : f ( foldr0 ( f , tail ( xs ) )
        , head ( xs )
        )
</code>```

However, that's not the case with foldl – a new acc is computed in each step and it's needed to compute the next step, so we can't just drop the parameter and replace with 0 like we did with foldr. Instead, the easiest (and smartest) implementation becomes

const foldl0 = ( f , xs ) =>
  foldl ( f , 0 , xs )

const foldr0 = ( f , xs ) =>
  foldr ( f , 0 , xs )
```

<p>This doesn't meet your criteria of "no helper method", but that's not really a real thing. The exercise is likely meant to show you why it's challenging to implement a left fold without an auxiliary helper; as a means of helping you visualize process.</p>

<hr>

<p>tl:dr;</p>

<p>JavaScript is full of all sorts of tricks though, so you can cheat to pass your class and prevent yourself from learning anything!</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const isEmpty = xs =>
  xs.length === 0

const head = ( [ x , ... xs ] ) =>
  x

const tail = ( [ x , ... xs ] ) =>
  xs

const foldl0 = ( f , xs , acc = 0 ) =>
  isEmpty (xs)
    ? acc
    : foldl0 ( f
             , tail ( xs )
             , f ( acc , head ( xs ) )
             )

const myFunc = ( x , y ) =>
  `( ${x} + ${y} )`

console.log ( foldl0 ( myFunc , [ 1 , 2 , 3 ] ) )
// ( ( ( 0 + 1 ) + 2 ) + 3 )</code>```

Body:
I have following code:

function foldr0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return func(list[0], foldr0(list.slice(1), func));
  }
}

function foldl0(list, func) {
  if (list.length == 0) {
    return 0;
  } else {
    return ?
  }
}

I know it is easy to implement a recursive foldl0 with an iterative logic by defining a helper method iter(list, func, part_result) and store the result as an argument. But how to implement foldl0 without helper method just like foldr0's implementation?

NOTICE: I wrote this problem with Javascript for convenience. Please solve it with car and cdr, thanks.

Body:
We're going to look at the computational process evolved by each generic foldr and foldl. Seeing the implementations below, compare how f gets the result of foldr, but foldl gets the result of f

const foldr = ( f , acc , xs ) =>
  isEmpty (xs)
    ? acc
    : f ( foldr ( f , acc , tail ( xs ) )
        , head ( xs )
        )

const foldl = ( f , acc , xs ) =>
  isEmpty (xs)
    ? acc
    : foldl ( f
            , f ( acc , head ( xs ) )
            , tail ( xs )
            )

Let's look closer at the process now – in foldr, you can see how acc (0) gets passed all the way down the call stack before any f is ever computed

// example call
foldr ( f , 0 , [ 1 , 2 , 3 ] )

// notice we can't run f yet, still waiting for foldr
f ( foldr ( f , 0 , [ 2 , 3 ] )
  , 1
  )

// now 2 f calls pending; still waiting on foldr
f ( f ( foldr ( f , 0 , [ 3 ] )
      , 2
      )
  , 1
  )

// now 3 f calls pending, still waiting on foldr
f ( f ( f ( foldr ( f , 0 , [] )
          , 3
          )
      , 2
      )
  , 1
  )

// now we can compute the inner most f, working our way out
f ( f ( f ( 0
          , 3
          )
      , 2
      )
  , 1
  )

// in other words, foldr traverses your input and creates a stack of f calls
f ( f ( f ( 0 , 3 ) , 2 ) , 1 )

The call stack for foldl is much different – notice how the acc is used immediately

// pretend f = ( x , y ) => x + y
foldl ( f
      , 0
      , [ 1 , 2 , 3 ]
      )

// this time f is called first, and the result becomes the next acc
foldl ( f
      , f ( 0 , 1 ) // next acc = 1
      , [ 2 , 3 ]
      )

// f is always computed before recurring
foldl ( f
      , f ( 1 , 2 ) // next acc = 3
      , [ 3 ]
      )

// notice how foldl stays nice and flat (foldl uses a tail call, foldr doesn't)
foldl ( f
      , f ( 3 , 3 ) // next acc = 6
      , []
      )

// when the input is empty, the acc is just returned
foldl ( f
      , 6
      , [] // empty input
      )

// result
6

So why are we looking at these generics? Well the point is to show you what the computational process looks like. It's in the visualization of the process that you can see how data moves through the program.

In foldr you can see how acc is immediately passed all the way down the call stack – so you could  effectively drop the acc parameter and replace acc with 0 and there is your foldr0 –  which is precisely what you have

const foldr0 = ( f , xs ) =>
  isEmpty (xs)
    ? 0
    : f ( foldr0 ( f , tail ( xs ) )
        , head ( xs )
        )

However, that's not the case with foldl – a new acc is computed in each step and it's needed to compute the next step, so we can't just drop the parameter and replace with 0 like we did with foldr. Instead, the easiest (and smartest) implementation becomes

const foldl0 = ( f , xs ) =>
  foldl ( f , 0 , xs )

const foldr0 = ( f , xs ) =>
  foldr ( f , 0 , xs )

This doesn't meet your criteria of "no helper method", but that's not really a real thing. The exercise is likely meant to show you why it's challenging to implement a left fold without an auxiliary helper; as a means of helping you visualize process.

tl:dr;

JavaScript is full of all sorts of tricks though, so you can cheat to pass your class and prevent yourself from learning anything!

const isEmpty = xs =>
  xs.length === 0

const head = ( [ x , ... xs ] ) =>
  x

const tail = ( [ x , ... xs ] ) =>
  xs

const foldl0 = ( f , xs , acc = 0 ) =>
  isEmpty (xs)
    ? acc
    : foldl0 ( f
             , tail ( xs )
             , f ( acc , head ( xs ) )
             )

const myFunc = ( x , y ) =>
  `( ${x} + ${y} )`

console.log ( foldl0 ( myFunc , [ 1 , 2 , 3 ] ) )
// ( ( ( 0 + 1 ) + 2 ) + 3 )


问:
REg Exp allowing ASCII Printable characters, Special characters allowed, Spaces not allowed
I am looking for a Regular Expression which should have Min 1-Max 50 characters accepted and Accepts ASCII Printable characters, Special characters allowed, Spaces not allowed.

Right now I'm having

```<code>^[ -~][^\\s]{1,50}$
</code>```

but when I enter one single character it throws an error. Could anyone please check with this. Thanks.

答:
Use a regex that consists of a single character class that matches ASCII symbols from an exclamation mark (since it comes right after the space. its hex code is 21) till a tilde, add the quantifier and wrap with anchors.

```<code>^[!-~]{1,50}$
</code>```

The ^[ -~][^\\s]{1,50}$ regex matches the start of string, then any printable ASCII char and then any nonwhitespace char at the end of the string, thus, as you see, it cannot match a single char string.

The ^[!-~]{1,50}$ matches a string that only consists of 1 to 50 ASCII printable chars other than space.

Body:
I am looking for a Regular Expression which should have Min 1-Max 50 characters accepted and Accepts ASCII Printable characters, Special characters allowed, Spaces not allowed.

Right now I'm having

^[ -~][^\\s]{1,50}$

but when I enter one single character it throws an error. Could anyone please check with this. Thanks.

Body:
Use a regex that consists of a single character class that matches ASCII symbols from an exclamation mark (since it comes right after the space. its hex code is 21) till a tilde, add the quantifier and wrap with anchors.

^[!-~]{1,50}$

The ^[ -~][^\\s]{1,50}$ regex matches the start of string, then any printable ASCII char and then any nonwhitespace char at the end of the string, thus, as you see, it cannot match a single char string.

The ^[!-~]{1,50}$ matches a string that only consists of 1 to 50 ASCII printable chars other than space.


问:
SSH agent forwarding to Docker Alpine container from Mac OS
Okay so for several projects I need to access my private repositories, so I'd like to forward the host's SSH Agent to the container to allow retrieving from these private repositories. Eventually I would like to implement this in docker-compose.

I've found a lot of answers and solutions pointing to something like this:

```<code>docker run --rm -t -i \
-v $SSH_AUTH_SOCK:/ssh-agent \
-e SSH_AUTH_SOCK=/ssh-agent \
alpine:3.6 sh
</code>```

But when I run ssh-add -l inside there (after making sure openssh is installed)

I get the following error:

Error connecting to agent: Connection refused

Also tried this within my docker compose setup but it doesn't seem to work like it should.
Due to most posts and solutions being several years old I hope someone can help me with accurate up-to-date info.

答:
You can mount files, but not sockets - sharing sockets between MacOS through the hypervisor into docker containers is something that isn't supported yet. Various bug reports and acknowledgements exist, and some day it should work.

So in the meantime, you need to have something that forwards network traffic between the container and MacOS. One of the solutions that people point out is docker-ssh-agent-forward.

A different solution would be to run ssh-agent in a container and to access that from MacOS and the other containers - it's probably a bit more invasive but works. A solution is docker-ssh-agent.

Body:
Okay so for several projects I need to access my private repositories, so I'd like to forward the host's SSH Agent to the container to allow retrieving from these private repositories. Eventually I would like to implement this in docker-compose.

I've found a lot of answers and solutions pointing to something like this:

docker run --rm -t -i \
-v $SSH_AUTH_SOCK:/ssh-agent \
-e SSH_AUTH_SOCK=/ssh-agent \
alpine:3.6 sh

But when I run ssh-add -l inside there (after making sure openssh is installed)

I get the following error:

Error connecting to agent: Connection refused

Also tried this within my docker compose setup but it doesn't seem to work like it should.
Due to most posts and solutions being several years old I hope someone can help me with accurate up-to-date info.


问:
how much data to hold in memory when looping through large dataset
I am trying to create a trading simulator to test strategies over long periods of time.

I am using 1 minute data points. So if I were to run a simulation for say 10 years that would be approx 3,740,000 prices (Price class shown below). A simulation could be much longer than 10 years but using this an example.

```<code>     class Price
     {
          DateTime DatePrice
          double Open
          double High
          double Low
          double Close
     }
</code>```

My simulator works however I can't help feeling the way I'm doing it isn't very optimal.

So currently what I do is to grab a years worth of prices from my SQL database so approx 374,400 prices. I do this because I don't want to use too much memory (this might be misguided have no idea).

Now when looping through time the code will also make use of the previous lets say 10 prices. So at 2.30am the code will look back the prices from 2.20am, all the prices previous to this are now redundant. So it seems somewhat wasteful to me if I hold 374,400 prices in memory.

```<code>            time       Close
            00:00      102
            00:01      99
            00:02      100
            ...
            02:20      84
            02:21      88
</code>```

So I have a loop that will loop through from my start date to my end date, checking at each step if I need to download additional prices from the database.

```<code>   List<Price> PriceList = Database.GetPrices(first years worth or prices)

   for(DateTime dtNow = dtStart; dtNow < dtEnd; dtNow = dtNow.AddMinutes(1))
   {
         // run some calculations which doesn't take long

         // then check if PriceList[i] == PriceList.Count - 1
         // if so get more prices from the database and obviously reset i to zero but baring in mind I need to keep the previous 10 prices
   }
</code>```

What is the best solution for this kind of problem? Should I be getting prices from the database on another thread or something?

答:
If I were you, I would keep the problem of caching (which seems to be your problem), separate from functionality.

I don't know how you currently fetch your data from the DB. I am guessing you are using some logic similar to

```<code>DataAdapter.Fill(dataset);
List<Price> PriceList = dataset.Tables[0].SomeLinqQuery();
</code>```

Instead of fetching all the prices at teh same time, you can use something like below to fetch them incrementally and convert the fetched row into a Price object

```<code>IDataReader rdr = IDbCommand.ExecuteReader();
while(rdr.Read())
{
}
</code>```

Now to make transparent access to Prices, you might want to roll in some class which can provide caching

```<code>class FixedSizeCircularBuffer<T> {
    void Add(T item) { } // make sure to dequeue automatically to keep buffer size fixed
    public T GetPrevious(int relativePosition) { } // provide indexer to access relative to the current element
}

class CachedPrices {
    FixedSizeCircularBuffer<Price> Cache;

    public CachedPrices() {
        // connect to the DB and do ExecuteReader
        // set the cache object to a good size
    }

    public Price this[int i] {
        get {
            if (i is in Cache)
                return Cache[i];
            else
                reader.Read();
                //store the newly fetched item to cache
        }
    }

}
</code>```

Once you have such infrastructure, then you can pretty much use it to restrict how much pricing information is loaded and keep your functionality separate from the Caching mechanism. This provides you the flexibility to control how much memory you have to spare for pre-fetching prices and the amount of data you can process

Needless to say, this is just a guideline - you will have to understand this and implement for yourself

Body:
I am trying to create a trading simulator to test strategies over long periods of time.

I am using 1 minute data points. So if I were to run a simulation for say 10 years that would be approx 3,740,000 prices (Price class shown below). A simulation could be much longer than 10 years but using this an example.

     class Price
     {
          DateTime DatePrice
          double Open
          double High
          double Low
          double Close
     }

My simulator works however I can't help feeling the way I'm doing it isn't very optimal.

So currently what I do is to grab a years worth of prices from my SQL database so approx 374,400 prices. I do this because I don't want to use too much memory (this might be misguided have no idea).

Now when looping through time the code will also make use of the previous lets say 10 prices. So at 2.30am the code will look back the prices from 2.20am, all the prices previous to this are now redundant. So it seems somewhat wasteful to me if I hold 374,400 prices in memory.

            time       Close
            00:00      102
            00:01      99
            00:02      100
            ...
            02:20      84
            02:21      88

So I have a loop that will loop through from my start date to my end date, checking at each step if I need to download additional prices from the database.

   List<Price> PriceList = Database.GetPrices(first years worth or prices)

   for(DateTime dtNow = dtStart; dtNow < dtEnd; dtNow = dtNow.AddMinutes(1))
   {
         // run some calculations which doesn't take long

         // then check if PriceList[i] == PriceList.Count - 1
         // if so get more prices from the database and obviously reset i to zero but baring in mind I need to keep the previous 10 prices
   }

What is the best solution for this kind of problem? Should I be getting prices from the database on another thread or something?

Body:
If I were you, I would keep the problem of caching (which seems to be your problem), separate from functionality.

I don't know how you currently fetch your data from the DB. I am guessing you are using some logic similar to

DataAdapter.Fill(dataset);
List<Price> PriceList = dataset.Tables[0].SomeLinqQuery();

Instead of fetching all the prices at teh same time, you can use something like below to fetch them incrementally and convert the fetched row into a Price object

IDataReader rdr = IDbCommand.ExecuteReader();
while(rdr.Read())
{
}

Now to make transparent access to Prices, you might want to roll in some class which can provide caching

class FixedSizeCircularBuffer<T> {
    void Add(T item) { } // make sure to dequeue automatically to keep buffer size fixed
    public T GetPrevious(int relativePosition) { } // provide indexer to access relative to the current element
}

class CachedPrices {
    FixedSizeCircularBuffer<Price> Cache;

    public CachedPrices() {
        // connect to the DB and do ExecuteReader
        // set the cache object to a good size
    }

    public Price this[int i] {
        get {
            if (i is in Cache)
                return Cache[i];
            else
                reader.Read();
                //store the newly fetched item to cache
        }
    }

}

Once you have such infrastructure, then you can pretty much use it to restrict how much pricing information is loaded and keep your functionality separate from the Caching mechanism. This provides you the flexibility to control how much memory you have to spare for pre-fetching prices and the amount of data you can process

Needless to say, this is just a guideline - you will have to understand this and implement for yourself


问:
Resolution issue when building the game
I am using the ViewportHandler script for Unity(https://github.com/dfsp-spirit/way2close/blob/master/Way2Close/Assets/Scripts/ViewportHandler.cs), to allow for my UI to appear the same in different resolutions. I am pretty sure that it was looking just fine and pretty much the same in all resolutions(with different quality graphics due to stretching, but that is fine).

I have opened up my project after a while and I am now noticing that while the game scene looks fine inside the editor, the UI elements change position for all resolutions when building the game.

I am attaching two screenshots to show the difference. The Editor one is the proper one where elements are aligned properly. The other one is when I am building the game and running it full screen.

The weird thing is that when building the game, every resolution displays the wrong way (as in picture 1). So the elements are actually resizing properly, but they are just in the wrong place for some reason and I really can't see why. Any ideas ?

(My Canvas is Screen Space - Overlay, Scale with Screen Size, Ref resolution is 2560/1440, Match width and height and ref pixels 100).

答:
You don't need 3rd party scripts to achieve a constant size on different resolutions. Use the Canvas Scaler component on your canvas and set it to 'Constant Physical Size'. Unity should handle all the rest.

If images/sprites change position, try to change the anchor point to fit your needs.

Title: Resolution issue when building the game


问:
Problem adding a custom field to Devise while testing with cucumber
I added a username field to my Rails app that's using Devise. I did all the necessary steps like adding the field to the views, adding it to the User model, migrating my database, etc. Now, when I run through the registration steps manually everything works fine. But as soon as I try to write a feature in Cucumber I get a huge page of errors.

Here's a very short list of the errors I get when running my cucumber feature

```<code>  Scenario: New user registration with valid info # features/user_access.feature:7
When I sign up as a new user with valid info  # features/step_definitions/user_access_steps.rb:5
  undefined method `username' for #<User:0x00000102f7dcf0> (ActionView::Template::Error)
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:364:in `method_missing'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/activerecord-3.0.3/lib/active_record/attribute_methods.rb:46:in `method_missing'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:1019:in `value_before_type_cast'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:1007:in `value_before_type_cast'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:915:in `block in to_input_field_tag'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:915:in `fetch'
</code>```

I have isolated the error to my Devise view. For some reason cucumber doesn't like the following lines

```<code><%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! % >

<p><%= f.label :username %><br />
<%= f.text_field :username %></p>
</code>```

For some reason cucumber wont play nice with the :username label and text_field. All I am doing in my cucumber steps is going to the registration page and trying to fill in username with a name.

Any idea what is causing this error and how to fix it?

答: Have you updated the test database? rake db:test:prepare

Body:
I added a username field to my Rails app that's using Devise. I did all the necessary steps like adding the field to the views, adding it to the User model, migrating my database, etc. Now, when I run through the registration steps manually everything works fine. But as soon as I try to write a feature in Cucumber I get a huge page of errors.

Here's a very short list of the errors I get when running my cucumber feature

  Scenario: New user registration with valid info # features/user_access.feature:7
When I sign up as a new user with valid info  # features/step_definitions/user_access_steps.rb:5
  undefined method `username' for #<User:0x00000102f7dcf0> (ActionView::Template::Error)
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/activemodel-3.0.3/lib/active_model/attribute_methods.rb:364:in `method_missing'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/activerecord-3.0.3/lib/active_record/attribute_methods.rb:46:in `method_missing'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:1019:in `value_before_type_cast'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:1007:in `value_before_type_cast'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:915:in `block in to_input_field_tag'
  /Users/Daniel/.rvm/gems/ruby-1.9.2-p136@Flow1/gems/actionpack-3.0.3/lib/action_view/helpers/form_helper.rb:915:in `fetch'

I have isolated the error to my Devise view. For some reason cucumber doesn't like the following lines

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! % >

<%= f.label :username %>

<%= f.text_field :username %>

For some reason cucumber wont play nice with the :username label and text_field. All I am doing in my cucumber steps is going to the registration page and trying to fill in username with a name.

Any idea what is causing this error and how to fix it?


问:
Does .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) trigger a job to run IMMEDIATELY there is wifi
Does .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) actually TRIGGER the job to run immediately when the wifi comes back or will the job just run as part of another scheduled batch of jobs IF wifi happens to be available.

The only reason I ask is that since i have been experimenting it seems to have done both things. With Nougat for example it seems to actually trigger the job to run immediately when wifi comes back, whereas with with Lollipop (I think) it seemed like it just waited for another batch of jobs to run.

Kind of an important detail because if it doesn't trigger a job to run consistently on all verisons then I need a broadcast receiver to run my uploads when WIFI comes back.

答:
Not necessarily. With JobScheduler, you are giving control over to Android to decide the best time to run something. However, the JobSchedulerService.java code has an explanation in the comments of the maybeQueueReadyJobsForExecutionLockedH method:

```<code>/**
 * The state of at least one job has changed. Here is where we could enforce various
 * policies on when we want to execute jobs.
 * Right now the policy is such:
 * If >1 of the ready jobs is idle mode we send all of them off
 * if more than 2 network connectivity jobs are ready we send them all off.
 * If more than 4 jobs total are ready we send them all off.
 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
 */
</code>```

This tells me that if I have two jobs waiting for the network, then they will run when the network comes on.  I tested that and found it to be true.  This was helpful, but I didn't necessarily want to wait for two jobs to queue and it sounds like you don't either.

I finally found that I can get more control over when it runs by also calling SetOverrideDeadline. By setting the deadline, it will run the job even if the network criteria is not met just that initial time.  Obviously, your code would have to be smart enough to handle running without a connection, but then after that initial try, it then waits until ALL the criteria are all met to try again.  The reason for that is not in the comment above (though it should be), but it is found in the actual code of that method.  It turns out that if there are any jobs that had a previous failure, the job scheduler will run.  Here is the relevant snippet from that same maybeQueueReadyJobsForExecutionLockedH method:

```<code>for (int i=0; i<jobs.size(); i++) {
    JobStatus job = jobs.valueAt(i);
    if (isReadyToBeExecutedLocked(job)) {
        if (job.getNumFailures() > 0) {
            backoffCount++;
        }
...
</code>```

Above notice the backoffCount being incremented, so that counts the total number of jobs that had previous failures.  Then a few lines later:

```<code>if (backoffCount > 0 ||
        idleCount >= MIN_IDLE_COUNT ||
        connectivityCount >= MIN_CONNECTIVITY_COUNT ||
        chargingCount >= MIN_CHARGING_COUNT ||
        runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
    ... run the jobs ...
    }
</code>```

I hope this saves you some time - I struggled for a while with this!

Body:
Not necessarily. With JobScheduler, you are giving control over to Android to decide the best time to run something. However, the JobSchedulerService.java code has an explanation in the comments of the maybeQueueReadyJobsForExecutionLockedH method:

/**
 * The state of at least one job has changed. Here is where we could enforce various
 * policies on when we want to execute jobs.
 * Right now the policy is such:
 * If >1 of the ready jobs is idle mode we send all of them off
 * if more than 2 network connectivity jobs are ready we send them all off.
 * If more than 4 jobs total are ready we send them all off.
 * TODO: It would be nice to consolidate these sort of high-level policies somewhere.
 */

This tells me that if I have two jobs waiting for the network, then they will run when the network comes on.  I tested that and found it to be true.  This was helpful, but I didn't necessarily want to wait for two jobs to queue and it sounds like you don't either.

I finally found that I can get more control over when it runs by also calling SetOverrideDeadline. By setting the deadline, it will run the job even if the network criteria is not met just that initial time.  Obviously, your code would have to be smart enough to handle running without a connection, but then after that initial try, it then waits until ALL the criteria are all met to try again.  The reason for that is not in the comment above (though it should be), but it is found in the actual code of that method.  It turns out that if there are any jobs that had a previous failure, the job scheduler will run.  Here is the relevant snippet from that same maybeQueueReadyJobsForExecutionLockedH method:

for (int i=0; i<jobs.size(); i++) {
    JobStatus job = jobs.valueAt(i);
    if (isReadyToBeExecutedLocked(job)) {
        if (job.getNumFailures() > 0) {
            backoffCount++;
        }
...

Above notice the backoffCount being incremented, so that counts the total number of jobs that had previous failures.  Then a few lines later:

if (backoffCount > 0 ||
        idleCount >= MIN_IDLE_COUNT ||
        connectivityCount >= MIN_CONNECTIVITY_COUNT ||
        chargingCount >= MIN_CHARGING_COUNT ||
        runnableJobs.size() >= MIN_READY_JOBS_COUNT) {
    ... run the jobs ...
    }

I hope this saves you some time - I struggled for a while with this!