问:
Why does the type-inferencing logic fails with an iteration over a TreeNodeCollection?
I am a bit puzzled with this behavior,

This code compiles fine:

```<code>private void CheckAvailabilityOfCurrentTreeNodes() {
   foreach( TreeNode treeNode in this.DeviceTree.Nodes ) {
      if( Object.ReferenceEquals(treeNode.Tag, _recorder.CaptureDevice) ) {
         ...
       }
   }
}
</code>```

But the following produces a compilation error saying that 'object' does not contain a definition for 'Tag'

```<code>private void CheckAvailabilityOfCurrentTreeNodes() {
   foreach( var treeNode in this.DeviceTree.Nodes ) {
      if( Object.ReferenceEquals(treeNode.Tag, _recorder.CaptureDevice) ) {
         ...
       }
   }
}
</code>```

In this case, the type-inferencing logic is returning Object as the iterator's result type, but I don't understand clearly why, since the TreeNodeCollection is strongly-typed.  Is it because this collection type is quite dated?

Can someone enlighten me on the technical reasons for this behavior?

答:
since the TreeNodeCollection is strongly-typed

Here is the definition of the TreeNodeCollection class:

```<code>public class TreeNodeCollection : IList, ICollection, IEnumerable
</code>```

As you can see, it's not strongly typed because it implements the non generic IEnumerable interface rather than IEnumerable<TreeNode>. So the type inference works, just the inferred type from IEnumerable.Current is object.

This basically applies to all WinForms collections. Although most of them provide strongly typed indexer, all they implement the non generic IEnumerable interface.

Why? Because they were created at the time generics (hence IEnumerable<T> interface) didn't exist. And simply never get updated.

Body:
I am a bit puzzled with this behavior,

This code compiles fine:

private void CheckAvailabilityOfCurrentTreeNodes() {
   foreach( TreeNode treeNode in this.DeviceTree.Nodes ) {
      if( Object.ReferenceEquals(treeNode.Tag, _recorder.CaptureDevice) ) {
         ...
       }
   }
}

But the following produces a compilation error saying that 'object' does not contain a definition for 'Tag'

private void CheckAvailabilityOfCurrentTreeNodes() {
   foreach( var treeNode in this.DeviceTree.Nodes ) {
      if( Object.ReferenceEquals(treeNode.Tag, _recorder.CaptureDevice) ) {
         ...
       }
   }
}

In this case, the type-inferencing logic is returning Object as the iterator's result type, but I don't understand clearly why, since the TreeNodeCollection is strongly-typed.  Is it because this collection type is quite dated?

Can someone enlighten me on the technical reasons for this behavior?

Body:
since the TreeNodeCollection is strongly-typed

Here is the definition of the TreeNodeCollection class:

public class TreeNodeCollection : IList, ICollection, IEnumerable

As you can see, it's not strongly typed because it implements the non generic IEnumerable interface rather than IEnumerable<TreeNode>. So the type inference works, just the inferred type from IEnumerable.Current is object.

This basically applies to all WinForms collections. Although most of them provide strongly typed indexer, all they implement the non generic IEnumerable interface.

Why? Because they were created at the time generics (hence IEnumerable<T> interface) didn't exist. And simply never get updated.


来源: stackexchange

问:
iOS 10 Swift programmatically get sticker from Stickers.xcstickers
I have a sticker package Stickers.xcstickers with a few stickers in it. I would like to programmatically get one of these stickers and put it in a MSStickerView that I have in a UICollectionViewCell. I know with a UIImage it is easy and you can just do

```<code>let myImage = UIImage(named: "myImage.jpg")
</code>```

Is there an equivalent to this with MSSticker?

let mySticker = MSSticker(named: "mySticker") obviously does not work.

There is MSSticker(contentsOfFileURL: URL, localizedDescription: String but I am unsure how to, if possible, properly implement in a similar fashion to UIImage.

Thanks.

答:
BJHStudios is right, unfortunately! I recently answered another question that you may want to take a look at. It goes over everything you need to get your stickers onto the BrowserView with the MSSticker(contentsOfFileURL: URL, localizedDescription: String) method.

Link to other question

ContentLicense: CC BY-SA 3.0

Body:
I have a sticker package Stickers.xcstickers with a few stickers in it. I would like to programmatically get one of these stickers and put it in a MSStickerView that I have in a UICollectionViewCell. I know with a UIImage it is easy and you can just do

let myImage = UIImage(named: "myImage.jpg")

Is there an equivalent to this with MSSticker?

let mySticker = MSSticker(named: "mySticker") obviously does not work.

There is MSSticker(contentsOfFileURL: URL, localizedDescription: String but I am unsure how to, if possible, properly implement in a similar fashion to UIImage.

Thanks.


问:
Detecting document keystrokes in Office-js
Is it possible to detect keystrokes in an Office Online document/workbook/presentation through officeJS, specifically for keystrokes involving character outputs on the document: alphanumerics, space, tabs, new line, etc.

Something similar to how we can add event handlers in javascript such as :

```<code>document.addEventListener('keydown' ...)
</code>```

答: Short answer is no. There are no specific events to detect keystrokes. There are couple of things to note: Due to the asynchronous nature of the APIs, it is not possible to detect and act of the event in a synchronous fashion. The real-time detection and follow-up actions are not ideal use-cases for web based add-ins. However, you could detect changes at a higher level based on data changed events. You'd have to determine what changed in the event handler and know that by then the change would have already taken place. </p>

Body:
Is it possible to detect keystrokes in an Office Online document/workbook/presentation through officeJS, specifically for keystrokes involving character outputs on the document: alphanumerics, space, tabs, new line, etc.

Something similar to how we can add event handlers in javascript such as :

document.addEventListener('keydown' ...)


问:
Webkit browsers not accounting for padding when determining cell width in table-layout:fixed
I am getting different results when applying table-layout:fixed to a table and using padding on the cells. IE and Firefox seem to work correctly by adding the cell width and the padding together. Chrome and Safari only use the cell width. I saw there is a bug out for the problem, but can't find any workarounds. Does anyone know how to get around it?

WebKit Bugzilla : https://bugs.webkit.org/show_bug.cgi?id=13339

```<code>table {
width:200px;
border-collapse:collapse;
}
#table-1 {
table-layout:auto;
}
#table-2 {
table-layout:fixed;
}
td {
padding:5px 10px;
}
td.set-width {
width:15px;
}
.box {
width:15px;
height:15px;
background-color:red;
}

<h2>Table-Layout: Auto</h2>
<table border="1" cellspacing="0" cellpadding="0" id="table-1">
<tr>
<td> </td>
<td class="set-width"><div class="box"></div></td>
</tr>
<tr>
<td> </td>
<td>unbroken</td>
</tr>
</table>
<h2>Table-Layout: Fixed</h2>
<table border="1" cellspacing="0" cellpadding="0" id="table-2">
<tr>
<td> </td>
<td class="set-width"><div class="box"></div></td>
</tr>
<tr>
<td> </td>
<td>unbroken</td>
</tr>
</table>
</code>```

答:
There are 3 methods I can think of.

The easiest would be to add stylesheet blocks interpreted only by Chrome and Safari that adjust behavior to take into account the rendering issue. Avoid using "@media screen and (-webkit-min-device-pixel-ratio:0)" since that can affect Opera and some versions of FF. Use "body:first-of-type":

```<code>body:first-of-type td {
padding:5px 10px;
}
</code>```

You can also have separate stylesheets:

```<code><link rel="stylesheet" type="text/safari" href="webkit-styles.css" />
<link rel="stylesheet" type="text/chrome" href="webkit-styles.css" />
</code>```

The third option is to use Javascript. Within script tags you can use navigator.appName and navigator.appVersion to identify the browser and fix issues dynamically.

Body:
I am getting different results when applying table-layout:fixed to a table and using padding on the cells. IE and Firefox seem to work correctly by adding the cell width and the padding together. Chrome and Safari only use the cell width. I saw there is a bug out for the problem, but can't find any workarounds. Does anyone know how to get around it?

WebKit Bugzilla : https://bugs.webkit.org/show_bug.cgi?id=13339

table {
width:200px;
border-collapse:collapse;
}
#table-1 {
table-layout:auto;
}
#table-2 {
table-layout:fixed;
}
td {
padding:5px 10px;
}
td.set-width {
width:15px;
}
.box {
width:15px;
height:15px;
background-color:red;
}

Table-Layout: Auto

unbroken

Table-Layout: Fixed

unbroken

Body:
There are 3 methods I can think of.

The easiest would be to add stylesheet blocks interpreted only by Chrome and Safari that adjust behavior to take into account the rendering issue. Avoid using "@media screen and (-webkit-min-device-pixel-ratio:0)" since that can affect Opera and some versions of FF. Use "body:first-of-type":

body:first-of-type td {
padding:5px 10px;
}

You can also have separate stylesheets:

<link rel="stylesheet" type="text/safari" href="webkit-styles.css" />
<link rel="stylesheet" type="text/chrome" href="webkit-styles.css" />

The third option is to use Javascript. Within script tags you can use navigator.appName and navigator.appVersion to identify the browser and fix issues dynamically.

ContentLicense: CC BY-SA 2.5


问:
File uploading works on local server but not web server
This exact code will work fine when uploading files on my local XAMPP server but uploading it to my web server this stops working. Other functions of the same project still work fine though.

```<code>    //Image Uploading
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    $allowed = array('png', 'jpg', 'jpeg');

    if(in_array($file_ext, $allowed)) {
        $file_name_new = $username.'.png';
        $file_dest = '../images/'.$file_name_new;
        if($file_error > 0){
            echo "There was an error uploading this image! Try another.";
        } else {
            if(move_uploaded_file($file_tmp, $file_dest)) {
                header("Location: ../user/editprofile.php?user=".$username);
            }
        }
    }
}
</code>```

HTML bit

```<code>                <h2>Profile Image</h2>
            <form action="editprofile.php?user=<?php echo $user; ?>" method="post" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="submit" value="Upload">
            </form>
</code>```

答:
Firstly, I'd pathinfo to get the filename and file extension of the uploaded file. Secondly you should validate mimetype rather than extension by comparing what is in $_FILES['userfile']['type'] against a list of mimetypes, for this situation you'll want to check for ['image/png', 'image/jpeg'] to prevent someone uploading something like a PHP script with a jpg extension. You also probably want to preserve the extension of the uploaded file rather than making them all png as this could cause unexpected errors.

With that out of the way the information will be inside $file_error to let you know exactly why the file isn't uploading. You will get back a file error code that will tell you what has gone wrong.

It will be one of these:

UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

The most common on shared hosting is incorrect permissions on the file you're uploading to (value 7).

Body:
This exact code will work fine when uploading files on my local XAMPP server but uploading it to my web server this stops working. Other functions of the same project still work fine though.

    //Image Uploading
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    $allowed = array('png', 'jpg', 'jpeg');

    if(in_array($file_ext, $allowed)) {
        $file_name_new = $username.'.png';
        $file_dest = '../images/'.$file_name_new;
        if($file_error > 0){
            echo "There was an error uploading this image! Try another.";
        } else {
            if(move_uploaded_file($file_tmp, $file_dest)) {
                header("Location: ../user/editprofile.php?user=".$username);
            }
        }
    }
}

HTML bit

Profile Image

            <form action="editprofile.php?user=<?php echo $user; ?>" method="post" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="submit" value="Upload">
            </form>


问:
In Python, how do I get user's remote IP (their last hop) if they're connected over SSH?
I want to detect if the user is connected over SSH. In a term, the "env" command shows SSH_CONNECTION line. Accessed in Python in one of two ways:

```<code>#python:
import os
print os.getenv("SSH_CONNECTION")       #works
print os.environ.get("SSH_CONNECTION")  #works
</code>```

But, if the user has ran my program using SUDO (as they will need to), env$ dooesn't show SSH_CONNECTION. So Python can't see it:

```<code>#sudo python:
import os
print os.getenv("SSH_CONNECTION")       #not set
print os.environ.get("SSH_CONNECTION")  #not set
</code>```

The aim is to achieve the following:

```<code>#Detect if user is over remote IP
lRemoteIP=""                                     #Is set if user on SSH
lStr=os.environ.get("SSH_CONNECTION")            #Temp var
if lStr: lRemoteIP=lStr.split()[0].split("=")[1] #Store user's lasthop IP

#Later on in the code, for multiple purposes:
if lRemoteIP: pass #Do stuff (or not) depending on if they're on SSH
</code>```

How do I retrieve SSH_CONNECTION environment variable under SUDO, when its not present in env$ ?

Or more precisely: how can I detect if the current session is via SSH when sudo?

I'm not a natural at Linuxy-type things, so be gentle with me...

[EDIT:] METHOD 2: Giving up on env$, I've tried the following:

```<code>pstree -ps $$ | grep "sshd("
</code>```

If it returns anything then it means that the SSH daemon sits above the session. Ergo, it's a SSH connection. And the results are showing me the PIDs of the SSH daemons. Results of the pstree cmd:

```<code>init(1)---sshd(xxx)---sshd(xxx)---sshd(xxx)---bash(xxx)-+-grep(xxx)
</code>```

But I'm struggling to get a src IP from the PID. Any ideas on this avenue?

[EDIT] METHOD 3: /run/utmp contains details of SSH logins. In python:

```<code>import os
import sys

lStr=open("/var/run/utmp").read().replace('\x00','') #Remove all those null values which make things hard to read

#Get the pseudo-session ID (pts) minus the /dev/ that it starts with:
lCurSess=os.ttyname(sys.stdout.fileno()).replace('/dev/','')
#Answer is like pts/10  (pseudo-term session number 10)
#Search lStr for pts/10
lInt=lStr.find(lCurSess.replace('/dev/',''))
#Print /var/utmp starting with where it first mentions current pts:
print lStr[lInt:]
</code>```

So far, so good. This gives the following results (I've changed the IP and username to USERNAME)

```<code>pts/10/10USERNAME\x9e\x958Ym\xb2\x05\x0 74\x14pts/10s/10USERNAME192.168.1.1\xbf\x958Y\xf8\xa3\r\xc0\xa88\x01
</code>```

So, when it comes to extracting the IP from the file, there's some bumf inbetween the occurances of pts/10 and the IP. What's the best way to parse it, given that (I reckon) the precise distance from the match to the IP will be different under different circumstances?

答:
GOT IT AT LAST!!!

The "last" command has list of users and their IPs!! So simple.

It has "still logged in" marked against sessions. Filter by these
And then filter by current pts ID

To get the IP for the current SSH session in Python, do this:

```<code>import os,sys,subprocess
(out, err) = subprocess.Popen(['last | grep "still logged in" | grep "' + os.ttyname(sys.stdout.fileno()).replace('/dev/','') + '"'], stdout=subprocess.PIPE, shell=True).communicate()
RemoteIP=out.split()[2].replace(":0.0","") #Returns "" if not SSH
</code>```

For readability, across multiple lines:

```<code>import os,sys,subprocess
pseudoTermID = os.ttyname(sys.stdout.fileno()).replace('/dev/','')
cmdStr       = 'last | grep "still logged in" | grep "'+pseudoTermID+'"'
sp           = subprocess.Popen([cmdStr], stdout=subprocess.PIPE, shell=True)
(out, err)   = sp.communicate()
RemoteIP     = out.split()[2].replace(":0.0","")   #Returns "" if not SSH
</code>```

Body:
I want to detect if the user is connected over SSH. In a term, the "env" command shows SSH_CONNECTION line. Accessed in Python in one of two ways:

#python:
import os
print os.getenv("SSH_CONNECTION")       #works
print os.environ.get("SSH_CONNECTION")  #works

But, if the user has ran my program using SUDO (as they will need to), env$ dooesn't show SSH_CONNECTION. So Python can't see it:

#sudo python:
import os
print os.getenv("SSH_CONNECTION")       #not set
print os.environ.get("SSH_CONNECTION")  #not set

The aim is to achieve the following:

#Detect if user is over remote IP
lRemoteIP=""                                     #Is set if user on SSH
lStr=os.environ.get("SSH_CONNECTION")            #Temp var
if lStr: lRemoteIP=lStr.split()[0].split("=")[1] #Store user's lasthop IP

#Later on in the code, for multiple purposes:
if lRemoteIP: pass #Do stuff (or not) depending on if they're on SSH

How do I retrieve SSH_CONNECTION environment variable under SUDO, when its not present in env$ ?

Or more precisely: how can I detect if the current session is via SSH when sudo?

I'm not a natural at Linuxy-type things, so be gentle with me...

[EDIT:] METHOD 2: Giving up on env$, I've tried the following:

pstree -ps $$ | grep "sshd("

If it returns anything then it means that the SSH daemon sits above the session. Ergo, it's a SSH connection. And the results are showing me the PIDs of the SSH daemons. Results of the pstree cmd:

init(1)---sshd(xxx)---sshd(xxx)---sshd(xxx)---bash(xxx)-+-grep(xxx)

But I'm struggling to get a src IP from the PID. Any ideas on this avenue?

[EDIT] METHOD 3: /run/utmp contains details of SSH logins. In python:

import os
import sys

lStr=open("/var/run/utmp").read().replace('\x00','') #Remove all those null values which make things hard to read

#Get the pseudo-session ID (pts) minus the /dev/ that it starts with:
lCurSess=os.ttyname(sys.stdout.fileno()).replace('/dev/','')
#Answer is like pts/10  (pseudo-term session number 10)
#Search lStr for pts/10
lInt=lStr.find(lCurSess.replace('/dev/',''))
#Print /var/utmp starting with where it first mentions current pts:
print lStr[lInt:]

So far, so good. This gives the following results (I've changed the IP and username to USERNAME)

pts/10/10USERNAME\x9e\x958Ym\xb2\x05\x0 74\x14pts/10s/10USERNAME192.168.1.1\xbf\x958Y\xf8\xa3\r\xc0\xa88\x01

So, when it comes to extracting the IP from the file, there's some bumf inbetween the occurances of pts/10 and the IP. What's the best way to parse it, given that (I reckon) the precise distance from the match to the IP will be different under different circumstances?

Body:
GOT IT AT LAST!!!

The "last" command has list of users and their IPs!! So simple.

It has "still logged in" marked against sessions. Filter by these
And then filter by current pts ID

To get the IP for the current SSH session in Python, do this:

import os,sys,subprocess
(out, err) = subprocess.Popen(['last | grep "still logged in" | grep "' + os.ttyname(sys.stdout.fileno()).replace('/dev/','') + '"'], stdout=subprocess.PIPE, shell=True).communicate()
RemoteIP=out.split()[2].replace(":0.0","") #Returns "" if not SSH

For readability, across multiple lines:

import os,sys,subprocess
pseudoTermID = os.ttyname(sys.stdout.fileno()).replace('/dev/','')
cmdStr       = 'last | grep "still logged in" | grep "'+pseudoTermID+'"'
sp           = subprocess.Popen([cmdStr], stdout=subprocess.PIPE, shell=True)
(out, err)   = sp.communicate()
RemoteIP     = out.split()[2].replace(":0.0","")   #Returns "" if not SSH


问:
AWS CloudFormation/API Gateway gives 'Invalid Resource identifier specified'
I have been trying to use CloudFormation to deploy to API Gateway, however, I constantly run into the same issue with my method resources. The stack deployments keep failing with 'Invalid Resource identifier specified'.

Here is my method resource from my CloudFormation template:

```<code>"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": "UsersResource",
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }
</code>```

Is anyone able to help me figure out why this keeps failing the stack deployment?

UPDATE: I forgot to mention that I had also tried using references to add the resource ID, that also gave me the same error:

```<code>"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }
</code>```

Here is the full CloudFormation template:

```<code>{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
    "LambdaDynamoDBRole": {
        "Type": "AWS::IAM::Role",
        "Properties": {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [{
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lambda.amazonaws.com"
                        ]
                    },
                    "Action": [
                        "sts:AssumeRole"
                    ]
                }]
            },
            "Path": "/",
            "Policies": [{
                "PolicyName": "DynamoReadWritePolicy",
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Sid": "1",
                        "Action": [
                            "dynamodb:DeleteItem",
                            "dynamodb:GetItem",
                            "dynamodb:PutItem",
                            "dynamodb:Query",
                            "dynamodb:Scan",
                            "dynamodb:UpdateItem"
                        ],
                        "Effect": "Allow",
                        "Resource": "*"
                    }, {
                        "Sid": "2",
                        "Resource": "*",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"
                        ],
                        "Effect": "Allow"
                    }]
                }
            }]
        }
    },
    "MyFirstLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "myfirstlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MyFirstLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MySecondLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "mysecondlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MySecondLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MyApi": {
        "Type": "AWS::ApiGateway::RestApi",
        "Properties": {
            "Name": "Project Test API",
            "Description": "Project Test API",
            "FailOnWarnings": true
        }
    },
    "FirstUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "FirstUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "FirstUserPropertyModel",
                "type": "object",
                "properties": {
                    "Email": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "SecondUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "SecondUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "SecondUserPropertyModel",
                "type": "object",
                "properties": {
                    "Name": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "ErrorCfn": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "ErrorCfn",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "Error Schema",
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "UsersResource": {
        "Type": "AWS::ApiGateway::Resource",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "ParentId": {
                "Fn::GetAtt": ["MyApi", "RootResourceId"]
            },
            "PathPart": "users"
        }
    },
    "UsersPost": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "POST",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyFirstLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "FirstUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MySecondLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "SecondUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "RestApiDeployment": {
        "Type": "AWS::ApiGateway::Deployment",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "StageName": "Prod"
        },
        "DependsOn": ["UsersPost", "UsersPut"]
    }
},
"Description": "Project description"
</code>```

}

答:
I figured that actually it was the RestApiId which needed to be a reference too:</p>

```<code>            "RestApiId": {
                "Ref": "MyApi"
            },
</code>```

Body:
I have been trying to use CloudFormation to deploy to API Gateway, however, I constantly run into the same issue with my method resources. The stack deployments keep failing with 'Invalid Resource identifier specified'.

Here is my method resource from my CloudFormation template:

"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": "UsersResource",
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }

Is anyone able to help me figure out why this keeps failing the stack deployment?

UPDATE: I forgot to mention that I had also tried using references to add the resource ID, that also gave me the same error:

"UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyLambdaFunc", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "StatusCode": 200
            }]
        }
    }

Here is the full CloudFormation template:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
    "LambdaDynamoDBRole": {
        "Type": "AWS::IAM::Role",
        "Properties": {
            "AssumeRolePolicyDocument": {
                "Version": "2012-10-17",
                "Statement": [{
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lambda.amazonaws.com"
                        ]
                    },
                    "Action": [
                        "sts:AssumeRole"
                    ]
                }]
            },
            "Path": "/",
            "Policies": [{
                "PolicyName": "DynamoReadWritePolicy",
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [{
                        "Sid": "1",
                        "Action": [
                            "dynamodb:DeleteItem",
                            "dynamodb:GetItem",
                            "dynamodb:PutItem",
                            "dynamodb:Query",
                            "dynamodb:Scan",
                            "dynamodb:UpdateItem"
                        ],
                        "Effect": "Allow",
                        "Resource": "*"
                    }, {
                        "Sid": "2",
                        "Resource": "*",
                        "Action": [
                            "logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"
                        ],
                        "Effect": "Allow"
                    }]
                }
            }]
        }
    },
    "MyFirstLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "myfirstlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MyFirstLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MySecondLambdaFn": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "Code": {
                "S3Bucket": "mysecondlambdafn",
                "S3Key": "lambda_handler.py.zip"
            },
            "Description": "",
            "FunctionName": "MySecondLambdaFn",
            "Handler": "lambda_function.lambda_handler",
            "MemorySize": 512,
            "Role": {
                "Fn::GetAtt": [
                    "LambdaDynamoDBRole",
                    "Arn"
                ]
            },
            "Runtime": "python2.7",
            "Timeout": 3
        },
        "DependsOn": "LambdaDynamoDBRole"
    },
    "MyApi": {
        "Type": "AWS::ApiGateway::RestApi",
        "Properties": {
            "Name": "Project Test API",
            "Description": "Project Test API",
            "FailOnWarnings": true
        }
    },
    "FirstUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "FirstUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "FirstUserPropertyModel",
                "type": "object",
                "properties": {
                    "Email": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "SecondUserPropertyModel": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "SecondUserPropertyModel",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "SecondUserPropertyModel",
                "type": "object",
                "properties": {
                    "Name": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "ErrorCfn": {
        "Type": "AWS::ApiGateway::Model",
        "Properties": {
            "ContentType": "application/json",
            "Name": "ErrorCfn",
            "RestApiId": {
                "Ref": "MyApi"
            },
            "Schema": {
                "$schema": "http://json-schema.org/draft-04/schema#",
                "title": "Error Schema",
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string"
                    }
                }
            }
        }
    },
    "UsersResource": {
        "Type": "AWS::ApiGateway::Resource",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "ParentId": {
                "Fn::GetAtt": ["MyApi", "RootResourceId"]
            },
            "PathPart": "users"
        }
    },
    "UsersPost": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "POST",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MyFirstLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "FirstUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "UsersPut": {
        "Type": "AWS::ApiGateway::Method",
        "Properties": {
            "ResourceId": {
                "Ref": "UsersResource"
            },
            "RestApiId": "MyApi",
            "ApiKeyRequired": true,
            "AuthorizationType": "NONE",
            "HttpMethod": "PUT",
            "Integration": {
                "Type": "AWS_PROXY",
                "IntegrationHttpMethod": "POST",
                "Uri": {
                    "Fn::Join": ["", ["arn:aws:apigateway:", {
                        "Ref": "AWS::Region"
                    }, ":lambda:path/2015-03-31/functions/", {
                        "Fn::GetAtt": ["MySecondLambdaFn", "Arn"]
                    }, "/invocations"]]
                }
            },
            "MethodResponses": [{
                "ResponseModels": {
                    "application/json": {
                        "Ref": "SecondUserPropertyModel"
                    }
                },
                "StatusCode": 200
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 404
            }, {
                "ResponseModels": {
                    "application/json": {
                        "Ref": "ErrorCfn"
                    }
                },
                "StatusCode": 500
            }]
        }
    },
    "RestApiDeployment": {
        "Type": "AWS::ApiGateway::Deployment",
        "Properties": {
            "RestApiId": {
                "Ref": "MyApi"
            },
            "StageName": "Prod"
        },
        "DependsOn": ["UsersPost", "UsersPut"]
    }
},
"Description": "Project description"

}

Body:
I figured that actually it was the RestApiId which needed to be a reference too:

            "RestApiId": {
                "Ref": "MyApi"
            },


问:
Counting same values in multidimensional array with unknown nesting levels
I am trying to count how many (of the same) values show up in a huge list of multidimensional arrays. In the array below (a small snippet of the whole thing) I want to count how many of the "parentID" values are the same. As you can see in this example, there are 2 parent IDs with the same value. I got really close using a For loop, but since each "category detail" array has a random number of sub-arrays, i get undefined offset errors. Here is what i came close with: </p>

```<code>$number_of_same = 0;
for ($row = 0; $row < 5; $row++) {
    if($array['results'][$row]['categoryDetails'][$row]["parentID"]=="xID") {
        $number_of_same++;
    }
}

Array (
    [resultsTotal] => 754
    [results] => Array (
        [0] => Array (
            [blogComments] => 0
            [categoryDetails] => Array (
                [0] => Array (
                    [parentId] => 1697731
                )
            )
        )
        [1] => Array (
            [blogComments] => 0
            [categoryDetails] => Array (
                [0] => Array (
                    [parentId] => 1697731
                )
                [1] => Array (
                    [parentId] => 1702267
                )
            )
        )
    )
)
</code>```

答:
How about array_walk_recursive()?

Input:

```<code>$array=[
    'resultsTotal'=> 754,
    'results'=> [
        [
            'blogComments'=> 0,
            'categoryDetails'=> [
                ['parentId'=> 1697731]
            ]
        ],
        [
            'blogComments'=> 0,
            'categoryDetails'=> [
                [
                    'parentId'=> 1697731
                ],
                [
                    'parentId'=> 1702267
                ]
            ]
        ]
    ]
];
</code>```

Method:

Warning, my first posted array_walk_recursive() code block used == to identify keys called parentId.  This was working okay with the OP's posted sample array. However, when implemented with OP's real array, there were some unexpected key matches where keys where 0 (Buggy Demo).  To remedy this behavior, I simply replaced == with === and the array_walk_recursive() code block was back to business as normal.

```<code>array_walk_recursive($array,function($v,$k)use(&$result){
    if($k==='parentId'){
        if(!isset($result[$v])){$result[$v]=0;}
        ++$result[$v];
    }
}
);
var_export($result);
</code>```

Output:

```<code>array (
  1697731 => 2,
  1702267 => 1,
)
</code>```

Explanation:

The anonymous function call will provide both the keys and values as it traverses all "leaf nodes" (keys that have values versus arrays) of the input array.

The use(&$result) makes $result available outside of the function since there is no return (array_walk_recursive() returns a true|false response).

When a "leaf node" has a key that is parentId, then it first ensures that that key exists in the $result array, and then increments it.

*For speed improvements, you could try to cut down the input string to isolate only portions of your multidimensional array that could include parentId keys.

Here is a non-recursive method:

```<code>foreach(array_column($array['results'],'categoryDetails') as $details){
    foreach($details as $a){
//        if(isset($a['parentId'])){  // only use this if receiving a notice/warning - trying to access non-existent element
            if(!isset($result[$a['parentId']])){$result[$a['parentId']]=0;}
            ++$result[$a['parentId']];
//        }
    }
}
var_export($result);  // same result without any side effects
</code>```

Body:
I am trying to count how many (of the same) values show up in a huge list of multidimensional arrays. In the array below (a small snippet of the whole thing) I want to count how many of the "parentID" values are the same. As you can see in this example, there are 2 parent IDs with the same value. I got really close using a For loop, but since each "category detail" array has a random number of sub-arrays, i get undefined offset errors. Here is what i came close with:

$number_of_same = 0;
for ($row = 0; $row < 5; $row++) {
    if($array['results'][$row]['categoryDetails'][$row]["parentID"]=="xID") {
        $number_of_same++;
    }
}

Array (
    [resultsTotal] => 754
    [results] => Array (
        [0] => Array (
            [blogComments] => 0
            [categoryDetails] => Array (
                [0] => Array (
                    [parentId] => 1697731
                )
            )
        )
        [1] => Array (
            [blogComments] => 0
            [categoryDetails] => Array (
                [0] => Array (
                    [parentId] => 1697731
                )
                [1] => Array (
                    [parentId] => 1702267
                )
            )
        )
    )
)

Body:
How about array_walk_recursive()?

Input:

$array=[
    'resultsTotal'=> 754,
    'results'=> [
        [
            'blogComments'=> 0,
            'categoryDetails'=> [
                ['parentId'=> 1697731]
            ]
        ],
        [
            'blogComments'=> 0,
            'categoryDetails'=> [
                [
                    'parentId'=> 1697731
                ],
                [
                    'parentId'=> 1702267
                ]
            ]
        ]
    ]
];

Method:

Warning, my first posted array_walk_recursive() code block used == to identify keys called parentId.  This was working okay with the OP's posted sample array. However, when implemented with OP's real array, there were some unexpected key matches where keys where 0 (Buggy Demo).  To remedy this behavior, I simply replaced == with === and the array_walk_recursive() code block was back to business as normal.

array_walk_recursive($array,function($v,$k)use(&$result){
    if($k==='parentId'){
        if(!isset($result[$v])){$result[$v]=0;}
        ++$result[$v];
    }
}
);
var_export($result);

Output:

array (
  1697731 => 2,
  1702267 => 1,
)

Explanation:

The anonymous function call will provide both the keys and values as it traverses all "leaf nodes" (keys that have values versus arrays) of the input array.

The use(&$result) makes $result available outside of the function since there is no return (array_walk_recursive() returns a true|false response).

When a "leaf node" has a key that is parentId, then it first ensures that that key exists in the $result array, and then increments it.

*For speed improvements, you could try to cut down the input string to isolate only portions of your multidimensional array that could include parentId keys.

Here is a non-recursive method:

foreach(array_column($array['results'],'categoryDetails') as $details){
    foreach($details as $a){
//        if(isset($a['parentId'])){  // only use this if receiving a notice/warning - trying to access non-existent element
            if(!isset($result[$a['parentId']])){$result[$a['parentId']]=0;}
            ++$result[$a['parentId']];
//        }
    }
}
var_export($result);  // same result without any side effects


问:
JavaScript file inclusion. Should I not link in ?
I'm watching Douglas Crockfords "Theory of the DOM" and he mentioned that the location of my script tags can greatly affect the load time of my applications.  Furthermore, he asserts that a script tag should be included as far towards the bottom of the document body as possible.

Is this accurate?

OR

Is this video out of date? (which he actually sites as a reason he didn't lecture on the DOM sooner).

答:
Well, it's correct. Unless you use something like 'head.js' which loads you javascript files in parallel. Oh, and, some scripts have to be before the content. For example, the html5-shiv script.

http://headjs.com/

Title: JavaScript file inclusion. Should I not link in <head>?


问:
Import free text files
I have been asked to do NLP on a folder of free text documents in SAS. Normally I do this in Python or R and I am not sure how to import he txt files into SAS because there is no structure.

I have thought about using proc import but don't know what I would use as a delimiter. How can one import free text files with no structure into SAS? I supposed once I got in I could use things '%like%' sort of items to pull out what they want.

答:
I would strongly recommend against this. Use the right tool for the right job, in this case it's not SAS.

Ok, that being said some basics you could do:
Import text files and create n grams. Ideally, 1,2 &3 words.

Use PROC FREQ to summarize n-grams.

Find a parts of speech corpus and merge than with the 1 gram to remove useless words.

Calculate length of words and length of sentence to create a document complexity score.

Those are all doable in Base.

Title: Import free text files


问:
How do I find and restore a deleted file in a Git repository?
Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I discover that I need to restore that file after deleting it.

I know I can checkout a file using git checkout <commit> -- filename.txt, but I don't know when that file was deleted.

How do I find the commit that deleted a given filename?

How do I restore that file back into my working copy?

答:
git undelete path/to/file.ext

Put this in your .bash_profile (or other relevant file that loads when you open a command shell):

```<code>git config --global alias.undelete '!sh -c "git checkout $(git rev-list -n 1 HEAD -- $1)^ -- $1" -'
</code>```

Then use:

```<code>git undelete path/to/file.ext
</code>```

This alias first checks to find the last commit where this file existed, and then does a Git checkout of that file path from that last commit where this file existed. Source.

ContentLicense: CC BY-SA 4.0

Body:
git undelete path/to/file.ext

Put this in your .bash_profile (or other relevant file that loads when you open a command shell):

git config --global alias.undelete '!sh -c "git checkout $(git rev-list -n 1 HEAD -- $1)^ -- $1" -'

Then use:

git undelete path/to/file.ext

This alias first checks to find the last commit where this file existed, and then does a Git checkout of that file path from that last commit where this file existed. Source.


问:
Debugging dump of 32-bit process captured on 64-bit machine
I recently received a 64-bit crash dump from a customer.

Our processes are all 32-bit, but the customer's machine is running x64 Server 2008.

Visual Studio (both 2008 and 2010 Express) is telling me that I have to use the 64-bit version of MSVSMON.EXE, which I can't because I don't have a 64-bit machine.

I'm pretty sure there's a way to do this in WinDbg, but I find WinDbg to be hostile.

Is there any way to debug a 64-bit dump on a 32-bit machine, preferably using Visual Studio?

答: I worked around the problem by using 32 bit task manager (C:\Windows\SysWOW64\Taskmgr.exe) to capture the dump.


问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
One can always (try to) be clever, but abstraction doesn't always pay off when the code becomes longer and not more reusable. KISS.

But if you want to go for it, I'd choose

```<code>function addTo(property, x, operand) { // "x" for lack of a more meaningful name
    const shouldAdd = $scope[property] === null || $scope[x] === null;
    if (shouldAdd)
        $scope[property] += operand; // assuming "operand" is a number
// or   $scope[property] = ($scope[property] || "") + operand; // when it's a string
    return shouldAdd;
}
$scope.setOperand = function (operandEntered) {
    addTo("leftOperand", "operator", operandEntered) || addTo("rightOperand", "answer", operandEntered);
 };
</code>```

If you care more about conciseness than about readability, you can even shorten the helper to

```<code>function addTo(property, x, operand) {
    return ($scope[property] === null || $scope[x] === null) && (($scope[property] += operand), true);
}
</code>```

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
One can always (try to) be clever, but abstraction doesn't always pay off when the code becomes longer and not more reusable. KISS.

But if you want to go for it, I'd choose

function addTo(property, x, operand) { // "x" for lack of a more meaningful name
    const shouldAdd = $scope[property] === null || $scope[x] === null;
    if (shouldAdd)
        $scope[property] += operand; // assuming "operand" is a number
// or   $scope[property] = ($scope[property] || "") + operand; // when it's a string
    return shouldAdd;
}
$scope.setOperand = function (operandEntered) {
    addTo("leftOperand", "operator", operandEntered) || addTo("rightOperand", "answer", operandEntered);
 };

If you care more about conciseness than about readability, you can even shorten the helper to

function addTo(property, x, operand) {
    return ($scope[property] === null || $scope[x] === null) && (($scope[property] += operand), true);
}


问:
Can't seem to find why my Prime Number Program doesn't work properly after reprompt for number
Im having trouble with my prime number section part of my program. When I compile and run my program, the prime numbers print out fine for the first number, but when reprompted for another number. It usually prints out either no numbers or it cuts off the prime numbers from a certain point down. Im new to coding and this forum so I'm sorry about any formatting issues in my post.</p>

```<code>#include <stdio.h>
#include <math.h>
int main(void)
{
    int number, n=1;
    long factorial=1;
    int a=1, b=0,c;
    int q=2, r=2, w=0;
    int prime, count;

    printf("Enter a Number:\n");
    scanf("\n%d", &number);
    while(number!=1000)
    {
        if(number<1||number>1000)
            printf("Input is Invalid\n");
        else
       {
            if(number==1000)
                printf("Goodbye\n");
            if(number<15)
            {
            factorial=number;
            n=number-1;
            while(n>=1)
            {
            factorial=factorial*n;
            n--;

            }
            printf("The Factorial of %d is: %ld\n", number,  factorial);
        }
        c=a+b;
        printf("Fibonacci Sequence up to %d\n ", number);
        while(c<number&&a+b<number)
            {
                 c=a+b;
                 a=b;
                 b=c;
                 n++;
                 printf("%d\t", c);

                 count=n;
                 if(count%10==0)
                    printf("\n");

            }
            printf("\nTotal:%d\n", n);
            printf("\nPrime numbers up to %d:\n", number);

            while(q<=number)
            {
                prime=0;

                for(r=2;r<q;++r)
                {
                if(q%r==0)
                {
                prime=1;
                }
                }
                if(prime==0)
                {
                printf("%d\t", r);
                w++;
                }
                q++;
                }
                count=r;
                if(count%10==0)
                    printf("\n");
                    printf("\nTotal:%d\n", w);
                }
                printf("\nEnter a Number:\n");
                scanf("\n%d", &number);
                        a=1;
                b=0;
            }
return(0);
}
</code>```

答:
You are never resetting your variable q, which is the control variable for your prime number loop. It is best practice to create all of your variables which need to be reset inside your loop. Either reset q at the beginning/end of your loop, or create q at the beginning of your outer loop and set it to 2.

Like this:

```<code>while(number != 1000) {
  int q = 2;
  //other assignments below which need to be reset
  ...
  //all other code below
  ...
}
</code>```

Body:
Im having trouble with my prime number section part of my program. When I compile and run my program, the prime numbers print out fine for the first number, but when reprompted for another number. It usually prints out either no numbers or it cuts off the prime numbers from a certain point down. Im new to coding and this forum so I'm sorry about any formatting issues in my post.

#include <stdio.h>
#include <math.h>
int main(void)
{
    int number, n=1;
    long factorial=1;
    int a=1, b=0,c;
    int q=2, r=2, w=0;
    int prime, count;

    printf("Enter a Number:\n");
    scanf("\n%d", &number);
    while(number!=1000)
    {
        if(number<1||number>1000)
            printf("Input is Invalid\n");
        else
       {
            if(number==1000)
                printf("Goodbye\n");
            if(number<15)
            {
            factorial=number;
            n=number-1;
            while(n>=1)
            {
            factorial=factorial*n;
            n--;

            }
            printf("The Factorial of %d is: %ld\n", number,  factorial);
        }
        c=a+b;
        printf("Fibonacci Sequence up to %d\n ", number);
        while(c<number&&a+b<number)
            {
                 c=a+b;
                 a=b;
                 b=c;
                 n++;
                 printf("%d\t", c);

                 count=n;
                 if(count%10==0)
                    printf("\n");

            }
            printf("\nTotal:%d\n", n);
            printf("\nPrime numbers up to %d:\n", number);

            while(q<=number)
            {
                prime=0;

                for(r=2;r<q;++r)
                {
                if(q%r==0)
                {
                prime=1;
                }
                }
                if(prime==0)
                {
                printf("%d\t", r);
                w++;
                }
                q++;
                }
                count=r;
                if(count%10==0)
                    printf("\n");
                    printf("\nTotal:%d\n", w);
                }
                printf("\nEnter a Number:\n");
                scanf("\n%d", &number);
                        a=1;
                b=0;
            }
return(0);
}

Body:
You are never resetting your variable q, which is the control variable for your prime number loop. It is best practice to create all of your variables which need to be reset inside your loop. Either reset q at the beginning/end of your loop, or create q at the beginning of your outer loop and set it to 2.

Like this:

while(number != 1000) {
  int q = 2;
  //other assignments below which need to be reset
  ...
  //all other code below
  ...
}


问:
FieldInfo.GetValue return null for a private member while debugger indicates field is non null?
In C# / .NET 4.0 I am trying to retrieve a field value through reflection with:

```<code>var bar = foo.GetType()
  .GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
  .GetValue(foo)
</code>```

I am a bit puzzled by the situation. The value returned is null, and yet, the field (when observed through the debugger) is not null. Even more puzzling, the code here above works for the other object properties.

The only odd aspect are the two flags IsSecurityCritical and IsSecuritySafeCritical that are true, but I am not even sure it's actually relevant to the situation.

I am ending up in such a situation with a small HttpModule.

```<code>public class MyModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += BeginRequest;
    }

    void BeginRequest(object sender, EventArgs e)
    {
         var app = (HttpApplication)sender;

         var rawContent = typeof(HttpRequest)
                .GetField("_rawContent", BindingFlags.Instance | BindingFlags.NonPublic)
                .GetValue(app.Request);

         // at this point 'rawContent' is null, while debugger indicates it is not.
    }
}
</code>```

Any suggestion that would explain such a behavior?

答:
This is caused by the security model in .net 4.0, as you're running an asp.net application, which is probably not running in full trust. As the field is security critical, you can't access it through reflection.

You can read a bit on the msdn about: Security Considerations for Reflection

Body:
In C# / .NET 4.0 I am trying to retrieve a field value through reflection with:

var bar = foo.GetType()
  .GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
  .GetValue(foo)

I am a bit puzzled by the situation. The value returned is null, and yet, the field (when observed through the debugger) is not null. Even more puzzling, the code here above works for the other object properties.

The only odd aspect are the two flags IsSecurityCritical and IsSecuritySafeCritical that are true, but I am not even sure it's actually relevant to the situation.

I am ending up in such a situation with a small HttpModule.

public class MyModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += BeginRequest;
    }

    void BeginRequest(object sender, EventArgs e)
    {
         var app = (HttpApplication)sender;

         var rawContent = typeof(HttpRequest)
                .GetField("_rawContent", BindingFlags.Instance | BindingFlags.NonPublic)
                .GetValue(app.Request);

         // at this point 'rawContent' is null, while debugger indicates it is not.
    }
}

Any suggestion that would explain such a behavior?


问:
Scripting for file management with a very large amount of files
I have a three OSX machine setup that was using syncthing to keep shared drives synchronized remotely.  Someone made some mistakes and a lot of files ended up getting renamed.

So all throughout this drive I have situations where there's a file of size 0KB named,for example, file.jpg and another file with real size named
file.sync-confilct201705-4528.jpg.  I need to search the entire drive recursively and while I find a file with the sync-conflict string in it, check to see if there is the same file without the 'sync-conflict' string along with a size of 0KB.  If there is, I need to rename the sync-conflict file to overwrite the 0KB file.

I have considered tackling this with a bash script or a Perl script.  Using bash I think just using the 'find' command with -regex would get me started but I don't really know how to process the results and run the next find test.  I am studying and working on it.

Same problem with Perl. I can get through the first step using File::Find:find and select what I need using regex to filter out the files, but there again I am stuck getting to the next step, which would be finding the original file in the same directory and performing the necessary file move function.

In both of these cases I am willing to put in the time to figure it out, but I wonder what the caveats will be?  Can both of these scenarios handle recursing a large number of files without exception?  Is there perhaps a better approach anyone can recommend?

答:
Create a function to fix the name:

```<code>$ function fixname() { file="$1"; newname=$( echo "$file" | sed "s/sync-conflict.*\.jpg$/.jpg/" );  if [ -f "$newname" -a ! -s "$newname" ]; then mv "$file" "$newname"; fi; }
</code>```

Or, spread out a bit:

```<code>function fixname() {
    file="$1"
    newname=$( echo "$file" | sed "s/sync-conflict.*\.jpg$/.jpg/" )
    # If empty file exists
    if [ -f "$newname" -a ! -s "$newname" ]; then
        mv "$file" "$newname"
    fi
}
</code>```

Export the function:

```<code>$ export -f fixname
</code>```

Run find to execute the function:

```<code>$ find . -type f -name \*sync-conflict\*.jpg -exec bash -c 'fixname {}' bash \;
</code>```

Caveat: It will not work with spaces or funky characters in the filenames.

Body:
Create a function to fix the name:

$ function fixname() { file="$1"; newname=$( echo "$file" | sed "s/sync-conflict.*\.jpg$/.jpg/" );  if [ -f "$newname" -a ! -s "$newname" ]; then mv "$file" "$newname"; fi; }

Or, spread out a bit:

function fixname() {
    file="$1"
    newname=$( echo "$file" | sed "s/sync-conflict.*\.jpg$/.jpg/" )
    # If empty file exists
    if [ -f "$newname" -a ! -s "$newname" ]; then
        mv "$file" "$newname"
    fi
}

Export the function:

$ export -f fixname

Run find to execute the function:

$ find . -type f -name \*sync-conflict\*.jpg -exec bash -c 'fixname {}' bash \;

Caveat: It will not work with spaces or funky characters in the filenames.


问:
Laravel update multiple database rows with Eloquent
I want to update the products leased count when a product is rented to a customer.
The owner of the website can rent multiple things. I do this by cloning with Ajax.

Now, when someone has rented like 2 chairs and 1 table, i want to update the products_leased row for both products. How would i do that?

The error i get:

```<code>`SQLSTATE[01000]: Warning: 1265 Data truncated for column 'product_leased' at row 1 (SQL: update `products` set `product_leased` = 3 5, `updated_at` = 2017-06-07 19:57:03 where `id` = 1)`
</code>```

My controller:

```<code>public function create_order($id) {

    $customer = Customer::find($id);
    $pr = Product::get();

    $rent_from = Request::input('rent_from');
    $rent_till = Request::input('rent_till');
    $productArray = Request::get('product_name');
    $productCountArray = Request::get('product_count');

    $rentProduct = new cRent;
    $rentProduct->customer_id = $customer->id;
    $rentProduct->rent_from = $rent_from;
    $rentProduct->rent_till = $rent_till;
    $rentProduct->rented_products = implode(', ', $productArray);
    $rentProduct->rented_products_count = implode(', ', $productCountArray);

    $rentProduct->save();

    $pru = Product::find($id);

    $pru->product_leased = implode(' ', $productCountArray);
    $pru->update();

    return back();

}
</code>```

The code above works only when one product has been rented. Not when i rent 2 products.

Thanks in advance.

答:
```<code>$rentProduct = new cRent;
</code>```

the code above indicates only one instance of your cRent off-course if you want have another transaction with the database with a different values or data another instance is needed

I think what you want is something like this

```<code>public function create_order($id) {

    $customer = Customer::find($id);
    $pr = Product::get();

    $rent_from = Request::input('rent_from');
    $rent_till = Request::input('rent_till');
    $productArray = Request::get('product_name');
    $productCountArray = Request::get('product_count');

    foreache($productArray as $prod){

        $rentProduct = new cRent;
        $rentProduct->customer_id = $customer->id;
        $rentProduct->rent_from = $rent_from;
        $rentProduct->rent_till = $rent_till;
        $rentProduct->rented_products = $prod
        $rentProduct->rented_products_count = //not sure in this line

        $rentProduct->save();
    }

    $pru = Product::find($id);

    $pru->product_leased = implode(' ', $productCountArray);
    $pru->update();

    return back();

}
</code>```

Body:
I want to update the products leased count when a product is rented to a customer.
The owner of the website can rent multiple things. I do this by cloning with Ajax.

Now, when someone has rented like 2 chairs and 1 table, i want to update the products_leased row for both products. How would i do that?

The error i get:

`SQLSTATE[01000]: Warning: 1265 Data truncated for column 'product_leased' at row 1 (SQL: update `products` set `product_leased` = 3 5, `updated_at` = 2017-06-07 19:57:03 where `id` = 1)`

My controller:

public function create_order($id) {

    $customer = Customer::find($id);
    $pr = Product::get();

    $rent_from = Request::input('rent_from');
    $rent_till = Request::input('rent_till');
    $productArray = Request::get('product_name');
    $productCountArray = Request::get('product_count');

    $rentProduct = new cRent;
    $rentProduct->customer_id = $customer->id;
    $rentProduct->rent_from = $rent_from;
    $rentProduct->rent_till = $rent_till;
    $rentProduct->rented_products = implode(', ', $productArray);
    $rentProduct->rented_products_count = implode(', ', $productCountArray);

    $rentProduct->save();

    $pru = Product::find($id);

    $pru->product_leased = implode(' ', $productCountArray);
    $pru->update();

    return back();

}

The code above works only when one product has been rented. Not when i rent 2 products.

Thanks in advance.

Body:
$rentProduct = new cRent;

the code above indicates only one instance of your cRent off-course if you want have another transaction with the database with a different values or data another instance is needed

I think what you want is something like this

public function create_order($id) {

    $customer = Customer::find($id);
    $pr = Product::get();

    $rent_from = Request::input('rent_from');
    $rent_till = Request::input('rent_till');
    $productArray = Request::get('product_name');
    $productCountArray = Request::get('product_count');

    foreache($productArray as $prod){

        $rentProduct = new cRent;
        $rentProduct->customer_id = $customer->id;
        $rentProduct->rent_from = $rent_from;
        $rentProduct->rent_till = $rent_till;
        $rentProduct->rented_products = $prod
        $rentProduct->rented_products_count = //not sure in this line

        $rentProduct->save();
    }

    $pru = Product::find($id);

    $pru->product_leased = implode(' ', $productCountArray);
    $pru->update();

    return back();

}


问:
Missing Collections in Local Mongo DB in Meteor App
My Meteor App local mongoDB is missing 2 collections when compared to my live DB on MLab

Already double checked my connection string and am connected to same DB.

This issue just recently started after pulled a new remote branch but nothing was changed related to the DB.

I don't know what else to try.

What other information can I provide to get a good answer here?

答:
I do not know what was causing the issue but here's what I did to resolve it.

Dump my live database to a local copy:
mongodump --host ds15XXXX-a0.mlab.com --db   --port 5XXXXX --username  --password

Import to local DB:
mongorestore --drop --host localhost --port 3001 --db meteor ./dump/


问:
Failing to open csv file
My current python script is like this:

```<code>import csv

with open ('2017_IL_sales.csv','r') as infile:
    reader=csv.reader(infile)
    with open('2017_IL_sales_report.csv') as outfile:
        writer=csv.writer(outfile)
        dict_report={rows[1]:rows[2] for rows in reader}

print dict_report
</code>```

In brief, I want to open a csv file called 2017_IL_sales then create a dictionary for two columns inside. But with whatever reason, everytime I run the code via IDLE it told me this IOError: [Errno 2] No such file or directory: '2017_IL_sales.csv'. Anyone knows the reason?

答: Make sure that the script you are running is in the same folder as the file you are trying to read. If that is not possible, make sure to specify the correct file path.</p>

Title: Failing to open csv file

Body:
My current python script is like this:

import csv

with open ('2017_IL_sales.csv','r') as infile:
    reader=csv.reader(infile)
    with open('2017_IL_sales_report.csv') as outfile:
        writer=csv.writer(outfile)
        dict_report={rows[1]:rows[2] for rows in reader}

print dict_report

In brief, I want to open a csv file called 2017_IL_sales then create a dictionary for two columns inside. But with whatever reason, everytime I run the code via IDLE it told me this IOError: [Errno 2] No such file or directory: '2017_IL_sales.csv'. Anyone knows the reason?