问:
open generated pdf file in new tab instead of downloading..Web API
.Net 4.6.1 C#

I generate a pdf file at runtime and can download it successfully. I want to open the newly created pdf file in a new tab instead of downloading it. Here's my code (Web API 2.1 method):

```<code>  public HttpResponseMessage ToPDF(string cn)
    {

        var stream = new MemoryStream();
            stream = GeneratePDF();

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        return result;

    }
</code>```

I thought this would work, but it doesn't. I have target="_blank" on my anchor tag as well. How do i open my newly generated pdf file in a new tab instead of the browser wanting to download it to the user's hard drive? Thanks

答:
Aside from David Mkheyan's proposal of setting the proper MIME type, you also need to change the content disposition from attachment to inline.

```<code>result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(System.Net.Mime.DispositionTypeNames.Inline)
    {
        FileName = "file.pdf"
    };
</code>```

According to https://www.iana.org/assignments/cont-disp/cont-disp.xhtml attachment means "user controlled display" and inline is "displayed automatically".

Body:
.Net 4.6.1 C#

I generate a pdf file at runtime and can download it successfully. I want to open the newly created pdf file in a new tab instead of downloading it. Here's my code (Web API 2.1 method):

  public HttpResponseMessage ToPDF(string cn)
    {

        var stream = new MemoryStream();
            stream = GeneratePDF();

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.pdf"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

        return result;

    }

I thought this would work, but it doesn't. I have target="_blank" on my anchor tag as well. How do i open my newly generated pdf file in a new tab instead of the browser wanting to download it to the user's hard drive? Thanks

Body:
Aside from David Mkheyan's proposal of setting the proper MIME type, you also need to change the content disposition from attachment to inline.

result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(System.Net.Mime.DispositionTypeNames.Inline)
    {
        FileName = "file.pdf"
    };

According to https://www.iana.org/assignments/cont-disp/cont-disp.xhtml attachment means "user controlled display" and inline is "displayed automatically".


来源: stackexchange

问:
Destructive Stack Iteration
This is my Stack implementation.

```<code>class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return self

    def __next__(self):
        if self.head:
            curr = self.head
        else:
            raise StopIteration()
        self.head = self.head.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

if __name__ == '__main__':
    stack = Stack()
    stack.push(12)
    stack.push(13)
    stack.push(9)
    for item in stack:
        print(item)
    print(stack.peek())
</code>```

The problem with this is the iteration. The iteration is destructive and thus the call to peek at the end of the iteration throws an error.

return self.head.val
AttributeError: 'NoneType' object has no attribute 'val'
How do I make the iteration non-desctructive?

答:
A simple way to do this to give your Stack an alternative head that it can use for iterating. I've also added a __len__ method tha returns the Stack's size.

```<code>class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def __len__(self):
        return self.size

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        self.top = self.head
        return self

    def __next__(self):
        if self.top:
            curr = self.top
        else:
            raise StopIteration()
        self.top = self.top.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

if __name__ == '__main__':
    stack = Stack()
    stack.push(12)
    stack.push(13)
    stack.push(9)
    print('Size', len(stack))
    for item in stack:
        print(item)
    print(stack.peek())
    stack.push(42)
    print('Size', len(stack))
    for item in stack:
        print(item)
</code>```

output

```<code>Size 3
9
13
12
9
Size 4
42
9
13
12
</code>```

It's probably a Good Idea to add self.top = None to __init__, although it's not strictly necessary. And you may wish to mark it as a private name with a leading underscore: self._top.

As timgeb implies in the comments, this approach is a little fragile, since we can only perform one iteration at a time on the stack, since we only have a single self.top.

BTW, you can optimize that push method slightly:

```<code>def push(self, item):
    node = Node(item)
    if self.head:
        node.next = self.head
    self.head = node
    self.size += 1
</code>```

ContentLicense: CC BY-SA 3.0

Title: Destructive Stack Iteration

Body:
This is my Stack implementation.

class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        return self

    def __next__(self):
        if self.head:
            curr = self.head
        else:
            raise StopIteration()
        self.head = self.head.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

if __name__ == '__main__':
    stack = Stack()
    stack.push(12)
    stack.push(13)
    stack.push(9)
    for item in stack:
        print(item)
    print(stack.peek())

The problem with this is the iteration. The iteration is destructive and thus the call to peek at the end of the iteration throws an error.

return self.head.val
AttributeError: 'NoneType' object has no attribute 'val'
How do I make the iteration non-desctructive?

Body:
A simple way to do this to give your Stack an alternative head that it can use for iterating. I've also added a __len__ method tha returns the Stack's size.

class Stack:
    def __init__(self):
        self.head = None
        self.size = 0

    def __len__(self):
        return self.size

    def push(self, item):
        node = Node(item)
        if not self.head:
            self.head = node
        else:
            node.next = self.head
            self.head = node
        self.size += 1

    def pop(self):
        if self.size == 0:
            raise ValueError('Popping off an empty stack!')
        item = self.head.val
        self.head = self.head.next
        return item

    def peek(self):
        if self.size == 0:
            raise ValueError('Peeking into an empty stack!')
        return self.head.val

    def __iter__(self):
        self.top = self.head
        return self

    def __next__(self):
        if self.top:
            curr = self.top
        else:
            raise StopIteration()
        self.top = self.top.next
        return curr.val

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

if __name__ == '__main__':
    stack = Stack()
    stack.push(12)
    stack.push(13)
    stack.push(9)
    print('Size', len(stack))
    for item in stack:
        print(item)
    print(stack.peek())
    stack.push(42)
    print('Size', len(stack))
    for item in stack:
        print(item)

output

Size 3
9
13
12
9
Size 4
42
9
13
12

It's probably a Good Idea to add self.top = None to __init__, although it's not strictly necessary. And you may wish to mark it as a private name with a leading underscore: self._top.

As timgeb implies in the comments, this approach is a little fragile, since we can only perform one iteration at a time on the stack, since we only have a single self.top.

BTW, you can optimize that push method slightly:

def push(self, item):
    node = Node(item)
    if self.head:
        node.next = self.head
    self.head = node
    self.size += 1


问:
Add last column in csv file
I have csv file with separator tab and I want modify each row with value. can I got the reference for this case? I already search in google but I can't get the good reference. what is the best practice? what kind of library java to use easily for this case? for example I have csv file contains:

```<code>value1 value2 value3
value4 value5 value6
value7 value8 value9
</code>```

and I want to modify become:

```<code>value1 value2 value3 new_value1
value4 value5 value6 new_value2
value7 value8 value9 new_value3
</code>```

and my csv file have around 10.000 rows. what kind of logic for effective to modify each row? thanks.

答:
I used this library and was quite satisfied.

One example tutorial of how to use it is here.

Read the csv per row, add your new column and write to a new csv. Good luck!

Title: Add last column in csv file

Body:
I have csv file with separator tab and I want modify each row with value. can I got the reference for this case? I already search in google but I can't get the good reference. what is the best practice? what kind of library java to use easily for this case? for example I have csv file contains:

value1 value2 value3
value4 value5 value6
value7 value8 value9

and I want to modify become:

value1 value2 value3 new_value1
value4 value5 value6 new_value2
value7 value8 value9 new_value3

and my csv file have around 10.000 rows. what kind of logic for effective to modify each row? thanks.


问:
TS-2304 Error - can not find name 'Iterable' in TypeScript while importing "jquery" in ".ts" file
I am working on TypeScript version 2.4 using Visual Studio Code as an editor. I installed jQuery with NPM using the following command:

```<code>npm install --save @types/jquery
</code>```

Then I downloaded the source code of jquery module from GitHub.

The code of registrationpage.ts file is as follows:

```<code>import * as $ from 'jquery';
class Registration_Page {
    txtuname: string;
    Registration() {
        $('#table').hide;
        this.txtuname = ( <HTMLTextAreaElement> (document.getElementById('txtusername'))).value;
    }
}
window.onload = () => {
    $('#table').show;
    var bttnLogin = document.getElementById('submit');
    var obj = new Registration_Page();
    bttnLogin.onclick = function () {
        obj.Registration();
    }
}
</code>```

The code for index.html is as follows:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="registrationpage.js"></script>

</head>
<body>
    <form id="form1">
    <div>
     <fieldset style="font-size: medium; color: #000000;">
        <legend style="background-color:#CCCCFF; font-size: larger;font-weight:bold">Registration Page in TypeScript</legend>
        <br />
        <b>UserName</b>
        <input id="txtusername" type="text" /><br />
        <br />

            <input id="submit" type="button" value="Submit" />

    </fieldset>
    </div>
    <div id="table">
        <table>
            <tr>
                <th>UserName</th>

            </tr>
        </table>
    </div>
    </form>
</body>
</html>
</code>```

tsconfig.json file :

```<code>{
    "compilerOptions": {
        "target": "es5",
        "noImplicitAny": true,
        "lib": [ "es2015", "dom" ]

    }

}
</code>```

When I compile the code on CMD , I get the following error:

ERROR TS2304 : cannot find the name Iterable

Please suggest an appropriate solution.

答:
Consider installing the node type definitions.

npm i --save-dev @types/node

If you are using Yarn instead of NPM:

yarn add -D @types/node

Body:
I am working on TypeScript version 2.4 using Visual Studio Code as an editor. I installed jQuery with NPM using the following command:

npm install --save @types/jquery

Then I downloaded the source code of jquery module from GitHub.

The code of registrationpage.ts file is as follows:

import * as $ from 'jquery';
class Registration_Page {
    txtuname: string;
    Registration() {
        $('#table').hide;
        this.txtuname = ( <HTMLTextAreaElement> (document.getElementById('txtusername'))).value;
    }
}
window.onload = () => {
    $('#table').show;
    var bttnLogin = document.getElementById('submit');
    var obj = new Registration_Page();
    bttnLogin.onclick = function () {
        obj.Registration();
    }
}

The code for index.html is as follows:

<!DOCTYPE html>

    <title></title>

    <form id="form1">

     <fieldset style="font-size: medium; color: #000000;">
        <legend style="background-color:#CCCCFF; font-size: larger;font-weight:bold">Registration Page in TypeScript</legend>

        UserName
        <input id="txtusername" type="text" />

            <input id="submit" type="button" value="Submit" />

    </fieldset>

                UserName

    </form>

tsconfig.json file :

{
    "compilerOptions": {
        "target": "es5",
        "noImplicitAny": true,
        "lib": [ "es2015", "dom" ]

    }

}

When I compile the code on CMD , I get the following error:

ERROR TS2304 : cannot find the name Iterable

Please suggest an appropriate solution.


问:
sql - Joining one table to two more tables
I am trying to join a table (employee table) to two other tables (employee earnings and employee deductions) to display the amount for the particular type of earning and deduction of employee. Now, when my query duplicates the deduction when the employee has a record for two different types of earning and only one record for a deduction type. Employee has a one-to-many relationship to both earning and deduction tables.

Here is my query:

```<code>SELECT EmployeeMaster.EmployeeNumber, FirstName, LastName, MiddleName, empEarnings.EarningCode, empEarnings.amt, empDeduc.DeductionId, empDeduc.amt
from EmployeeMaster
LEFT OUTER JOIN
(
    SELECT EmployeeNumber, EarningCode, SUM(Amount) AS amt FROM EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
) AS empEarnings
ON EmployeeMaster.EmployeeNumber = empEarnings.EmployeeNumber
LEFT OUTER JOIN
(
    SELECT EmployeeID, DeductionID, SUM(Amount) AS amt FROM EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS empDeduc
ON EmployeeMaster.EmployeeNumber = empDeduc.EmployeeId
</code>```

This returns (sample data only)

```<code>00001   First Name  Last Name   EARN       1000000.0000000000000000 SSS 1000.0000000000000000
00001   First Name  Last Name   EARN2      1000.0000000000000000    SSS 1000.0000000000000000
00002   First Name2 Last Name2  EARN       10000.0000000000000000   SSS 100.0000000000000000
00002   First Name2 Last Name2  EARN2      10000.0000000000000000   SSS 100.0000000000000000
</code>```

The result is almost correct except, these employees only have one record of a deduction type. However, the result set duplicates the deduction table result which results to the sum of the total deduction being wrong (double of the supposed value) in my ssrs report.

How should I modify my query to fit these requirements, and also being able to generate an ssrs report in a format like:

```<code>Emp# First Name Last Name EarnType1 EarnType2 [...] DeducType1 DeducType2 [...]
#1    John        Doe       100000    100000        100        100
</code>```

答:
Use SQL Fiddle for the following http://sqlfiddle.com/#!6/71e8b/12:

I think this is a short-hand of what you want:

```<code>CREATE TABLE emp (
  empNum INT,
  fName VARCHAR(20),
  lName VARCHAR(20),
  mName varchar(20));

create table empEarnings(
  eCode INT,
  empNum INT,
  earnAmount INT);

create table empDeduc(
  empDedId INT,
  emDedAmt INT,
empNum INT);

 INSERT INTO emp (empNum, fName, lName, mName)
 VALUES (1, 'a', 'ab', 'abc');

 INSERT INTO empEarnings (eCode, earnAmount, empNum)
 VALUES (1, 100, 1);

 INSERT INTO empDeduc (empDedId, emDedAmt, empNum)
 VALUES (1, 2, 1);

 INSERT INTO empDeduc (empDedId, emDedAmt, empNum)
 VALUES (2, 3, 1);
</code>```

ANSWER:

```<code>;With getEarnSum AS(
SELECT ee.empNum, SUM(ee.earnAmount) AS 'sumAmount' FROM empEarnings ee
LEFT OUTER JOIN empDeduc ed ON ee.empNum = ed.empNum
GROUP BY ee.empNum)
SELECT emp.fname, emp.lname, emp.mname, cte.sumAmount FROM emp
LEFT OUTER JOIN
getEarnSum cte ON emp.empNum = cte.empNum
</code>```

Body:
I am trying to join a table (employee table) to two other tables (employee earnings and employee deductions) to display the amount for the particular type of earning and deduction of employee. Now, when my query duplicates the deduction when the employee has a record for two different types of earning and only one record for a deduction type. Employee has a one-to-many relationship to both earning and deduction tables.

Here is my query:

SELECT EmployeeMaster.EmployeeNumber, FirstName, LastName, MiddleName, empEarnings.EarningCode, empEarnings.amt, empDeduc.DeductionId, empDeduc.amt
from EmployeeMaster
LEFT OUTER JOIN
(
    SELECT EmployeeNumber, EarningCode, SUM(Amount) AS amt FROM EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
) AS empEarnings
ON EmployeeMaster.EmployeeNumber = empEarnings.EmployeeNumber
LEFT OUTER JOIN
(
    SELECT EmployeeID, DeductionID, SUM(Amount) AS amt FROM EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS empDeduc
ON EmployeeMaster.EmployeeNumber = empDeduc.EmployeeId

This returns (sample data only)

00001   First Name  Last Name   EARN       1000000.0000000000000000 SSS 1000.0000000000000000
00001   First Name  Last Name   EARN2      1000.0000000000000000    SSS 1000.0000000000000000
00002   First Name2 Last Name2  EARN       10000.0000000000000000   SSS 100.0000000000000000
00002   First Name2 Last Name2  EARN2      10000.0000000000000000   SSS 100.0000000000000000

The result is almost correct except, these employees only have one record of a deduction type. However, the result set duplicates the deduction table result which results to the sum of the total deduction being wrong (double of the supposed value) in my ssrs report.

How should I modify my query to fit these requirements, and also being able to generate an ssrs report in a format like:

Emp# First Name Last Name EarnType1 EarnType2 [...] DeducType1 DeducType2 [...]
#1    John        Doe       100000    100000        100        100

Body:
Use SQL Fiddle for the following http://sqlfiddle.com/#!6/71e8b/12:

I think this is a short-hand of what you want:

CREATE TABLE emp (
  empNum INT,
  fName VARCHAR(20),
  lName VARCHAR(20),
  mName varchar(20));

create table empEarnings(
  eCode INT,
  empNum INT,
  earnAmount INT);

create table empDeduc(
  empDedId INT,
  emDedAmt INT,
empNum INT);

 INSERT INTO emp (empNum, fName, lName, mName)
 VALUES (1, 'a', 'ab', 'abc');

 INSERT INTO empEarnings (eCode, earnAmount, empNum)
 VALUES (1, 100, 1);

 INSERT INTO empDeduc (empDedId, emDedAmt, empNum)
 VALUES (1, 2, 1);

 INSERT INTO empDeduc (empDedId, emDedAmt, empNum)
 VALUES (2, 3, 1);

ANSWER:

;With getEarnSum AS(
SELECT ee.empNum, SUM(ee.earnAmount) AS 'sumAmount' FROM empEarnings ee
LEFT OUTER JOIN empDeduc ed ON ee.empNum = ed.empNum
GROUP BY ee.empNum)
SELECT emp.fname, emp.lname, emp.mname, cte.sumAmount FROM emp
LEFT OUTER JOIN
getEarnSum cte ON emp.empNum = cte.empNum


问:
Month name of date field in Access database from external application (C#)
I want to populate a drop down list at runtime in C#. I have a Date/Time field (e.g., 01/05/2000) in an Access 2003 database. I want to have the month name (i.e. January, February, ...) in the drop down list at runtime.

```<code>SELECT DISTINCT MonthName(Month(DATE_OF_BOOKING)) AS MNTH
    FROM TRAVEL_DETAILS WHERE YEAR(DATE_OF_BOOKING)='2008'
</code>```

The above query works fine while I'm running it from Access directly,
but when I'm trying to run it from an OledbCommand object in C# it says

Undefined function 'MonthName' in expression.

答:
MonthName is one of the many Access functions that was not supported by the ODBC and OLEDB drivers for the original "Jet" database engine, i.e.

Driver={Microsoft Access Driver (*.mdb)} for ODBC, or

Provider=Microsoft.Jet.OLEDB.4.0 for OLEDB

but it is supported by the drivers for the newer "ACE" database engine

Driver={Microsoft Access Driver (*.mdb, *.accdb)} for ODBC, or

Provider=Microsoft.ACE.OLEDB.12.0 for OLEDB

Microsoft Access Database Engine 2016 Redistributable

Microsoft Access Database Engine 2010 Redistributable

Body:
I want to populate a drop down list at runtime in C#. I have a Date/Time field (e.g., 01/05/2000) in an Access 2003 database. I want to have the month name (i.e. January, February, ...) in the drop down list at runtime.

SELECT DISTINCT MonthName(Month(DATE_OF_BOOKING)) AS MNTH
    FROM TRAVEL_DETAILS WHERE YEAR(DATE_OF_BOOKING)='2008'

The above query works fine while I'm running it from Access directly,
but when I'm trying to run it from an OledbCommand object in C# it says

Undefined function 'MonthName' in expression.


问:
passing variable to partial loop
Could it be possible to pass the values in partial loop. for code

EDIT:: in my file where partial is called, i've another array to pass. and i want S/N for array

```<code> <?php echo $this->partialLoop("partials/destination.phtml", $this->deslist);?>
</code>```

and i my partial/destination.phtml file i have

```<code><td><?php echo ++$count; ?></td>
</code>```

i am getting warning message

```<code>    Notice: Undefined variable: count in
    /var/www/globaltours.com/application/modules/admin/views/scripts/partials/destination.phtml
    on line 2 1
</code>```

i wanted to display the count(order) of the items

答:
View variables are in $this; use $this->count to access the count variable:

```<code><td><?php echo ++$this->$count; ?></td>
</code>```

Assuming you have passed the variable to the view like this:

```<code>$view->partialLoop('view-script.phtml', array(
    // loop 1
    array(
        'count' => 0,
        'other_variable' => 'value',
        'other_variable' => 'value',
    ),
    // loop n
    array(
        'count' => 0,
        'other_variable' => 'value',
        'other_variable' => 'value',
    ),
));
</code>```

ContentLicense: CC BY-SA 2.5

Title: passing variable to partial loop

Body:
Could it be possible to pass the values in partial loop. for code

EDIT:: in my file where partial is called, i've another array to pass. and i want S/N for array

 <?php echo $this->partialLoop("partials/destination.phtml", $this->deslist);?>

and i my partial/destination.phtml file i have

<?php echo ++$count; ?>

i am getting warning message

    Notice: Undefined variable: count in
    /var/www/globaltours.com/application/modules/admin/views/scripts/partials/destination.phtml
    on line 2 1

i wanted to display the count(order) of the items

Body:
View variables are in $this; use $this->count to access the count variable:

<td><?php echo ++$this->$count; ?></td>

Assuming you have passed the variable to the view like this:

$view->partialLoop('view-script.phtml', array(
    // loop 1
    array(
        'count' => 0,
        'other_variable' => 'value',
        'other_variable' => 'value',
    ),
    // loop n
    array(
        'count' => 0,
        'other_variable' => 'value',
        'other_variable' => 'value',
    ),
));


问:
Cannot debug serverless application in Visual Studio Code
I have tried to debug serverless application developed using serverless framework in VS code. I have followed this article.

But when I trying to debug the code I'm getting an error from VS code as below.

Cannot launch program 'g:\Projects\Serverless1\node_modules.bin\sls'; setting the 'outDir or outFiles' attribute might help.

sls command file already exists in the folder and following are the launch.json file settings

```<code>"version": "0.2.0",
"configurations": [

    {
        "type": "node",
        "request": "launch",
        "protocol": "inspector",
        "name": "run hello function",
        "program": "${workspaceRoot}\\node_modules\\.bin\\sls",
        "args": [
            "invoke",
            "local",
            "-f",
            "hello",
            "--data",
            "{}"
        ]

    }
]
</code>```

Please help me to fix this issue.

答:
I attempted to follow the same article, and experienced the same error.  Adding outFiles didn't help, although it did change my error message to:

```<code>Cannot launch program 'd:\<path>\node_modules\.bin\sls' because corresponding JavaScript cannot be found.
</code>```

I can't explain why VSCode has a problem with the executable in node_modules/.bin, but if I point at node_modules/serverless/bin instead, things work as expected:

```<code>"program": "${workspaceFolder}\\node_modules\\serverless\\bin\\serverless",
</code>```

Here is my full working configuration, where my test event JSON exists in sample-event.json in the project root:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug Lambda",
            "program": "${workspaceFolder}/node_modules/serverless/bin/serverless",
            "args": [
                "invoke",
                "local",
                "-f",
                "<function-name>",
                "--data",
                "{}" // You can use this argument to pass data to the function to help with the debug
            ]
        }
    ]
}
</code>```

Using Serverless ^1.26.1, Node 8.9.4 LTS, VSCode 1.20.1

Body:
I have tried to debug serverless application developed using serverless framework in VS code. I have followed this article.

But when I trying to debug the code I'm getting an error from VS code as below.

Cannot launch program 'g:\Projects\Serverless1\node_modules.bin\sls'; setting the 'outDir or outFiles' attribute might help.

sls command file already exists in the folder and following are the launch.json file settings

"version": "0.2.0",
"configurations": [

    {
        "type": "node",
        "request": "launch",
        "protocol": "inspector",
        "name": "run hello function",
        "program": "${workspaceRoot}\\node_modules\\.bin\\sls",
        "args": [
            "invoke",
            "local",
            "-f",
            "hello",
            "--data",
            "{}"
        ]

    }
]

Please help me to fix this issue.

Body:
I attempted to follow the same article, and experienced the same error.  Adding outFiles didn't help, although it did change my error message to:

Cannot launch program 'd:\<path>\node_modules\.bin\sls' because corresponding JavaScript cannot be found.

I can't explain why VSCode has a problem with the executable in node_modules/.bin, but if I point at node_modules/serverless/bin instead, things work as expected:

"program": "${workspaceFolder}\\node_modules\\serverless\\bin\\serverless",

Here is my full working configuration, where my test event JSON exists in sample-event.json in the project root:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug Lambda",
            "program": "${workspaceFolder}/node_modules/serverless/bin/serverless",
            "args": [
                "invoke",
                "local",
                "-f",
                "<function-name>",
                "--data",
                "{}" // You can use this argument to pass data to the function to help with the debug
            ]
        }
    ]
}

Using Serverless ^1.26.1, Node 8.9.4 LTS, VSCode 1.20.1


问:
copy a sub part of a string
I'm trying to copy a part of a string in a other string.
I know the 2 identifiers starting and ending the sub-string.

I'm trying to copy the IP from this string:

```<code>0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection
</code>```

The beginning of the string will be "Host: " or 192
The ending will be "\r\nC" or the 2nd occurrence of "\r\n"
So the desired output is:

```<code>192.168.1.200
</code>```

I tried using strcpy and memcpy but the IP has to be variable so I don't know how long it will be or what it will be, the minimum will be 11 and the maximum 15 chars.

I hope you can help me further.

答:
You will need a buffer of 16 bytes (max 3 bytes for each octet, total 12, plus three points is 15, plus zero-terminator).

Then, as you say, you need to precisely position your read:

```<code>host = strstr(string, "Host: ");
if (!host) {
    // Problem. Cannot continue, the string has not the format expected.
}
host += strlen("Host: ");
end  = strstr(host, "\r\n");
if (!end) {
    // Problem
}
// Sanity check: end - host must be less than 16. Someone could send you
// Host: 192.168.25.12.Hello.I.Am.Little.Bobby.Headers\r\n
if ((end - host) > 15) {
    // Big problem
}
// We now know where the address starts, and where it ends.
// Copy the string into address
strncpy(address, host, (end-host));
// Add zero terminator to make this a C string
address[end-host] = 0x0;
</code>```

Title: copy a sub part of a string

Body:
I'm trying to copy a part of a string in a other string.
I know the 2 identifiers starting and ending the sub-string.

I'm trying to copy the IP from this string:

0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection

The beginning of the string will be "Host: " or 192
The ending will be "\r\nC" or the 2nd occurrence of "\r\n"
So the desired output is:

192.168.1.200

I tried using strcpy and memcpy but the IP has to be variable so I don't know how long it will be or what it will be, the minimum will be 11 and the maximum 15 chars.

I hope you can help me further.

Body:
You will need a buffer of 16 bytes (max 3 bytes for each octet, total 12, plus three points is 15, plus zero-terminator).

Then, as you say, you need to precisely position your read:

host = strstr(string, "Host: ");
if (!host) {
    // Problem. Cannot continue, the string has not the format expected.
}
host += strlen("Host: ");
end  = strstr(host, "\r\n");
if (!end) {
    // Problem
}
// Sanity check: end - host must be less than 16. Someone could send you
// Host: 192.168.25.12.Hello.I.Am.Little.Bobby.Headers\r\n
if ((end - host) > 15) {
    // Big problem
}
// We now know where the address starts, and where it ends.
// Copy the string into address
strncpy(address, host, (end-host));
// Add zero terminator to make this a C string
address[end-host] = 0x0;


问:
Kotlin type missmatch. Expected Any received MyObject
I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

```<code>abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}
</code>```

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.

答:
You should generify the classes to accept Resource<T> i.e LiveData<Resource<T>>. Any is the covariance of any object passed, but I think you are not trying to achieve that.

Another friendly advice is that you don't need to add another abstraction on top of MediatorLiveData that solely does the same you have implemented.

Body:
I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.


问:
Why isn't my function being called in Java?
I'm new to java, and trying to learn on my own. I'm coming from a background in C++. Any help would be much appreciated. FibonacciSeq() isn't being called in my main and I'm unsure why. I made the method to accept the beginning integer (0) in a fibonacci sequence and from there recurse filling a vector with each value. The function should end when the vector has 9 elements. </p>

```<code>public class Fibonacci
{
    static Scanner input = new Scanner(System.in);
    static Vector<Integer> fibonacciVect = new Vector<Integer>(0);
    static int second;
    static int newFirst;
    static int fibIn = 0;

    public static void main(String[] args)
    {
    System.out.print("Here comes the Fibonacci, watch out!");

    fibonacciSeq(fibIn);

    System.out.print("Values in Fibonacci Vector:");
    for (int i = 0; i < fibonacciVect.size(); i++)
        {
        System.out.print(fibonacciVect.elementAt(i));
        }

    System.exit(0);
    }

    public static void fibonacciSeq(int first)
    {
        if (first == 0)
        {
            second = 1;
            fibonacciVect.addElement(0);
            fibonacciVect.addElement(1);
            newFirst = first + second;
            fibonacciSeq(newFirst);
        }

        if (fibonacciVect.size() == 9)
        {
            System.exit(0);
        }

        else
        {
            newFirst = first + second;
            fibonacciVect.addElement(newFirst);
            second = first;
            fibonacciSeq(newFirst);
        }

    }
}
</code>```

答:
As a beginner, you can instead replace you System.exit(0) by return

```<code>if (fibonacciVect.size() == 9)
    {
        return;
    }
</code>```

Also, please remove the other System.exit(0) too.
Your code should work now.

Body:
I'm new to java, and trying to learn on my own. I'm coming from a background in C++. Any help would be much appreciated. FibonacciSeq() isn't being called in my main and I'm unsure why. I made the method to accept the beginning integer (0) in a fibonacci sequence and from there recurse filling a vector with each value. The function should end when the vector has 9 elements.

public class Fibonacci
{
    static Scanner input = new Scanner(System.in);
    static Vector<Integer> fibonacciVect = new Vector<Integer>(0);
    static int second;
    static int newFirst;
    static int fibIn = 0;

    public static void main(String[] args)
    {
    System.out.print("Here comes the Fibonacci, watch out!");

    fibonacciSeq(fibIn);

    System.out.print("Values in Fibonacci Vector:");
    for (int i = 0; i < fibonacciVect.size(); i++)
        {
        System.out.print(fibonacciVect.elementAt(i));
        }

    System.exit(0);
    }

    public static void fibonacciSeq(int first)
    {
        if (first == 0)
        {
            second = 1;
            fibonacciVect.addElement(0);
            fibonacciVect.addElement(1);
            newFirst = first + second;
            fibonacciSeq(newFirst);
        }

        if (fibonacciVect.size() == 9)
        {
            System.exit(0);
        }

        else
        {
            newFirst = first + second;
            fibonacciVect.addElement(newFirst);
            second = first;
            fibonacciSeq(newFirst);
        }

    }
}

Body:
As a beginner, you can instead replace you System.exit(0) by return

if (fibonacciVect.size() == 9)
    {
        return;
    }

Also, please remove the other System.exit(0) too.
Your code should work now.


问:
How do I automatically see incoming commits in Intellij IDEA with git?
We just switched from svn to git. The svn plugin in idea has this very nice feature to automatically check the repository for incoming commits every x minutes.

In the idea git plugin, I didn't find this feature - is this possible somehow to check my origin for new commits automatically and list them in the log?

(Would it make sense to automatically fetch the origin every x minutes with some automated workflow somehow?)

答: To update your local machine with commits from the remote repo, you can run git fetch from the command line. Equivalently, in IntelliJ, you can push Ctrl-Shift-A and type "fetch" then press Enter. I do not know how to set up IntelliJ to fetch automatically.


问:
SQLite: Select using LIKE '%?%' with rawQuery
I am trying to use a select statement to query some data from the database's table .
when i type =? the query succeed , but when i use LIKE %?% instead i got this error in logcat:

```<code>FATAL EXCEPTION: main
Process: com.example.ahmed.bus_time_djerba4, PID: 4178
java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range.  The statement has 0 parameters.
</code>```

and this is my methode that call the database:

```<code>public String  QuerySQL(String DepartStation,String Destination){

    String result="";

    SQLiteDatabase db=this.getReadableDatabase();
    Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});

    if(c.getCount()==0) {result="Data not found";c.close();}
    else {
        while (c.moveToNext()) {
            //affichage des lignes
            int ligne = c.getInt(1);
            String Station = c.getString(2);
            String Dest = c.getString(3);
            String hours = c.getString(4);
            result += "\n" + ligne + "|" + Station + "-" + Dest + " " + hours;
        }
        c.close();
    }

    return result;
}
</code>```

what is the problem ? please

答:
The Problem is with the SQL query you have used.

you are giving ? A String which is not acceptable for prepare statements.
select distinct * from table_name where X like '%?%'; is not correct because ? will be a string with double quotation inside a quotation like '%"your_string"%'.

instead write:

```<code>select distinct * from table_name where X like ?;
</code>```

and for ? use "'%your_string%'". you can apply this to your array of string too.

Body:
I am trying to use a select statement to query some data from the database's table .
when i type =? the query succeed , but when i use LIKE %?% instead i got this error in logcat:

FATAL EXCEPTION: main
Process: com.example.ahmed.bus_time_djerba4, PID: 4178
java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range.  The statement has 0 parameters.

and this is my methode that call the database:

public String  QuerySQL(String DepartStation,String Destination){

    String result="";

    SQLiteDatabase db=this.getReadableDatabase();
    Cursor c=db.rawQuery("select distinct * from "+TABLE_Name+" where "+Col_3+" LIKE '%?%' and "+Col_4+" LIKE '%?%'", new String[]{DepartStation,Destination});

    if(c.getCount()==0) {result="Data not found";c.close();}
    else {
        while (c.moveToNext()) {
            //affichage des lignes
            int ligne = c.getInt(1);
            String Station = c.getString(2);
            String Dest = c.getString(3);
            String hours = c.getString(4);
            result += "\n" + ligne + "|" + Station + "-" + Dest + " " + hours;
        }
        c.close();
    }

    return result;
}

what is the problem ? please

Body:
The Problem is with the SQL query you have used.

you are giving ? A String which is not acceptable for prepare statements.
select distinct * from table_name where X like '%?%'; is not correct because ? will be a string with double quotation inside a quotation like '%"your_string"%'.

instead write:

select distinct * from table_name where X like ?;

and for ? use "'%your_string%'". you can apply this to your array of string too.


问:
How can i compare result of $_POST["fname"],.... with the records in a table?
The student enters his credentials to a from:

```<code><form action="index.php" id="courseform" method="post">
Enter Your First Name: <input type="text" name="fname"><br><br>
Enter Your Last Name: <input type="text" name="lname"><br><br>
Enter Your Student Number: <input type="text" name="student_nr"><br><br>
  <input type="submit">
</form>
</code>```

I have a table with the student records as under:

```<code>Database changed
mysql> explain student;

    +-----------+-------------+------+-----+---------+-------+
    | Field     | Type        | Null | Key | Default | Extra |
    +-----------+-------------+------+-----+---------+-------+
    | id        | char(6)     | NO   | PRI | NULL    |       |
    | firstname | varchar(30) | NO   |     | NULL    |       |
    | lastname  | varchar(30) | NO   |     | NULL    |       |
    | email     | varchar(50) | YES  |     | NULL    |       |
    +-----------+-------------+------+-----+---------+-------+

4 rows in set (0.05 sec)
</code>```

How can i verify the 3 values 'fname', 'lname' and 'id'(=student_nr) entered into the form are valid entire, i.e: exist in the table?

I tried the following, but did not work:

```<code><?php
include 'parameter_conn.php';
$link = mysqli_connect("$server","$user","$pass","$db");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }else {
      echo "Connection Successful" . "<br>";
  }

if (isset($_POST['fname'],$_POST['lname'],$_POST['student_nr'])) {
 $fname = $_POST["fname"];
 $lname = $_POST["lname"];
 $student_nr = $_POST["student_nr"];
}
$result_student = mysqli_query($link, "SELECT * FROM student");
$rows_student = mysqli_num_rows($result_student);

if($fname === $result_student['firstname'] && $lname === $result_student['lastname'] && $student_nr === $result_student['id']) {
    echo 'found';
} else {
    echo 'not found';
}
</code>```

答:
You can use a where clouse in your sql statement and simply check if you get a matching row. Please note below is very insecure and prone to SQL Injection (https://en.wikipedia.org/wiki/SQL_injection) but it illustrates the purpose. Consider using PDO</p>

```<code>$fname = $POST['fname'];
$email = $POST['email'];
// .. all other fields

$sql = "SELECT id, firstname, lastname, email FROM studentsTable WHERE firstname='".$fname."' AND lastname='".$lname."' AND email='".$email."'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // match found
} else {
  // no match
}
</code>```

Body:
The student enters his credentials to a from:

<form action="index.php" id="courseform" method="post">
Enter Your First Name: <input type="text" name="fname">

Enter Your Last Name: <input type="text" name="lname">

Enter Your Student Number: <input type="text" name="student_nr">

  <input type="submit">
</form>

I have a table with the student records as under:

Database changed
mysql> explain student;

    +-----------+-------------+------+-----+---------+-------+
    | Field     | Type        | Null | Key | Default | Extra |
    +-----------+-------------+------+-----+---------+-------+
    | id        | char(6)     | NO   | PRI | NULL    |       |
    | firstname | varchar(30) | NO   |     | NULL    |       |
    | lastname  | varchar(30) | NO   |     | NULL    |       |
    | email     | varchar(50) | YES  |     | NULL    |       |
    +-----------+-------------+------+-----+---------+-------+

4 rows in set (0.05 sec)

How can i verify the 3 values 'fname', 'lname' and 'id'(=student_nr) entered into the form are valid entire, i.e: exist in the table?

I tried the following, but did not work:

<?php
include 'parameter_conn.php';
$link = mysqli_connect("$server","$user","$pass","$db");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }else {
      echo "Connection Successful" . "
";
  }

if (isset($_POST['fname'],$_POST['lname'],$_POST['student_nr'])) {
 $fname = $_POST["fname"];
 $lname = $_POST["lname"];
 $student_nr = $_POST["student_nr"];
}
$result_student = mysqli_query($link, "SELECT * FROM student");
$rows_student = mysqli_num_rows($result_student);

if($fname === $result_student['firstname'] && $lname === $result_student['lastname'] && $student_nr === $result_student['id']) {
    echo 'found';
} else {
    echo 'not found';
}

Body:
You can use a where clouse in your sql statement and simply check if you get a matching row. Please note below is very insecure and prone to SQL Injection (https://en.wikipedia.org/wiki/SQL_injection) but it illustrates the purpose. Consider using PDO

$fname = $POST['fname'];
$email = $POST['email'];
// .. all other fields

$sql = "SELECT id, firstname, lastname, email FROM studentsTable WHERE firstname='".$fname."' AND lastname='".$lname."' AND email='".$email."'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // match found
} else {
  // no match
}


问:
How to add space between the Flex items in ReactJs?
This is the image of the code and the page.

The justifyconent attribute in the Containerr doesn't seem to work. Why are the 3 children elements stuck together with no space?

EDIT: I tried justifyContent too. (instead of JustifyContent as in the picture..)

答:
It looks like the <Paper/> components are simply filling the available space. I tried to make a SUPER simple CodePen to demonstrate this (https://codepen.io/venetian13/pen/xPvYaM). flex: 1 and flex 4 will fill available space in proportion to each other | 1 |    4    | 1 |. If you want them to be separate you have to give them a cumulative width > the containers total width.

Great Reference : https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
Html.TextBoxFor format and css class
The two lines of code below work fine, but I want to combine them.
What I mean is: I want to use the @class in the first code line.
How can I do that?

```<code><%: Html.TextBoxFor(model => model.Product.Price, String.Format("{0:f}", Model.Product.Price))%>

<%: Html.TextBoxFor(model => model.Product.Name, new { @class = "textBox150" })%>
</code>```

thanks,

Filip

答:
I am afraid there is no clean way to achieve this. There are a couple of possibilities:

Use an editor template for the Product property:

```<code><%: Html.EditorFor(x => x.Product) %>
</code>```

and inside this editor template:

```<code><%: Html.TextBox("Price", string.Format("{0:f}", Model.Product.Price), new { @class = "textBox150" }) %>
<%: Html.TextBoxFor(model => model.Product.Name, new { @class = "textBox150" })%>
</code>```

Write a custom helper that will append the class

Wrap those textboxes in a span:

```<code><span class="container150">
    <%: Html.TextBoxFor(model => model.Product.Price, String.Format("{0:f}", Model.Product.Price))%>
    <%: Html.TextBoxFor(model => model.Product.Name)%>
</span>
</code>```

and then modify your CSS rule:

```<code>.container150 input {
    // some rule that applies to the textbox
}
</code>```

Title: Html.TextBoxFor format and css class

Body:
The two lines of code below work fine, but I want to combine them.
What I mean is: I want to use the @class in the first code line.
How can I do that?

<%: Html.TextBoxFor(model => model.Product.Price, String.Format("{0:f}", Model.Product.Price))%>

<%: Html.TextBoxFor(model => model.Product.Name, new { @class = "textBox150" })%>

thanks,

Filip

Body:
I am afraid there is no clean way to achieve this. There are a couple of possibilities:

Use an editor template for the Product property:

<%: Html.EditorFor(x => x.Product) %>

and inside this editor template:

<%: Html.TextBox("Price", string.Format("{0:f}", Model.Product.Price), new { @class = "textBox150" }) %>
<%: Html.TextBoxFor(model => model.Product.Name, new { @class = "textBox150" })%>

Write a custom helper that will append the class

Wrap those textboxes in a span:

<span class="container150">
    <%: Html.TextBoxFor(model => model.Product.Price, String.Format("{0:f}", Model.Product.Price))%>
    <%: Html.TextBoxFor(model => model.Product.Name)%>
</span>

and then modify your CSS rule:

.container150 input {
    // some rule that applies to the textbox
}


问:
What is ActiveMQ used for - can we apply messaging concept using a Database?
I looked it up and it used to send messages between 2 systems.

But why? Why wouldn't you just use a Database?

There must be some feature that ActiveMQ has that Databases do not?

答:
Suppose you have an application which is being used at multiple locations at the same time.
Also suppose your application has to handle 1000s of request per minute or something like that so normal db operations cannot handle such operations, Activemq acts as the message processing it takes all the messages into queue , so even if one of your application crashes at one location the other location won't be affected.</p>

ContentLicense: CC BY-SA 4.0


问:
Configure culture for client side validation in ASP.NET Core MVC
I having very hard time to configure client side validation in my APP. I would like to it be able to accept localized pt-BR inputs.

I tried configure the app using at startup:

```<code>var locale = "pt-BR";
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions {
    SupportedCultures   = new List<CultureInfo> { new CultureInfo(locale) },
    SupportedUICultures = new List<CultureInfo> { new CultureInfo(locale) },
    DefaultRequestCulture = new RequestCulture(locale)
};
</code>```

and I set  into the main HTML file.

It works for rendering currency, date time and numbers in server side, but the client validation still expecting en-US input.

The client side is using jquery.validate and jquery.validate.unobtrusive

How can I configure the client side validation to understand localized input ?

答:
Create a helper class like this:

```<code>public class PortugueseCulture : CultureInfo
{
    private readonly Calendar cal;
    private readonly Calendar[] optionals;

    public PortugueseCulture()
        : this("pt-BR", true)
    {
    }

    public PortugueseCulture(string cultureName, bool useUserOverride) : base(cultureName, useUserOverride)
    {
        //Your Custom Currency Numbers Calendar Culture Code
    }

    public override Calendar Calendar
    {
        get { return cal; }
    }

    public override Calendar[] OptionalCalendars
    {
        get { return optionals; }
    }
}
</code>```

Then in Global.asax.cs add this method

```<code>    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var portugueseCulture = new PortugueseCulture();
        Thread.CurrentThread.CurrentCulture = portugueseCulture;
        Thread.CurrentThread.CurrentUICulture = portugueseCulture;
    }
</code>```

Body:
I having very hard time to configure client side validation in my APP. I would like to it be able to accept localized pt-BR inputs.

I tried configure the app using at startup:

var locale = "pt-BR";
RequestLocalizationOptions localizationOptions = new RequestLocalizationOptions {
    SupportedCultures   = new List<CultureInfo> { new CultureInfo(locale) },
    SupportedUICultures = new List<CultureInfo> { new CultureInfo(locale) },
    DefaultRequestCulture = new RequestCulture(locale)
};

and I set  into the main HTML file.

It works for rendering currency, date time and numbers in server side, but the client validation still expecting en-US input.

The client side is using jquery.validate and jquery.validate.unobtrusive

How can I configure the client side validation to understand localized input ?

Body:
Create a helper class like this:

public class PortugueseCulture : CultureInfo
{
    private readonly Calendar cal;
    private readonly Calendar[] optionals;

    public PortugueseCulture()
        : this("pt-BR", true)
    {
    }

    public PortugueseCulture(string cultureName, bool useUserOverride) : base(cultureName, useUserOverride)
    {
        //Your Custom Currency Numbers Calendar Culture Code
    }

    public override Calendar Calendar
    {
        get { return cal; }
    }

    public override Calendar[] OptionalCalendars
    {
        get { return optionals; }
    }
}

Then in Global.asax.cs add this method

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var portugueseCulture = new PortugueseCulture();
        Thread.CurrentThread.CurrentCulture = portugueseCulture;
        Thread.CurrentThread.CurrentUICulture = portugueseCulture;
    }


答:
Combine the deduction and earning result sets in a vertical fashion. Then use a matrix in SSRS to display in horizontal formal.</p>

```<code>CREATE TABLE #Employee (EmployeeNumber int, LastName varchar(100), FirstName varchar(100))
CREATE TABLE #Earning (EmployeeNumber int, EarningCode varchar(10), Amount money)
CREATE TABLE #Deduction (EmployeeNumber int, DeductionCode varchar(10), Amount money)

INSERT INTO #Employee (EmployeeNumber, LastName, FirstName) VALUES
(1, 'Smith', 'John'),
(2, 'Doe', 'Jane')

INSERT INTO #Earning (EmployeeNumber, EarningCode, Amount) VALUES
(1, 'EARN1', 1.11),
(1, 'EARN2', 3.33),
(1, 'EARN3', 5.55),
(1, 'EARN4', 7.77),
(2, 'EARN1', 2.22),
(2, 'EARN2', 4.44)

INSERT INTO #Deduction (EmployeeNumber, DeductionCode, Amount) VALUES
(1, 'DEDU1', 2.22),
(1, 'DEDU2', 4.44),
(2, 'DEDU1', 1.11),
(2, 'DEDU2', 3.33),
(2, 'DEDU3', 5.55),
(2, 'DEDU4', 7.77)

SELECT EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, DED.DeductionCode AS 'Code', SUM(Amount) AS 'Amount'
FROM #Employee AS EMP JOIN #Deduction AS DED ON EMP.EmployeeNumber = DED.EmployeeNumber
GROUP BY EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, DED.DeductionCode
UNION ALL
SELECT EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, ERN.EarningCode AS 'Code', SUM(Amount) AS 'Amount'
FROM #Employee AS EMP JOIN #Earning AS ERN ON EMP.EmployeeNumber = ERN.EmployeeNumber
GROUP BY EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, ERN.EarningCode

DROP TABLE #Employee
DROP TABLE #Earning
DROP TABLE #Deduction
</code>```

Title: sql - Joining one table to two more tables

Body:
I am trying to join a table (employee table) to two other tables (employee earnings and employee deductions) to display the amount for the particular type of earning and deduction of employee. Now, when my query duplicates the deduction when the employee has a record for two different types of earning and only one record for a deduction type. Employee has a one-to-many relationship to both earning and deduction tables.

Here is my query:

SELECT EmployeeMaster.EmployeeNumber, FirstName, LastName, MiddleName, empEarnings.EarningCode, empEarnings.amt, empDeduc.DeductionId, empDeduc.amt
from EmployeeMaster
LEFT OUTER JOIN
(
    SELECT EmployeeNumber, EarningCode, SUM(Amount) AS amt FROM EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
) AS empEarnings
ON EmployeeMaster.EmployeeNumber = empEarnings.EmployeeNumber
LEFT OUTER JOIN
(
    SELECT EmployeeID, DeductionID, SUM(Amount) AS amt FROM EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS empDeduc
ON EmployeeMaster.EmployeeNumber = empDeduc.EmployeeId

This returns (sample data only)

00001   First Name  Last Name   EARN       1000000.0000000000000000 SSS 1000.0000000000000000
00001   First Name  Last Name   EARN2      1000.0000000000000000    SSS 1000.0000000000000000
00002   First Name2 Last Name2  EARN       10000.0000000000000000   SSS 100.0000000000000000
00002   First Name2 Last Name2  EARN2      10000.0000000000000000   SSS 100.0000000000000000

The result is almost correct except, these employees only have one record of a deduction type. However, the result set duplicates the deduction table result which results to the sum of the total deduction being wrong (double of the supposed value) in my ssrs report.

How should I modify my query to fit these requirements, and also being able to generate an ssrs report in a format like:

Emp# First Name Last Name EarnType1 EarnType2 [...] DeducType1 DeducType2 [...]
#1    John        Doe       100000    100000        100        100

Body:
Combine the deduction and earning result sets in a vertical fashion. Then use a matrix in SSRS to display in horizontal formal.

CREATE TABLE #Employee (EmployeeNumber int, LastName varchar(100), FirstName varchar(100))
CREATE TABLE #Earning (EmployeeNumber int, EarningCode varchar(10), Amount money)
CREATE TABLE #Deduction (EmployeeNumber int, DeductionCode varchar(10), Amount money)

INSERT INTO #Employee (EmployeeNumber, LastName, FirstName) VALUES
(1, 'Smith', 'John'),
(2, 'Doe', 'Jane')

INSERT INTO #Earning (EmployeeNumber, EarningCode, Amount) VALUES
(1, 'EARN1', 1.11),
(1, 'EARN2', 3.33),
(1, 'EARN3', 5.55),
(1, 'EARN4', 7.77),
(2, 'EARN1', 2.22),
(2, 'EARN2', 4.44)

INSERT INTO #Deduction (EmployeeNumber, DeductionCode, Amount) VALUES
(1, 'DEDU1', 2.22),
(1, 'DEDU2', 4.44),
(2, 'DEDU1', 1.11),
(2, 'DEDU2', 3.33),
(2, 'DEDU3', 5.55),
(2, 'DEDU4', 7.77)

SELECT EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, DED.DeductionCode AS 'Code', SUM(Amount) AS 'Amount'
FROM #Employee AS EMP JOIN #Deduction AS DED ON EMP.EmployeeNumber = DED.EmployeeNumber
GROUP BY EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, DED.DeductionCode
UNION ALL
SELECT EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, ERN.EarningCode AS 'Code', SUM(Amount) AS 'Amount'
FROM #Employee AS EMP JOIN #Earning AS ERN ON EMP.EmployeeNumber = ERN.EmployeeNumber
GROUP BY EMP.EmployeeNumber, EMP.FirstName, EMP.LastName, ERN.EarningCode

DROP TABLE #Employee
DROP TABLE #Earning
DROP TABLE #Deduction


答:
Because you coded a System.Exit() at the point that you reach the 9th recursion.
That causes yout program to finish. You can use a return statement instead.</p>

Title: Why isn't my function being called in Java?


问:
Which CSS selector to use to select the first letter of the element with id?
Which CSS selector to use to select the first letter of the element with id?
I want to make the first letter of the element with id 'special' green and 100px font size.
I tried :</p>

```<code>#special:nth-of-type(1){
    color: green;
    font-size: 100px;
}
</code>```

答:
I've had the same issue. The answer above is correct. For further information, read the following on https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

"21. X::pseudoElement

```<code>p::first-line {
   font-weight: bold;
   font-size: 1.2em;
}
</code>```

We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line, or the first letter. Keep in mind that these must be applied to block level elements in order to take effect.

A pseudo-element is composed of two colons: ::

Target the First Letter of a Paragraph

```<code>p::first-letter {
float: left;
font-size: 2em;
font-weight: bold;
font-family: cursive;
padding-right: 2px;
}
</code>```

This snippet is an abstraction that will find all paragraphs on the page, and then sub-target only the first letter of that element.

This is most often used to create newspaper-like styling for the first-letter of an article.

Target the First Line of a Paragraph

```<code>p::first-line {
font-weight: bold;
font-size: 1.2em;
}
</code>```

Similarly, the ::first-line pseudo element will, as expected, style the first line of the element only."

If you want to select the first letter of the element with id, simply add a "#" in order to select it. It goes like this:

```<code>#insertnameofyouridhere::first-line {
       color: blue;
       font-size: 20px;
    }
</code>```

Body:
Which CSS selector to use to select the first letter of the element with id?
I want to make the first letter of the element with id 'special' green and 100px font size.
I tried :

#special:nth-of-type(1){
    color: green;
    font-size: 100px;
}

Body:
I've had the same issue. The answer above is correct. For further information, read the following on https://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

"21. X::pseudoElement

p::first-line {
   font-weight: bold;
   font-size: 1.2em;
}

We can use pseudo elements (designated by ::) to style fragments of an element, such as the first line, or the first letter. Keep in mind that these must be applied to block level elements in order to take effect.

A pseudo-element is composed of two colons: ::

Target the First Letter of a Paragraph

p::first-letter {
float: left;
font-size: 2em;
font-weight: bold;
font-family: cursive;
padding-right: 2px;
}

This snippet is an abstraction that will find all paragraphs on the page, and then sub-target only the first letter of that element.

This is most often used to create newspaper-like styling for the first-letter of an article.

Target the First Line of a Paragraph

p::first-line {
font-weight: bold;
font-size: 1.2em;
}

Similarly, the ::first-line pseudo element will, as expected, style the first line of the element only."

If you want to select the first letter of the element with id, simply add a "#" in order to select it. It goes like this:

#insertnameofyouridhere::first-line {
       color: blue;
       font-size: 20px;
    }


问:
Find certain file type in c and save it
I need to find files of a certain type (.bin) in a folder and then sort their content and rename the sorted files again. Any ideas on how to do this? This far i have only

```<code>system("find -03 -L /home/Desktop/Folder1 "*.bin");
</code>```

and i have no idea what to do next. Please help !

答:
Avoid using system() if you can. C lets you do all these things without having to call external programs.

Use the opendir(), readdir() and closedir() functions to get the names of all files in a directory. For every filename, check if it has the right extension, and if so add it to an array, You can use the qsort() function to sort the array. You can rename files using the rename() function.

If you need to do this recursively, then have a look at the ftw() and nftw() functions.

Title: Find certain file type in c and save it

Body:
I need to find files of a certain type (.bin) in a folder and then sort their content and rename the sorted files again. Any ideas on how to do this? This far i have only

system("find -03 -L /home/Desktop/Folder1 "*.bin");

and i have no idea what to do next. Please help !


Title: PySpark won't convert timestamp

Body:
I have a very simple CSV, call it test.csv

name,timestamp,action
A,2012-10-12 00:30:00.0000000,1
B,2012-10-12 01:00:00.0000000,2
C,2012-10-12 01:30:00.0000000,2
D,2012-10-12 02:00:00.0000000,3
E,2012-10-12 02:30:00.0000000,1

I'm trying to read it using pyspark and add a new column indicating the month.

First I read in the data, and everything looks ok.

df = spark.read.csv('test.csv', inferSchema=True, header=True)
df.printSchema()
df.show()

Output:

root
 |-- name: string (nullable = true)
 |-- timestamp: timestamp (nullable = true)
 |-- action: double (nullable = true)

+----+-------------------+------+
|name|          timestamp|action|
+----+-------------------+------+
|   A|2012-10-12 00:30:00|   1.0|
|   B|2012-10-12 01:00:00|   2.0|
|   C|2012-10-12 01:30:00|   2.0|
|   D|2012-10-12 02:00:00|   3.0|
|   E|2012-10-12 02:30:00|   1.0|
+----+-------------------+------+

But when I try to add my column, the formatting option doesn't seem to do anything.

df.withColumn('month', to_date(col('timestamp'), format='MMM')).show()

Output:

+----+-------------------+------+----------+
|name|          timestamp|action|     month|
+----+-------------------+------+----------+
|   A|2012-10-12 00:30:00|   1.0|2012-10-12|
|   B|2012-10-12 01:00:00|   2.0|2012-10-12|
|   C|2012-10-12 01:30:00|   2.0|2012-10-12|
|   D|2012-10-12 02:00:00|   3.0|2012-10-12|
|   E|2012-10-12 02:30:00|   1.0|2012-10-12|
+----+-------------------+------+----------+

What's going on here?

Body:
to_date with format is used for parse string type columns. What you need is date_format

from pyspark.sql.functions import date_format

df.withColumn('month', date_format(col('timestamp'), format='MMM')).show()

# +----+-------------------+------+-----+
# |name|          timestamp|action|month|
# +----+-------------------+------+-----+
# |   A|2012-10-12 00:30:00|   1.0|  Oct|
# |   B|2012-10-12 01:00:00|   2.0|  Oct|
# |   C|2012-10-12 01:30:00|   2.0|  Oct|
# |   D|2012-10-12 02:00:00|   3.0|  Oct|
# |   E|2012-10-12 02:30:00|   1.0|  Oct|
# +----+-------------------+------+-----+


问:
Swift: Unable to detect linear type Barcodes
I am writing a barcode reader app but I am unable to detect linear type barcodes, ie code 128. I have no issues with Qr codes, EAN13 types and ISBN types. My code is pretty straightforward:

```<code>func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {

        if metadataObjects.count != 0 {
            if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
                if object.type == AVMetadataObject.ObjectType.qr {
                    if let text = object.stringValue {
                        print(text)

                        session.stopRunning()

                        let alertVC = UIAlertController(title: "QR Code", message: text, preferredStyle: UIAlertControllerStyle.alert)
                        alertVC.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
                            self.session.startRunning()
                        }))
                        present(alertVC, animated: true, completion: nil)
                    }
                } else {
                    if let text = object.stringValue {
                        print("Other code detected: ", text)
                    }
                }
            }
        }
</code>```

I used this free online barcode generator to test my app. I am able to detect most of other barcodes, except Linear Codes. Has anyone encountered such problems too?

答:
Make sure to include AVMetadataObjectTypeCode128Code [.code128] when setting AVCaptureMetadataOutput object types metadataObjectTypes.

```<code>metadataOutput.metadataObjectTypes = [.qr, .ean13, .code128]
</code>```

If you would like to allow all available metadata object types you can use  AVCaptureMetadataOutput property availableMetadataObjectTypeswhich return all available types:

```<code>metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes
</code>```

If you would like to allow all of then except the faces which is the first one, you can drop the first element of the availableMetadataObjectTypes. Note that Apple might change the metadata elements order in the near future so it is better to manually select only the barcode types required by your app:

```<code>metadataOutput.metadataObjectTypes =  Array(metadataOutput.availableMetadataObjectTypes.dropFirst())
</code>```

Just a few notes on your actual code. You shouldn't check the elements count if it is equal to zero to check if it is empty. Array has a property called isEmpty exactly for that if !metadataObjects.isEmpty { //.... Another option is if only the first element of the array is used I recommend using Array .first instead of subscript [0] which returns an optional element AVMetadataObject? and AVMetadataObject.ObjectType is redundant in your comparison:

```<code>if let object = metadataObjects.first as? AVMetadataMachineReadableCodeObject {
    if object.type == .qr {
        if let text = object.stringValue {
            print(text)
            session.stopRunning()
            let alertVC = UIAlertController(title: "QR Code", message: text, preferredStyle: .alert)
            alertVC.addAction(UIAlertAction(title: "Ok", style: .default) { _ in
                self.session.startRunning()
            })
            present(alertVC, animated: true)
        }
    }
    else
    if let text = object.stringValue {
        print("Other code detected: ", text)
    }
}
</code>```

Body:
I am writing a barcode reader app but I am unable to detect linear type barcodes, ie code 128. I have no issues with Qr codes, EAN13 types and ISBN types. My code is pretty straightforward:

func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {

        if metadataObjects.count != 0 {
            if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
                if object.type == AVMetadataObject.ObjectType.qr {
                    if let text = object.stringValue {
                        print(text)

                        session.stopRunning()

                        let alertVC = UIAlertController(title: "QR Code", message: text, preferredStyle: UIAlertControllerStyle.alert)
                        alertVC.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
                            self.session.startRunning()
                        }))
                        present(alertVC, animated: true, completion: nil)
                    }
                } else {
                    if let text = object.stringValue {
                        print("Other code detected: ", text)
                    }
                }
            }
        }

I used this free online barcode generator to test my app. I am able to detect most of other barcodes, except Linear Codes. Has anyone encountered such problems too?

Body:
Make sure to include AVMetadataObjectTypeCode128Code [.code128] when setting AVCaptureMetadataOutput object types metadataObjectTypes.

metadataOutput.metadataObjectTypes = [.qr, .ean13, .code128]

If you would like to allow all available metadata object types you can use  AVCaptureMetadataOutput property availableMetadataObjectTypeswhich return all available types:

metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes

If you would like to allow all of then except the faces which is the first one, you can drop the first element of the availableMetadataObjectTypes. Note that Apple might change the metadata elements order in the near future so it is better to manually select only the barcode types required by your app:

metadataOutput.metadataObjectTypes =  Array(metadataOutput.availableMetadataObjectTypes.dropFirst())

Just a few notes on your actual code. You shouldn't check the elements count if it is equal to zero to check if it is empty. Array has a property called isEmpty exactly for that if !metadataObjects.isEmpty { //.... Another option is if only the first element of the array is used I recommend using Array .first instead of subscript [0] which returns an optional element AVMetadataObject? and AVMetadataObject.ObjectType is redundant in your comparison:

if let object = metadataObjects.first as? AVMetadataMachineReadableCodeObject {
    if object.type == .qr {
        if let text = object.stringValue {
            print(text)
            session.stopRunning()
            let alertVC = UIAlertController(title: "QR Code", message: text, preferredStyle: .alert)
            alertVC.addAction(UIAlertAction(title: "Ok", style: .default) { _ in
                self.session.startRunning()
            })
            present(alertVC, animated: true)
        }
    }
    else
    if let text = object.stringValue {
        print("Other code detected: ", text)
    }
}


问:
Modifying the weights and biases of a restored CNN model in TensorFlow
I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following:
how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF?

Here is my code:

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
  LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
  LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

  # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) #

  # Testing the acuracy of the model:
  X = g.get_tensor_by_name('ImageIn:0')
  Y = g.get_tensor_by_name('LabelIn:0')
  KP = g.get_tensor_by_name('KeepProb:0')
  Accuracy = g.get_tensor_by_name('NetAccuracy:0')
  feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
  print( 'Model Accuracy = ' )
  print( sess.run( Accuracy, feed_dict ) )
</code>```

答:
In addition to an existing answer, tensor update can be performed via tf.assign function.

v1 = sess.graph.get_tensor_by_name('v1:0')
print(sess.run(v1))   # 1.0
sess.run(tf.assign(v1, v1 + 1))
print(sess.run(v1))   # 2.0
```

Body:
I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following:
how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF?

Here is my code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset

# Data Set:
# ---------
mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored

ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image)
NumOfClasses = 10

g = tf.get_default_graph()

with tf.Session() as sess:
  LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta')  # This object loads the model
  LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model

  # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) #

  # Testing the acuracy of the model:
  X = g.get_tensor_by_name('ImageIn:0')
  Y = g.get_tensor_by_name('LabelIn:0')
  KP = g.get_tensor_by_name('KeepProb:0')
  Accuracy = g.get_tensor_by_name('NetAccuracy:0')
  feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 }
  print( 'Model Accuracy = ' )
  print( sess.run( Accuracy, feed_dict ) )


问:
Python 3: using requests does not get the full content of a web page
I am testing using the requests module to get the content of a webpage. But when I look at the content I see that it does not get the full content of the page.

Here is my code:

```<code>import requests
from bs4 import BeautifulSoup

url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
page = requests.get(url)

soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())
</code>```

Also on the chrome web-browser if I look at the page source I do not see the full content.

Is there a way to get the full content of the example page that I have provided?

答: Request is different from getting page source or visual elements of the web page, also viewing source from web page doesn't give you full access to everything that is on the web page including database requests and other back-end stuff. Either your question is not clear enough or you've misinterpreted how web browsing works.</p>

Body:
I am testing using the requests module to get the content of a webpage. But when I look at the content I see that it does not get the full content of the page.

Here is my code:

import requests
from bs4 import BeautifulSoup

url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
page = requests.get(url)

soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())

Also on the chrome web-browser if I look at the page source I do not see the full content.

Is there a way to get the full content of the example page that I have provided?


问:
What is the result of adding an Object and an Array in javascript?
I tried this code in the address bar:

javascript: alert({} + [])

The result is: [object Object].

javascript: alert(typeof ({} + []))

The result is: string.

Can somebody explain to me what's going on?

答:
The concatenation operator (+) concatenates two string values together. If you give it things that are not string values, then it calls the .toString() method on them first.

In response to the comment below, "Yes it does!"

```<code>Object.prototype.toString = function () { return "a"; };
Array.prototype.toString = function () { return "b"; };
var foo = {} + [];
alert(foo); // alerts 'ab'
</code>```

Without the above modifications to the prototypes, if you have alert({} + []) then you are taking {}.toString() (which is "[Object object]") and [].toString() (which is "" as the array is empty), then concatenating them (which is still "[Object object]"). This is a string and typeof will tell you that it is a string.

Body:
The concatenation operator (+) concatenates two string values together. If you give it things that are not string values, then it calls the .toString() method on them first.

In response to the comment below, "Yes it does!"

Object.prototype.toString = function () { return "a"; };
Array.prototype.toString = function () { return "b"; };
var foo = {} + [];
alert(foo); // alerts 'ab'

Without the above modifications to the prototypes, if you have alert({} + []) then you are taking {}.toString() (which is "[Object object]") and [].toString() (which is "" as the array is empty), then concatenating them (which is still "[Object object]"). This is a string and typeof will tell you that it is a string.


答:
If the format of the input string is known, and is as suggested by the posted example input, sscanf() can be used with the scanset directive to extract the IP address.

Using %*[^:] causes sscanf() to match any characters in the input until a colon is encountered. The * suppresses assignment. Scanning resumes with the : character, so a literal : must be placed in the format string to match this character. Then the %s directive can be used to match and store the IP address as a string. Here is an example:

```<code>#include <stdio.h>

#define BUF_SZ  256

int main(void)
{
    const char *input = "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection";

    char ip_address[BUF_SZ];
    if (sscanf(input, "%*[^:]: %255s", ip_address) == 1) {
        puts(ip_address);
    }

    return 0;
}
</code>```

Program output:

192.168.1.200
```

Title: copy a sub part of a string

Body:
I'm trying to copy a part of a string in a other string.
I know the 2 identifiers starting and ending the sub-string.

I'm trying to copy the IP from this string:

0x200085f6 <memp_memory+4502> "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection

The beginning of the string will be "Host: " or 192
The ending will be "\r\nC" or the 2nd occurrence of "\r\n"
So the desired output is:

192.168.1.200

I tried using strcpy and memcpy but the IP has to be variable so I don't know how long it will be or what it will be, the minimum will be 11 and the maximum 15 chars.

I hope you can help me further.

Body:
If the format of the input string is known, and is as suggested by the posted example input, sscanf() can be used with the scanset directive to extract the IP address.

Using %*[^:] causes sscanf() to match any characters in the input until a colon is encountered. The * suppresses assignment. Scanning resumes with the : character, so a literal : must be placed in the format string to match this character. Then the %s directive can be used to match and store the IP address as a string. Here is an example:

#include <stdio.h>

#define BUF_SZ  256

int main(void)
{
    const char *input = "GET / HTTP/1.1\r\nHost: 192.168.1.200\r\nConnection";

    char ip_address[BUF_SZ];
    if (sscanf(input, "%*[^:]: %255s", ip_address) == 1) {
        puts(ip_address);
    }

    return 0;
}

Program output:

192.168.1.200


问:
Collections in Hugo data file using Netlify CMS
I'm trying to get my head round using Netlify CMS with Hugo ssg.

I use:

```<code>netlify-cms@1.0
hugo@0.29
</code>```

I have a simple netlify-cms config.yml with two collections: posts and authors.

```<code>  backend:
    name: github
    repo: sebhewelt/atlas
    branch: master

  display_url: https://mypage.com
  publish_mode: editorial_workflow
  media_folder: "static/uploads"
  public_folder: "/uploads"
  collections:

    - label: "Posts"
      name: "post"
      folder: "content"
      create: true
      slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
      fields:
        - { label: "Title", name: "title", widget: "string" }
        - { label: "Publish Date", name: "date", widget: "datetime" , format: "YYYY-MM-DD hh:mma"}
        - { label: "Body", name: "body", widget: "markdown" }

    - label: "Authors"
      name: "author"
      folder: "data"
      create: true
      fields:
        - {label: "Name", name: "name", widget: "string"}
        - {label: "About", name: "about", widget: "string"}
</code>```

The docs distinguish two collection types, of which I assume i should choose file collection, as I'd like to hold the authors data in one file.

I'd like to be able to add authors via admin dashboard and save it to file in data folder. The docs doesn't provide an example of how should the file holding the authors look like (Or does the cms make it automatically?).

I encounter an error with my current config. When I'm saving the "New Author" i get this:

Failed to persist entry: Error: Collection must have a field name that
  is a valid entry identifier

Why do i get this error?

答:
Your authors file needs to be under a top-level collection. Also, if you want to be able to add multiple authors to the file, you need to wrap the "name" and "about" widgets in a "list" type widget.

Example:

```<code>  collections:
    - label: "Settings"
      name: "settings"
      files:
        - name: "authors"
          label: "Authors"
          file: "data/authors.yml"
          extension: "yml"
          fields:
            - label: "Author"
              name: "author"
              widget: "list"
              fields:
                - {label: "Name", name: "name", widget: "string"}
                - {label: "About", name: "about", widget: "string"}
</code>```

CMS docs for file collections: https://www.netlifycms.org/docs/collection-types/#file-collections

CMS docs for list widgets: https://www.netlifycms.org/docs/widgets/#list

Body:
I'm trying to get my head round using Netlify CMS with Hugo ssg.

I use:

netlify-cms@1.0
hugo@0.29

I have a simple netlify-cms config.yml with two collections: posts and authors.

  backend:
    name: github
    repo: sebhewelt/atlas
    branch: master

  display_url: https://mypage.com
  publish_mode: editorial_workflow
  media_folder: "static/uploads"
  public_folder: "/uploads"
  collections:

    - label: "Posts"
      name: "post"
      folder: "content"
      create: true
      slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
      fields:
        - { label: "Title", name: "title", widget: "string" }
        - { label: "Publish Date", name: "date", widget: "datetime" , format: "YYYY-MM-DD hh:mma"}
        - { label: "Body", name: "body", widget: "markdown" }

    - label: "Authors"
      name: "author"
      folder: "data"
      create: true
      fields:
        - {label: "Name", name: "name", widget: "string"}
        - {label: "About", name: "about", widget: "string"}

The docs distinguish two collection types, of which I assume i should choose file collection, as I'd like to hold the authors data in one file.

I'd like to be able to add authors via admin dashboard and save it to file in data folder. The docs doesn't provide an example of how should the file holding the authors look like (Or does the cms make it automatically?).

I encounter an error with my current config. When I'm saving the "New Author" i get this:

Failed to persist entry: Error: Collection must have a field name that
  is a valid entry identifier

Why do i get this error?

Body:
Your authors file needs to be under a top-level collection. Also, if you want to be able to add multiple authors to the file, you need to wrap the "name" and "about" widgets in a "list" type widget.

Example:

  collections:
    - label: "Settings"
      name: "settings"
      files:
        - name: "authors"
          label: "Authors"
          file: "data/authors.yml"
          extension: "yml"
          fields:
            - label: "Author"
              name: "author"
              widget: "list"
              fields:
                - {label: "Name", name: "name", widget: "string"}
                - {label: "About", name: "about", widget: "string"}

CMS docs for file collections: https://www.netlifycms.org/docs/collection-types/#file-collections

CMS docs for list widgets: https://www.netlifycms.org/docs/widgets/#list


问:
MKMapView setRegion animated does not show animation
I have a MKMapView with annotation pins. When the view was loaded the nearest pin gets searched and the map will get zoomed so it shows both, the user's location and the nearest pin. I do that with [map setRegion:region animated:YES];. Everything works fine up to here. The same method is also called by tapping on a button which locates the user and then does exactly what I just described.

I also have a search field with which the user can search for map points. When the user taps on one of the search results the map sets the region so the searched pin is in the middle.
Now, there's something strange with that. I also set this region animated, at least I do the same command as above. But if the map point is too far away from the current visible part of the map it doesn't show the animation when changing the region.
Am I missing something? I've already had a look at Apples docs, they don't mention anything regarding any maximum distance for animations.

I'm looking forward to any help!

Update 1:

Just tested it again in the Simulator. An interesting fact is, that when I search for a MapPoint for the first time and then select a search result it doesn't animate. If I perform another search just after the first one and select a result it does animate. As soon as I tap on the locate button which brings the user back to his location and the closest point it doesn't animate for this setRegion: and the first search after that. But only in the Simulator, on my 4S it does exactly what I've described in the original question above.

Update 2:

In the comments I was asked to provide example coordinates.

So here the coordinates for the first step (searching of the own location and the nearest pin):

My Location: 47.227131 / 8.264251

Nearest pin: 47.251347 / 8.357191

The distance between them is about 22 kilometers. The center of the map is the center between the two pins. The distance from the center to the screen border is 1.5 times the distance between the two points which means about 33 kilometers in this case.

And here a set of coordinates for the second step (searching a map point and selecting it):

Searched pin: 46.790680 / 9.818824

The distance to the screen border is here fixed to 500 meters.

答:
Here are the functions by @Felix rewritten to Swift 4:</p>

```<code>// MARK: - MapView help properties
var destinationRegion: MKCoordinateRegion?
var intermediateAnimation = false

func center() {
    // Center map
    var initialCoordinates = CLLocationCoordinate2D(latitude: 49.195061, longitude: 16.606836)
    var regionRadius: CLLocationDistance = 5000000

    destinationRegion = MKCoordinateRegionMakeWithDistance(initialCoordinates, regionRadius * 2.0, regionRadius * 2.0)
    centreMap(on: destinationRegion!)
}

private func mapRect(forCoordinateRegion region: MKCoordinateRegion) -> MKMapRect {
    let topLeft = CLLocationCoordinate2D(latitude: region.center.latitude + (region.span.latitudeDelta/2), longitude: region.center.longitude - (region.span.longitudeDelta/2))
    let bottomRight = CLLocationCoordinate2D(latitude: region.center.latitude - (region.span.latitudeDelta/2), longitude: region.center.longitude + (region.span.longitudeDelta/2))

    let a = MKMapPointForCoordinate(topLeft)
    let b = MKMapPointForCoordinate(bottomRight)

    return MKMapRect(origin: MKMapPoint(x:min(a.x,b.x), y:min(a.y,b.y)), size: MKMapSize(width: abs(a.x-b.x), height: abs(a.y-b.y)))
}

func centreMap(on region: MKCoordinateRegion) {
    var region = region
    var rect = mapRect(forCoordinateRegion: region)
    let intersection = MKMapRectIntersection(rect, mapView.visibleMapRect)

    if MKMapRectIsNull(intersection) {
        rect = MKMapRectUnion(rect, mapView.visibleMapRect)
        region = MKCoordinateRegionForMapRect(rect)
        intermediateAnimation = true
    }

    mapView.setRegion(region, animated: true)
}

// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    if intermediateAnimation, let region = destinationRegion {
        intermediateAnimation = false
        mapView.setRegion(region, animated: true)
    }
}
</code>```

Body:
Here are the functions by @Felix rewritten to Swift 4:

// MARK: - MapView help properties
var destinationRegion: MKCoordinateRegion?
var intermediateAnimation = false

func center() {
    // Center map
    var initialCoordinates = CLLocationCoordinate2D(latitude: 49.195061, longitude: 16.606836)
    var regionRadius: CLLocationDistance = 5000000

    destinationRegion = MKCoordinateRegionMakeWithDistance(initialCoordinates, regionRadius * 2.0, regionRadius * 2.0)
    centreMap(on: destinationRegion!)
}

private func mapRect(forCoordinateRegion region: MKCoordinateRegion) -> MKMapRect {
    let topLeft = CLLocationCoordinate2D(latitude: region.center.latitude + (region.span.latitudeDelta/2), longitude: region.center.longitude - (region.span.longitudeDelta/2))
    let bottomRight = CLLocationCoordinate2D(latitude: region.center.latitude - (region.span.latitudeDelta/2), longitude: region.center.longitude + (region.span.longitudeDelta/2))

    let a = MKMapPointForCoordinate(topLeft)
    let b = MKMapPointForCoordinate(bottomRight)

    return MKMapRect(origin: MKMapPoint(x:min(a.x,b.x), y:min(a.y,b.y)), size: MKMapSize(width: abs(a.x-b.x), height: abs(a.y-b.y)))
}

func centreMap(on region: MKCoordinateRegion) {
    var region = region
    var rect = mapRect(forCoordinateRegion: region)
    let intersection = MKMapRectIntersection(rect, mapView.visibleMapRect)

    if MKMapRectIsNull(intersection) {
        rect = MKMapRectUnion(rect, mapView.visibleMapRect)
        region = MKCoordinateRegionForMapRect(rect)
        intermediateAnimation = true
    }

    mapView.setRegion(region, animated: true)
}

// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    if intermediateAnimation, let region = destinationRegion {
        intermediateAnimation = false
        mapView.setRegion(region, animated: true)
    }
}


问:
Given a string describing a Javascript function, convert it to a Javascript function
Say I've got a Javascript string like the following

```<code>var fnStr = "function(){blah1;blah2;blah3; }" ;
</code>```

(This may be from an expression the user has typed in, duly sanitized, or it may be the result of some symbolic computation.  It really doesn't matter).

I want to define fn as if the following line was in my code:

```<code>var fn = function(){blah1;blah2;blah3; } ;
</code>```

How do I do that?

The best I've come up with is the following:

```<code>var fn = eval("var f = function(){ return "+fnStr+";}; f() ;") ;
</code>```

This seems to do the trick, even though it uses the dreaded eval(), and uses a slightly convoluted argument.  Can I do better?  I.e. either not use eval(), or supply it with a simpler argument?

答:
Use parentheses.

```<code>var fn = eval("(function() {...})");
</code>```

This technique is also good for transmitting JSON values.

By the way, it's often better to build functions by composing them directly from other functions.  If you are using strings, you have to worry about things like unexpected variable capture.

Body:
Say I've got a Javascript string like the following

var fnStr = "function(){blah1;blah2;blah3; }" ;

(This may be from an expression the user has typed in, duly sanitized, or it may be the result of some symbolic computation.  It really doesn't matter).

I want to define fn as if the following line was in my code:

var fn = function(){blah1;blah2;blah3; } ;

How do I do that?

The best I've come up with is the following:

var fn = eval("var f = function(){ return "+fnStr+";}; f() ;") ;

This seems to do the trick, even though it uses the dreaded eval(), and uses a slightly convoluted argument.  Can I do better?  I.e. either not use eval(), or supply it with a simpler argument?

Body:
Use parentheses.

var fn = eval("(function() {...})");

This technique is also good for transmitting JSON values.

By the way, it's often better to build functions by composing them directly from other functions.  If you are using strings, you have to worry about things like unexpected variable capture.


答:
You can use eval here:

```<code>dict_from_file = {}
with open('output.txt','r') as f:
    for line in f:
        d_line = line.rstrip('\n')
        dict_from_file.update(eval('{{{0}}}'.format(d_line)))
</code>```

Or to keep it compact:

```<code>with open('output.txt', 'r') as f:
    dict_from_file = eval('{{{0}}}'.format(','.join(f.readlines()))
</code>```

Please note though: eval is not a save method. If you are not absolutely sure about the content you feed eval, don't use it!

A saver alternative is ast.literal_eval. You can use it just as eval here.

The best approach in this case would be to not have the first script write the dictionaries as plain text. Using something like pickles is both saver and simpler!

Title: Python: Reading in Dictionary from Textfile

Body:
I have an ugly problem I've come across. I'm being fed the following text file, which is output from another Python file. From that previous file, it's a dictionary that was spit out into this text file.

Text file (named 'output.txt'):

0:[([(11, 191), (11, 170), (14, 170), (11, 188)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]
90:[([(95, 170), (95, 2), (119, 2), (95, 146)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]
180:[([(182, 2), (182, 23), (179, 23), (182, 5)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]
270:[([(98, 23), (98, 191), (74, 191), (98, 47)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]

I'm fairly familiar with reading in text files, but this one has me stumped. The silly thing about this whole problem is that I actually need the file to be given to me in a dictionary format, so I'm basically just trying to read in the file as it was given to me. The problem is when reading it in, Python doesn't know it's a dictionary and instead gives me strings. Is there anyway to have the values of the dictionary read in as a list of lists instead of just a string (shown below)? Thanks very much!

d = {}
with open("output.txt") as f:
    for line in f:
        d_line = line.rstrip('\n').split(':')
        d[int(d_line[0])] = d_line[1]

print(d)

{0: '[([(11, 191), (11, 170), (14, 170), (11, 188)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]', 90: '[([(95, 170), (95, 2), (119, 2), (95, 146)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]', 180: '[([(182, 2), (182, 23), (179, 23), (182, 5)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]', 270: '[([(98, 23), (98, 191), (74, 191), (98, 47)], [0.7830932724146064, 0.7789413675533634, 0.7714495149543579, 0.7688444764225846])]'}

Body:
You can use eval here:

dict_from_file = {}
with open('output.txt','r') as f:
    for line in f:
        d_line = line.rstrip('\n')
        dict_from_file.update(eval('{{{0}}}'.format(d_line)))

Or to keep it compact:

with open('output.txt', 'r') as f:
    dict_from_file = eval('{{{0}}}'.format(','.join(f.readlines()))

Please note though: eval is not a save method. If you are not absolutely sure about the content you feed eval, don't use it!

A saver alternative is ast.literal_eval. You can use it just as eval here.

The best approach in this case would be to not have the first script write the dictionaries as plain text. Using something like pickles is both saver and simpler!