答:
Your min > input is always going to be false if min is None, hence why it never gets set.

Also you don't want the elif.  The first number is both the min and the max.

Fixed:

```<code>min = None
max = None
while True:
    input = raw_input("Please enter number: ")
    if input == "done":
        break
    else:
        try:
            input = float(input)
        except:
            continue

    if max is None or max < input:
        max = input
    if min is None or min > input:
        min = input

    print min
    print max
</code>```

Good luck!

Title: Conditional won't execute properly

Body:
I wonder if you could help me with the code below:

min = None
max = None
while True:
    input = raw_input("Please enter number: ")
    if input == "done":
        break
    else:
        try:
            input = float(input)
        except:
            continue

    if max < input:
        max = input
    elif min > input:
        min = input

    print min
    print max

It looks right to me, but the elif statement which gives a value to min always prints None. Could you please explain why?

Body:
Your min > input is always going to be false if min is None, hence why it never gets set.

Also you don't want the elif.  The first number is both the min and the max.

Fixed:

min = None
max = None
while True:
    input = raw_input("Please enter number: ")
    if input == "done":
        break
    else:
        try:
            input = float(input)
        except:
            continue

    if max is None or max < input:
        max = input
    if min is None or min > input:
        min = input

    print min
    print max

Good luck!


来源: stackexchange

问:
Create ETL process in SSIS
Suppose I've data from different sources. For example, MS SQL and Oracle. And these data are connected. And data from different sources should be loaded into 1 table. What are the ways in the SSIS to do this?</p>

答:
You can have multiple solutions based on requirements and table structure.

1.Relational tables - Merge join

2.Merge common data set - Union All

You may study and implement various Data Flow Transformations.

ContentLicense: CC BY-SA 3.0

Title: Create ETL process in SSIS


问:
Error in batch file due to space
I am having trouble with a seemingly simple script I have which essentially copies an item from the user's PC and places it on another computer; however, the destination file path contains a space in it. I have tried multiple methods of correcting this issue (some I don't completely understand) from using double quotation marks around the string to forcing it to run powershell.

To give a very brief precursor to this situation, I must add that I initially created this script using Powershell on Windows 10 and I should also add that it works completely fine in Powershell, just not as a .bat. I understand there may be some differences in the languages or what is interpreted through the programs.

Here is the string in the question:

```<code>Copy-Item $ENV:USERPROFILE\Desktop\VAST.accdb -destination "\\PRECDP19670\C$\Users\WAKE\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Force -PassThru -Verbose
</code>```

The destination contains the space in the filepath.

Any help is appreciated!

答:
As Bill mentioned, your BAT file needs to call PowerShell as an executable. </p>

```<code>PowerShell.exe -command 'Copy-Item $ENV:USERPROFILE\Desktop\VAST.accdb -destination "\\PRECDP19670\C$\Users\WAKE\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Force -PassThru -Verbose
</code>```

Title: Error in batch file due to space

Body:
I am having trouble with a seemingly simple script I have which essentially copies an item from the user's PC and places it on another computer; however, the destination file path contains a space in it. I have tried multiple methods of correcting this issue (some I don't completely understand) from using double quotation marks around the string to forcing it to run powershell.

To give a very brief precursor to this situation, I must add that I initially created this script using Powershell on Windows 10 and I should also add that it works completely fine in Powershell, just not as a .bat. I understand there may be some differences in the languages or what is interpreted through the programs.

Here is the string in the question:

Copy-Item $ENV:USERPROFILE\Desktop\VAST.accdb -destination "\\PRECDP19670\C$\Users\WAKE\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Force -PassThru -Verbose

The destination contains the space in the filepath.

Any help is appreciated!

Body:
As Bill mentioned, your BAT file needs to call PowerShell as an executable.

PowerShell.exe -command 'Copy-Item $ENV:USERPROFILE\Desktop\VAST.accdb -destination "\\PRECDP19670\C$\Users\WAKE\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Force -PassThru -Verbose


问:
Viewing changes to deleted files in git
Let's say that when I branch off from master, there's a file colors.txt on the master branch of my repo with these contents:

```<code>red
green
blue
yellow
</code>```

I then branch off into my-branch, in which I make the following changes:

Delete colors.txt

Add red.txt with these contents:

```<code>red
</code>```

Add green.txt with these contents:

```<code>green
</code>```

Add blue.txt with these contents:

```<code>blue
</code>```

Add yellow.txt with these contents:

```<code>yellow
</code>```

Now, there have been some changes on master that I need, so I want to merge. However, someone has also changed colors.txt to:

```<code>red
green
blue
yellow
orange
purple
</code>```

During my merge, the only information I get is that I deleted the file colors.txt, so how can I see the changes that have been to the file on master so I can appropriately resolve the conflict (in this case, by adding the files orange.txt and purple.txt)?

答: Tricky scenario, right? I think the best you can try to do is find out "when" color.txt was deleted. If you weren't merging, I'd say: use a bisect to find out when the file disappeared so you can see what happened but you are merging so that's no good. git blame --reverse can help somewhat by telling you when was the last time the file was present on your working tree. git log --name-status -- <file-path> can also help you see when the file disappeared (and why, through a nicely written revision comment, right?). I would tell you to give difflame a testdrive (A tool I worked on that by blending blame and diff output would be able to tell you the exact revision where the lines were deleted) but I think that because the file was deleted altogether, it will break.. not sure though. Here's the link just in case: https://github.com/eantoranz/difflame. Now... if you are able to find out on which revision the file was deleted, you might find out why it was deleted and you should figure out that you have to create a file for the new color that was added to color.txt while keeping color.txt deleted so that the merge is "complete".

Title: Viewing changes to deleted files in git

Body:
Let's say that when I branch off from master, there's a file colors.txt on the master branch of my repo with these contents:

red
green
blue
yellow

I then branch off into my-branch, in which I make the following changes:

Delete colors.txt

Add red.txt with these contents:

red

Add green.txt with these contents:

green

Add blue.txt with these contents:

blue

Add yellow.txt with these contents:

yellow

Now, there have been some changes on master that I need, so I want to merge. However, someone has also changed colors.txt to:

red
green
blue
yellow
orange
purple

During my merge, the only information I get is that I deleted the file colors.txt, so how can I see the changes that have been to the file on master so I can appropriately resolve the conflict (in this case, by adding the files orange.txt and purple.txt)?


问:
PayPal REST API Create Invoice with Template
Has anybody ever successfully created a PayPal invoice with a specific chosen template?
I can't seem to get it to work.

Have tried specifying the template_id in the call, and have also tried setting the desired template as the default.  In both cases, the API response contains the chosen template ID, but when the invoice is sent, it does not use the chosen template (can tell because there's no logo).

This the the API call:

```<code>curl -v -X POST https://api.paypal.com/v1/invoicing/invoices/ \
-H "Content-Type:application/json" \
-H "Authorization: Bearer <Access-Token>" \
-d '{
  "template_id": "TEMP-66B140465N059453G",
  "items": [
  {
    "name": "Part E",
    "quantity": 2,
    "unit_price": {
    "currency": "USD",
    "value": "10.15"
    }
  }
  ],
  "shipping_info": {
  "first_name": "John",
  "last_name": "Doe",
  "business_name": "Not applicable",
  "phone": {
    "country_code": "001",
    "national_number": "5039871234"
  },
  "address": {
    "line1": "1234 Broad St.",
    "city": "Portland",
    "state": "OR",
    "postal_code": "97216",
    "country_code": "US"
  }
  },
  "shipping_cost": {
  "amount": {
    "currency": "USD",
    "value": "15.01"
    }
  },
  "allow_tip": false
}'
</code>```

This is the response:

```<code>"id":<Invoice ID>,
"number":"0004",
"template_id":"TEMP-66B140465N059453G",
"status":"DRAFT",
"merchant_info":{},
"shipping_info":{"first_name":"John","last_name":"Doe","business_name":"Not applicable","phone":{"country_code":"001","national_number":"5039871234"},"address":{"line1":"1234 Broad St.","city":"Portland","state":"OR","postal_code":"97216","country_code":"US"}},
"items":[{"name":"Part E","quantity":2.0,"unit_price":{"currency":"USD","value":"10.15"}}],
"invoice_date":"2017-05-30 PDT",
"shipping_cost":{"amount":{"currency":"USD","value":"15.01"}},
"tax_calculated_after_discount":false,
"tax_inclusive":false,
"total_amount":{"currency":"USD","value":"35.31"},
"metadata":{"created_date":"2017-05-30 13:35:39 PDT"},
"allow_tip":false
</code>```

If anybody has any ideas, would be happy to hear them.

Thanks.

答:
We are correcting the instructions for how you use a Template ID.  Sorry for the confusion.

When you are doing a basic integration to create and send an invoice, you don't need to use Template at all.

Template is useful if you are creating a full invoicing app where you want the end user (invoicer) to be able to create templates and access them when creating invoices. See the PayPal.com website for how templates are used.

Regards,
Kristen

Body:
Has anybody ever successfully created a PayPal invoice with a specific chosen template?
I can't seem to get it to work.

Have tried specifying the template_id in the call, and have also tried setting the desired template as the default.  In both cases, the API response contains the chosen template ID, but when the invoice is sent, it does not use the chosen template (can tell because there's no logo).

This the the API call:

curl -v -X POST https://api.paypal.com/v1/invoicing/invoices/ \
-H "Content-Type:application/json" \
-H "Authorization: Bearer <Access-Token>" \
-d '{
  "template_id": "TEMP-66B140465N059453G",
  "items": [
  {
    "name": "Part E",
    "quantity": 2,
    "unit_price": {
    "currency": "USD",
    "value": "10.15"
    }
  }
  ],
  "shipping_info": {
  "first_name": "John",
  "last_name": "Doe",
  "business_name": "Not applicable",
  "phone": {
    "country_code": "001",
    "national_number": "5039871234"
  },
  "address": {
    "line1": "1234 Broad St.",
    "city": "Portland",
    "state": "OR",
    "postal_code": "97216",
    "country_code": "US"
  }
  },
  "shipping_cost": {
  "amount": {
    "currency": "USD",
    "value": "15.01"
    }
  },
  "allow_tip": false
}'

This is the response:

"id":<Invoice ID>,
"number":"0004",
"template_id":"TEMP-66B140465N059453G",
"status":"DRAFT",
"merchant_info":{},
"shipping_info":{"first_name":"John","last_name":"Doe","business_name":"Not applicable","phone":{"country_code":"001","national_number":"5039871234"},"address":{"line1":"1234 Broad St.","city":"Portland","state":"OR","postal_code":"97216","country_code":"US"}},
"items":[{"name":"Part E","quantity":2.0,"unit_price":{"currency":"USD","value":"10.15"}}],
"invoice_date":"2017-05-30 PDT",
"shipping_cost":{"amount":{"currency":"USD","value":"15.01"}},
"tax_calculated_after_discount":false,
"tax_inclusive":false,
"total_amount":{"currency":"USD","value":"35.31"},
"metadata":{"created_date":"2017-05-30 13:35:39 PDT"},
"allow_tip":false

If anybody has any ideas, would be happy to hear them.

Thanks.


问:
Properly specifying model input sizes when instantiating and fitting simple keras model?
We are just getting started with keras in class and I seem to be stuck on part of my first assignment. To start we are to build a simple perceptron within keras then train and test it against various truth tables.

I have started with the simple Not relationship. For the input and output I have generated two (2, 1) shaped matrices in numpy representing the Not relationship. I then programmatically generate the model based on the shapes of the input and output (for use later in the assignment). Though when it comes time to fit the model the input dimensions of the data are wrong for a reason I do not understand. keras produces the error

ValueError: Error when checking model input: expected dense_1_input to have 3 dimensions, but got array with shape (2, 1)

Here is a SSCCE that reproduces the issue (Obviously you need keras and numpy to run it)

```<code>import keras
import numpy as np

# Shape(s): (2, 1)
xONE = np.mat([[0], [1]])
yNOT = np.mat([[1], [0]])

def generateModel(xShape, yShape):
    model = keras.models.Sequential()
    model.add(keras.layers.Dense(yShape[0], input_shape = xShape))
    model.add(keras.layers.Activation('hard_sigmoid'))
    model.summary()
    return model

model = generateModel(xONE.shape, yNOT.shape)
model.compile(
    optimizer = 'adam',
    loss = 'binary_crossentropy',
    metrics = ['accuracy'])
model.fit(xONE, yNOT, epochs = 200, batch_size = 2, verbose = 1)
score = model.evaluate(xONE, yNOT, batch_size = 2)

print('Test loss:', score[0])
print('Test accuracy:', score[1])
</code>```

My only idea is that model.fit is expecting a bias term to be present in the input data as a result of the use of the use_bias = True param during the model generation? But this would just mean that it expects a input of shape (3, 1) not a 3-dimensional input...

答:
You need to change the row

```<code>model.add(keras.layers.Dense(yShape[0], input_shape = xShape))
</code>```

into:

```<code>model.add(keras.layers.Dense(yShape[1], input_dim = xShape[1]))
</code>```

The reason is that the dimension that required is the dimension of every data sample. When you used yShape[0] you passed instead the total number of samples. Similar issue happened with input_shape = xShape.

Body:
We are just getting started with keras in class and I seem to be stuck on part of my first assignment. To start we are to build a simple perceptron within keras then train and test it against various truth tables.

I have started with the simple Not relationship. For the input and output I have generated two (2, 1) shaped matrices in numpy representing the Not relationship. I then programmatically generate the model based on the shapes of the input and output (for use later in the assignment). Though when it comes time to fit the model the input dimensions of the data are wrong for a reason I do not understand. keras produces the error

ValueError: Error when checking model input: expected dense_1_input to have 3 dimensions, but got array with shape (2, 1)

Here is a SSCCE that reproduces the issue (Obviously you need keras and numpy to run it)

import keras
import numpy as np

# Shape(s): (2, 1)
xONE = np.mat([[0], [1]])
yNOT = np.mat([[1], [0]])

def generateModel(xShape, yShape):
    model = keras.models.Sequential()
    model.add(keras.layers.Dense(yShape[0], input_shape = xShape))
    model.add(keras.layers.Activation('hard_sigmoid'))
    model.summary()
    return model

model = generateModel(xONE.shape, yNOT.shape)
model.compile(
    optimizer = 'adam',
    loss = 'binary_crossentropy',
    metrics = ['accuracy'])
model.fit(xONE, yNOT, epochs = 200, batch_size = 2, verbose = 1)
score = model.evaluate(xONE, yNOT, batch_size = 2)

print('Test loss:', score[0])
print('Test accuracy:', score[1])

My only idea is that model.fit is expecting a bias term to be present in the input data as a result of the use of the use_bias = True param during the model generation? But this would just mean that it expects a input of shape (3, 1) not a 3-dimensional input...

Body:
You need to change the row

model.add(keras.layers.Dense(yShape[0], input_shape = xShape))

into:

model.add(keras.layers.Dense(yShape[1], input_dim = xShape[1]))

The reason is that the dimension that required is the dimension of every data sample. When you used yShape[0] you passed instead the total number of samples. Similar issue happened with input_shape = xShape.


问:
Access to nestes FormArray
```<code>export class RegulationComponent implements OnInit {
    regulation: Regulation;
    isCreateNew = false;
    regulationForm: FormGroup;
    itemArray: FormArray;
    paragraphArray: FormArray;

 constructor(private route: ActivatedRoute, private fb: FormBuilder) {
  this.regulationForm = new FormGroup({
  head: new FormControl(''),
  title: new FormControl(''),
  info: new FormControl(''),
  createdDate: new FormControl(''),
  tableOfContentTitle: new FormControl(''),
  items: new FormArray([
    new FormGroup({
      number: new FormControl(''),
      text: new FormControl(''),
      title: new FormControl(''),
      paragraphs: new FormArray([
        new FormGroup({
          number: new FormControl(''),
          text: new FormControl(''),
          title: new FormControl('')
        })
      ])
    })
  ]),
});
this.itemArray = <FormArray>this.regulationForm.controls['items'];
}
</code>```

This is my form and my questions is: how can i access the "paragraph" array in the "items" array?

Something like

```<code>this.itemArray = <FormArray>this.regulationForm.controls['items'];
</code>```

only for the "paragraph" array.

Thanks for your help!

答:
You could try:</p>

```<code><FormArray>this.regulationForm.get('items.paragraphs');
</code>```

Title: Access to nestes FormArray

Body:
export class RegulationComponent implements OnInit {
    regulation: Regulation;
    isCreateNew = false;
    regulationForm: FormGroup;
    itemArray: FormArray;
    paragraphArray: FormArray;

 constructor(private route: ActivatedRoute, private fb: FormBuilder) {
  this.regulationForm = new FormGroup({
  head: new FormControl(''),
  title: new FormControl(''),
  info: new FormControl(''),
  createdDate: new FormControl(''),
  tableOfContentTitle: new FormControl(''),
  items: new FormArray([
    new FormGroup({
      number: new FormControl(''),
      text: new FormControl(''),
      title: new FormControl(''),
      paragraphs: new FormArray([
        new FormGroup({
          number: new FormControl(''),
          text: new FormControl(''),
          title: new FormControl('')
        })
      ])
    })
  ]),
});
this.itemArray = <FormArray>this.regulationForm.controls['items'];
}

This is my form and my questions is: how can i access the "paragraph" array in the "items" array?

Something like

this.itemArray = <FormArray>this.regulationForm.controls['items'];

only for the "paragraph" array.

Thanks for your help!

Body:
You could try:

<FormArray>this.regulationForm.get('items.paragraphs');


问:
How to scrape AJAX based websites by using Scrapy and Splash?
I want to make a general scraper which can crawl and scrape all data from any type of website including AJAX websites. I have extensively searched the internet but could not find any proper link which can explain me how Scrapy and Splash together can scrape AJAX websites(which includes pagination,form data and clicking on button before page is displayed). Every link I have referred tells me that Javascript websites can be rendered using Splash but there's no good tutorial/explanation about using Splash to render JS websites. Please don't give me solutions related to using browsers(I want to do everything programmatically,headless browser suggestions are welcome..but I want to use Splash).

class FlipSpider(CrawlSpider):
    name = "flip"
    allowed_domains = ["www.amazon.com"]

    start_urls = ['https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=mobile']

    rules = (Rule(LinkExtractor(), callback='lol', follow=True),

    def parse_start_url(self,response):
       yield scrapy.Request(response.url,
                            self.lol,
                            meta={'splash':{'endpoint':'render.html','args':{'wait': 5,'iframes':1,}}})

    def lol(self, response):
       """
       Some code
       """
```

答:
The problem with Splash and pagination is following:

I wasn't able to product a Lua script that delivers a new webpage (after click on pagination link) that is in format of response. and not pure HTML.

So, my solution is following - to click the link and extract that new generated url and direct a crawler to this new url.

So, I on the page that has pagination link I execute

yield SplashRequest(url=response.url, callback=self.get_url, endpoint="execute", args={'lua_source': script})
```

<p>with following Lua script</p>

<pre class="lang-python prettyprint-override"><code>def parse_categories(self, response):
    script = """
             function main(splash)
                 assert(splash:go(splash.args.url))
                 splash:wait(1)
                 splash:runjs('document.querySelectorAll(".next-page")[0].click()')
                 splash:wait(1)
                 return splash:url()
             end
             """
</code>```

and the get_url function

def get_url(self,response):
    yield SplashRequest(url=response.body_as_unicode(), callback=self.parse_categories)
```

This way I was able to loop my queries.

Same way if you don't expect new URL your Lua script can just produce pure html that you have to work our with regex (that is bad) - but this is the best I was able to do.

ContentLicense: CC BY-SA 4.0

Body:
The problem with Splash and pagination is following:

I wasn't able to product a Lua script that delivers a new webpage (after click on pagination link) that is in format of response. and not pure HTML.

So, my solution is following - to click the link and extract that new generated url and direct a crawler to this new url.

So, I on the page that has pagination link I execute

yield SplashRequest(url=response.url, callback=self.get_url, endpoint="execute", args={'lua_source': script})

with following Lua script

def parse_categories(self, response):
    script = """
             function main(splash)
                 assert(splash:go(splash.args.url))
                 splash:wait(1)
                 splash:runjs('document.querySelectorAll(".next-page")[0].click()')
                 splash:wait(1)
                 return splash:url()
             end
             """

and the get_url function

def get_url(self,response):
    yield SplashRequest(url=response.body_as_unicode(), callback=self.parse_categories)

This way I was able to loop my queries.

Same way if you don't expect new URL your Lua script can just produce pure html that you have to work our with regex (that is bad) - but this is the best I was able to do.


问:
Count cells that contain any text
I want to count the cells that contain anything within a range.
Any cell that contain text, or numbers or something else should do a plus one in my result-cell.

I found this function,

```<code>countif(range; criteria)
</code>```

but this doesn't work for me, because I don't know what to type in the criteria. How can I do this?

答:
If you have cells with something like ="" and don't want to count them, you have to subtract number of empty cells from total number of cell by formula like

```<code>=row(G101)-row(G4)+1-countblank(G4:G101)
</code>```

In case of 2-dimensional array it would be

```<code>=(row(G101)-row(A4)+1)*(column(G101)-column(A4)+1)-countblank(A4:G101)
</code>```

Tested at google docs.

Title: Count cells that contain any text

Body:
I want to count the cells that contain anything within a range.
Any cell that contain text, or numbers or something else should do a plus one in my result-cell.

I found this function,

countif(range; criteria)

but this doesn't work for me, because I don't know what to type in the criteria. How can I do this?

Body:
If you have cells with something like ="" and don't want to count them, you have to subtract number of empty cells from total number of cell by formula like

=row(G101)-row(G4)+1-countblank(G4:G101)

In case of 2-dimensional array it would be

=(row(G101)-row(A4)+1)*(column(G101)-column(A4)+1)-countblank(A4:G101)

Tested at google docs.


问:
Java Spring: How to efficiently read and save large amount of data from a CSV file?
I am developing a web application in Java Spring where I want the user to be able to upload a CSV file from the front-end and then see the real-time progress of the importing process and after importing he should be able to search individual entries from the imported data.

The importing process would consist of actually uploading the file (sending it via REST API POST request) and then reading it and saving its contents to a database so the user would be able to search from this data.

What would be the fastest way to save the data to the database? Just looping over the lines and creating a new class object and saving it via JPARepository for each line takes too much time. It took around 90s for 10000 lines. I need to make it a lot faster. I need to add 200k rows in a reasonable amount of time.

Side Notes:

I saw Asynchronous approach, with Reactor. This should be faster as it uses multiple threads and the order of saving the rows basically isn't important (although the data has ID-s in the CSV).

Then I also saw Spring Batch jobs, but all of the examples use SQL. I am using repositories so I'm not sure if I can use it or whether it's the best approach.

答:
If you are using SQLServer simply create a SSiS package that looks for the file and when it shows up simply grabs it and loads it and then renames the file.  That make it a one time build and a million times execute and SSIS can load a ton of data fairly fast.
Rick</p>


问:
c++ Function to create gaussian random numbers
I'm using the following function to generate gaussian random numbers:

```<code>double r_norm(double mean, double sigma){
    random_device rd;
    mt19937 gen(rd());
    normal_distribution<double> d(mean, sigma);
    return d(gen);
}
</code>```

However, when I call this in main() with cout:

```<code>for (int k = 0; k < 10; k++){
    cout << r_norm(2,0.5) <<endl;
}
</code>```

It outputs the same number 10 times. Ideally I need to be able to call this function wherever, in order to receive a newly generated number each time.

Update: I managed to fix this by declaring the random device and mersenne twister outside of scope as global variables, but is there a neater way to do this?

答:
The problem is that you need to recycle the random_device.

If you really want to keep the exact same function signature, the easiest way would be to use a global variable:

```<code>random_device rd;
mt19937 gen(rd());

double r_norm(double mean, double sigma){
    normal_distribution<double> d(mean, sigma);
    return d(gen);
}
</code>```

That being said: stl random distributions are statefull, so you need to also recycle d if you want an actual valid distribution.

At this point, maintaining your interface would require a static std::map<pair<double, double>, normal_distribution> so that you recycle them properly as well.

Body:
I'm using the following function to generate gaussian random numbers:

double r_norm(double mean, double sigma){
    random_device rd;
    mt19937 gen(rd());
    normal_distribution<double> d(mean, sigma);
    return d(gen);
}

However, when I call this in main() with cout:

for (int k = 0; k < 10; k++){
    cout << r_norm(2,0.5) <<endl;
}

It outputs the same number 10 times. Ideally I need to be able to call this function wherever, in order to receive a newly generated number each time.

Update: I managed to fix this by declaring the random device and mersenne twister outside of scope as global variables, but is there a neater way to do this?

Body:
The problem is that you need to recycle the random_device.

If you really want to keep the exact same function signature, the easiest way would be to use a global variable:

random_device rd;
mt19937 gen(rd());

double r_norm(double mean, double sigma){
    normal_distribution<double> d(mean, sigma);
    return d(gen);
}

That being said: stl random distributions are statefull, so you need to also recycle d if you want an actual valid distribution.

At this point, maintaining your interface would require a static std::map<pair<double, double>, normal_distribution> so that you recycle them properly as well.


问:
ReflectionException in Route.php Class Controller does not exist
I'm using Laravel 5.2 in a centos 5.8 server and getting the following error:

```<code>ReflectionException in Route.php line 280:
Class xxxx\Http\Controllers\CpanelController does not exist

ErrorException in ClassLoader.php line 412: include(/home/xxxx/vendor/composer/../../app/Http/Controllers/CpanelController.php): failed to open stream: Permission denied
</code>```

I am trying with:

php artisan cache:clear

chmod -R 777 storage

composer dump-autoload

But the problem persists

答:
Laravel Throughs Reflection Exception when it does not find a class which is pointed in String.

There are some points to remember.

Make Sure you have a correct namespace in your class which you are trying to access.

Check the upper & lower case for controller file. Upper case and lower case doesn't matter in WINDOWS but it is not going to work in Linux/CentOS.

run composer update

give Permission to whole directories as 777 and file have 644

Body:
I'm using Laravel 5.2 in a centos 5.8 server and getting the following error:

ReflectionException in Route.php line 280:
Class xxxx\Http\Controllers\CpanelController does not exist

ErrorException in ClassLoader.php line 412: include(/home/xxxx/vendor/composer/../../app/Http/Controllers/CpanelController.php): failed to open stream: Permission denied

I am trying with:

php artisan cache:clear

chmod -R 777 storage

composer dump-autoload

But the problem persists


问:
How to automatically start Teapot on an Image start?
I use Teapot micro framework for my REST API server. However, if I reboot the VM Teapot does not start automatically on Image start.

What is the right way to autostart Teapot?

答:
There are two main ways you can add startup scripts to a Pharo Image:

1) The most simple way is just to put a "startup.st" file into the  directory with the Image. This file is run after the Image is loaded so any configurations can be there. So for instance Teapot start can be run from there.

2) More advanced way is to use "Smalltalk addToStartUpList: MyClass" call. This method will register "MyClass" into SessionManager startupList so that "MyClass>>startUp" class method is called on Image start.

This means that MyClass must have "startUp" method defined on the class side (where init Teapot script could be put).


问:
How can I set the width of certain columns?
I'm playing around with the code sample below.

```<code>Sub Hide_Columns_Containing_Value()

Dim c As Range
Dim ThisIsToday As Date
Dim TwoWeeksBack As Date
Dim ThreeMonthsAhead As Date

    ThisIsToday = Date
    TwoWeeksBack = ThisIsToday - 14
    ThreeMonthsAhead = ThisIsToday + 100

For Each c In Range("O4:XA4").Cells
If c.Value < TwoWeeksBack Or c.Value > ThreeMonthsAhead Then
    Range(c.Address).Select
    Selection.ColumnWidth = 1.75
    Else
        c.EntireColumn.Hidden = True
    End If
Next c

End Sub
</code>```

Basically I want to loop through all cells and if the value is a date less than two seeks ago, or more than 3 months from now, I want to hide the column.  The problem is that the dates are not in every cell; the dates are in every 7 cells, which represent every Friday.  The hiding and showing of columns is not working like I want it to, because of all the blank cells.

Here is a screen shot of the dates.

答:
```<code>Sub dostuff()
    Dim c As Range
    For Each c In Range("A:C").Columns
        c.ColumnWidth = 77
    Next c
End Sub
</code>```

you should be able to fill in the blanks from here

Body:
I'm playing around with the code sample below.

Sub Hide_Columns_Containing_Value()

Dim c As Range
Dim ThisIsToday As Date
Dim TwoWeeksBack As Date
Dim ThreeMonthsAhead As Date

    ThisIsToday = Date
    TwoWeeksBack = ThisIsToday - 14
    ThreeMonthsAhead = ThisIsToday + 100

For Each c In Range("O4:XA4").Cells
If c.Value < TwoWeeksBack Or c.Value > ThreeMonthsAhead Then
    Range(c.Address).Select
    Selection.ColumnWidth = 1.75
    Else
        c.EntireColumn.Hidden = True
    End If
Next c

End Sub

Basically I want to loop through all cells and if the value is a date less than two seeks ago, or more than 3 months from now, I want to hide the column.  The problem is that the dates are not in every cell; the dates are in every 7 cells, which represent every Friday.  The hiding and showing of columns is not working like I want it to, because of all the blank cells.

Here is a screen shot of the dates.

Body:
Sub dostuff()
    Dim c As Range
    For Each c In Range("A:C").Columns
        c.ColumnWidth = 77
    Next c
End Sub

you should be able to fill in the blanks from here


问:
Code challenge: finding the divisible in a list
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

```<code>def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt
</code>```

答:
I guess sorting the list is pretty inefficient. I would rather try to iteratively reduce the number of candidates. You could do that in two steps.

At first filter all numbers that do not have a divisor.

```<code>from itertools import combinations
candidates = [max(pair) for pair in combinations(l, 2) if max(pair)%min(pair) == 0]
</code>```

After that, count the number of remaining candidates, that do have a divisor.

```<code>result = sum(max(pair)%min(pair) == 0 for pair in combinations(candidates, 2))
</code>```

Body:
I am playing a code challenge. Simply speaking, the problem is:

Given a list L (max length is of the order of 1000) containing positive integers.
  Find the number of "Lucky Triples", which is L[i] divides L[j], and L[j] divides L[k].

for example, [1,2,3,4,5,6] should give the answer 3 because [1,2,4], [1,2,6],[1,3,6]

My attempt:

Sort the list. (let say there are n elements)

3 For loops: i, j, k (i from 1 to n-2), (j from i+1 to n-1), (k from j+1 to n)

only if L[j] % L[i] == 0, the k for loop will be executed

The algorithm seems to give the correct answer. But the challenge said that my code exceeded the time limit. I tried on my computer for the list [1,2,3,...,2000], count = 40888(I guess it is correct). The time is around 5 second.

Is there any faster way to do that?

This is the code I have written in python.

def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt

Body:
I guess sorting the list is pretty inefficient. I would rather try to iteratively reduce the number of candidates. You could do that in two steps.

At first filter all numbers that do not have a divisor.

from itertools import combinations
candidates = [max(pair) for pair in combinations(l, 2) if max(pair)%min(pair) == 0]

After that, count the number of remaining candidates, that do have a divisor.

result = sum(max(pair)%min(pair) == 0 for pair in combinations(candidates, 2))


问:
Different starting directory per window?
I daily use tmux (2.5) on my laptop to work, and my tmux sessions have a starting directory which is the working directory I started the tmux session from. Every pane/window I open start with this starting directory as working directory.

I can change this starting directory, and this change would apply to the whole session.

But if I want to work on a different project with several panes, I could start a new window, but every pane I would open in it would start with the session's starting directory : I would have to cd to the new location for each pane which isn't practical.

If I need to work on several project/directories simultaneously, I can start a new terminal session, then cd to the relevant directory/project and start a new tmux session. That's not complicated.

But if I want to do the same thing on a server through ssh, I'd need to either :

open a new ssh session.

either embed my remote tmux sessions in an other tmux session.

Neither sounds practical to me, I'd prefer a single tmux session on the remote machine.

I think it would be more convenient to being able to start new window with its own starting directory location that would apply to any new pane opened in it. Is there a way to achieve this?

Edit :

I already tried the -c parameter of tmux new-window command.

But it doesn't assign its starting directory to the window created this way, it only applies this custom starting directory to the first pane created.

Any new pane opened in this window then uses the session's starting directory as default working dir (and not the path passed to tmux new-window).

答:
Yes, it turns out the -c option to the new-window command is what you are looking for: https://unix.stackexchange.com/questions/12032/create-new-window-with-current-directory-in-tmux Also, this: https://unix.stackexchange.com/questions/101949/new-tmux-panes-go-to-the-same-directory-as-the-current-pane-new-tmux-windows-go

So either of tmux new-window -c $(pwd) or tmux new-window -c /path/to/dir inside your tmux session should do it.


问:
How I reference hash inside of subroutine?
I am trying to use the tie function of the module Config::IniFiles but I cannot figure out how to reference the hash inside of sub routine. If I remove the tie function and related code from the sub routine it works perfectly.

This is the line I thought would work, but tells me that "$cfg" is not initialized.

```<code>use Config::IniFiles
sub config_file {
    my $cfg_file = 'settings.ini';
    my %cfg;
    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    #my $cfg = Config::IniFiles->new( -file => $cfg_file );

}

sub esx_host_check {
    my $esx_host = config_file()->$cfg{ESX}{host};
}
</code>```

I am sure it is something simple, but I am stumped.

答:
(1) always start your perl code with use strict. You should have received a warning in esx_host_check() about an unknown %cfg

(2) use use vars(...) to implement "global" identifiers:

```<code>use vars qw(%cfg);

sub one
    {
        tie %cfg, ....
    }

sub two
    {
        my $value = $cfg{foo}{bar};
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use the tie function of the module Config::IniFiles but I cannot figure out how to reference the hash inside of sub routine. If I remove the tie function and related code from the sub routine it works perfectly.

This is the line I thought would work, but tells me that "$cfg" is not initialized.

use Config::IniFiles
sub config_file {
    my $cfg_file = 'settings.ini';
    my %cfg;
    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    #my $cfg = Config::IniFiles->new( -file => $cfg_file );

}

sub esx_host_check {
    my $esx_host = config_file()->$cfg{ESX}{host};
}

I am sure it is something simple, but I am stumped.

Body:
(1) always start your perl code with use strict. You should have received a warning in esx_host_check() about an unknown %cfg

(2) use use vars(...) to implement "global" identifiers:

use vars qw(%cfg);

sub one
    {
        tie %cfg, ....
    }

sub two
    {
        my $value = $cfg{foo}{bar};
    }


问:
ADO.NET Entity Data Model BUG
I have a project in visual studio ultimate 2010 (MVVM) and database, in SQLITE.

Everything worked fine, but now I have a problem with the ADO.NET Entity Data Model.

I searched for information about this and have not found much .. Every time I want to open the wizard, it just closes.

I think I should reinstall Visual Studio, but before doing so if anyone has had this error before and know what can be, I'd be grateful.

答:
I solved the problem by doing some steps below:
1/ Open "Server Explorer" window in Visual Studio
2/ Delete all Connections under "Data Connections" sections
3/ Then, Add the ADO.net Entity Data Model as normal </p>

Title: ADO.NET Entity Data Model BUG


问:
Required field display error message on form
I have a form that I need to have required fields filled out.  I know to use the code below to verify if the field is blank:

```<code><?php
if  (!empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
</code>```

My question is, how do I get the error message to display on the form page, saving all the data already entered in the form.  Example: I fill out all 15 fields on the form, excluding the required field.  When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.

I am not sure on the code to do that, or where to put it.  On the form, or on the script that executes the form?

答:
Why you use !empty you can use empty for best result like

```<code><?php
if  (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
</code>```

Actually you should be first set HTML5 validation like

```<code><input type="text" name="abc" required="">
</code>```

You can set custom error message for required field like

```<code><input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">
</code>```

Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.

Thanks.

Body:
I have a form that I need to have required fields filled out.  I know to use the code below to verify if the field is blank:

<?php
if  (!empty($_POST['client_name'])) {
echo '
'"Client Name is required!"'
';
}
?>

My question is, how do I get the error message to display on the form page, saving all the data already entered in the form.  Example: I fill out all 15 fields on the form, excluding the required field.  When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.

I am not sure on the code to do that, or where to put it.  On the form, or on the script that executes the form?

Body:
Why you use !empty you can use empty for best result like

<?php
if  (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>

Actually you should be first set HTML5 validation like

<input type="text" name="abc" required="">

You can set custom error message for required field like

<input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">

Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.

Thanks.


问:
Xamarin.Forms, XAML - How to display image with color overlay
I'm building a layout in my Xamarin.Forms app, and I need to display an image with a transparent color overlay. I have a Grid layout that displays the image and stacks a ContentView on top of it with a semitransparent background color. As you can see in the images below, the ContentView (and I suspect the containing Grid) simply refuses to shrink to the size of the image (the largest item in the Grid).

How can I do this?

I've tried all kinds of different VerticalOptions on the different views and nothing I've done so far has worked, but I'm new to Forms so confirm if you think the solution might be basic. :)

Thanks in advance!

Here's the code:

```<code><Grid VerticalOptions="Start">
    <Image Source="PlayerBackground.png" />
    <ContentView BackgroundColor="#88000000"></ContentView>
    <StackLayout VerticalOptions="Center">
        <Image/>
        <Label/>
    </StackLayout>
</Grid>
</code>```

Here's what it's supposed to look like:

And here's what I'm actually getting:

答:
Try setting the HorizontalOptions and Vertical Options on the ContentView.

Also you can use a Grid instead of a ContentView with HorizontalOptions and VerticalOptions set to FillAndExpand

Body:
I'm building a layout in my Xamarin.Forms app, and I need to display an image with a transparent color overlay. I have a Grid layout that displays the image and stacks a ContentView on top of it with a semitransparent background color. As you can see in the images below, the ContentView (and I suspect the containing Grid) simply refuses to shrink to the size of the image (the largest item in the Grid).

How can I do this?

I've tried all kinds of different VerticalOptions on the different views and nothing I've done so far has worked, but I'm new to Forms so confirm if you think the solution might be basic. :)

Thanks in advance!

Here's the code:

<Grid VerticalOptions="Start">
    <Image Source="PlayerBackground.png" />
    <ContentView BackgroundColor="#88000000"></ContentView>
    <StackLayout VerticalOptions="Center">
        <Image/>

    </StackLayout>
</Grid>

Here's what it's supposed to look like:

And here's what I'm actually getting:


答:
Your original code, for reference.

```<code>def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt
</code>```

There are a number of misimplementations here, and with just a few tweaks we can probably get this running much faster. Let's start:

```<code>def answer(lst):  # I prefer not to use `l` because it looks like `1`
    lst.sort()
    count = 0  # use whole words here. No reason not to.
    if len(lst) == 2:
        return count
    for i, first in enumerate(lst):
        # using `enumerate` here means you can avoid ugly ranges and
        # saves you from a look up on the list afterwards. Not really a
        # performance hit, but definitely looks and feels nicer.
        for j, second in enumerate(lst[i+1:], start=i+1):
            # this is the big savings. You know since you sorted the list that
            # lst[1] can't divide lst[n] if n>1, but your code still starts
            # searching from lst[1] every time! Enumerating over `l[i+1:]`
            # cuts out a lot of unnecessary burden.
            if second % first == 0:
                # see how using enumerate makes that look nicer?
                for third in lst[j+1:]:
                    if third % second == 0:
                        count += 1
    return count
</code>```

I bet that on its own will pass your speed test, but if not, you can check for membership instead. In fact, using a set here is probably a great idea!

```<code>def answer2(lst):
    s = set(lst)
    limit = max(s)  # we'll never have a valid product higher than this
    multiples = {}  # accumulator for our mapping
    for n in sorted(s):
        max_prod = limit // n  # n * (max_prod+1) > limit
        multiples[n] = [n*k for k in range(2, max_prod+1) if n*k in s]
        # in [1,2,3,4,5,6]:
        # multiples = {1: [2, 3, 4, 5, 6],
        #              2: [4, 6],
        #              3: [6],
        #              4: [],
        #              5: [],
        #              6: []}

    # multiples is now a mapping you can use a Depth- or Breadth-first-search on
    triples = sum(1 for j in multiples
                    for k in multiples.get(j, [])
                    for l in multiples.get(k, []))
    # This basically just looks up each starting value as j, then grabs
    # each valid multiple and assigns it to k, then grabs each valid
    # multiple of k and assigns it to l. For every possible combination there,
    # it adds 1 more to the result of `triples`
    return triples
</code>```

Title: Code challenge: finding the divisible in a list

Body:
Your original code, for reference.

def answer(l):
    l.sort()
    cnt = 0
    if len(l) == 2:
        return cnt
    for i in range(len(l)-2):
        for j in range(1,len(l)-1-i):
            if (l[i+j]%l[i] == 0):
                for k in range(1,len(l)-j-i):
                    if (l[i+j+k]%l[i+j] == 0):
                        cnt += 1

    return cnt

There are a number of misimplementations here, and with just a few tweaks we can probably get this running much faster. Let's start:

def answer(lst):  # I prefer not to use `l` because it looks like `1`
    lst.sort()
    count = 0  # use whole words here. No reason not to.
    if len(lst) == 2:
        return count
    for i, first in enumerate(lst):
        # using `enumerate` here means you can avoid ugly ranges and
        # saves you from a look up on the list afterwards. Not really a
        # performance hit, but definitely looks and feels nicer.
        for j, second in enumerate(lst[i+1:], start=i+1):
            # this is the big savings. You know since you sorted the list that
            # lst[1] can't divide lst[n] if n>1, but your code still starts
            # searching from lst[1] every time! Enumerating over `l[i+1:]`
            # cuts out a lot of unnecessary burden.
            if second % first == 0:
                # see how using enumerate makes that look nicer?
                for third in lst[j+1:]:
                    if third % second == 0:
                        count += 1
    return count

I bet that on its own will pass your speed test, but if not, you can check for membership instead. In fact, using a set here is probably a great idea!

def answer2(lst):
    s = set(lst)
    limit = max(s)  # we'll never have a valid product higher than this
    multiples = {}  # accumulator for our mapping
    for n in sorted(s):
        max_prod = limit // n  # n * (max_prod+1) > limit
        multiples[n] = [n*k for k in range(2, max_prod+1) if n*k in s]
        # in [1,2,3,4,5,6]:
        # multiples = {1: [2, 3, 4, 5, 6],
        #              2: [4, 6],
        #              3: [6],
        #              4: [],
        #              5: [],
        #              6: []}

    # multiples is now a mapping you can use a Depth- or Breadth-first-search on
    triples = sum(1 for j in multiples
                    for k in multiples.get(j, [])
                    for l in multiples.get(k, []))
    # This basically just looks up each starting value as j, then grabs
    # each valid multiple and assigns it to k, then grabs each valid
    # multiple of k and assigns it to l. For every possible combination there,
    # it adds 1 more to the result of `triples`
    return triples


问:
How to accomplish equivalent of Vim's Ctrl-n in GNU Emacs?
Vim's Ctrl+N generally works like this: I type few letters, hit Ctrl+N, and Vim provides me with completions based on words in my all opened buffers.

Solution for Emacs doesn't have to be identical. I mainly use it like this: declare variable, then use it in later code. But I like the lightweight approach of not parsing the source code.

答: I personally use AutoComplete It gives you a nice dropdown box. You can select how many letters you want to type before it activates and customise what you want to show up, including stuff in dabbrev-expand.</p>

OwnerDisplayName: phjr

OwnerDisplayName: James Brooks


问:
R: Atomic Number and averages in lists
I am attempting to find the average batting average per team. I have a matrix that is similar to what I have below:

```<code>        bat_avg      team_name
    [1,] "0.5"        "Rockies"
    [2,] "0"          "Astros"
    [3,] "0.5"        "Rockies"
    [4,] "0"          "Padres"
    [5,] "0"          "Padres"
    [6,] "0"          "Rockies"
    [7,] "0"          "Mets"
    [8,] "0.4"        "Red Sox"
    [9,] "0"          "Yankees"
   [10,] "0"          "Rockies"
</code>```

To find the average bating average per team I tried to transform the matrix into a data frame and attempted to aggregate the data by team name. I am keep receiving the error that my data type is atomic. I am unsure what to do to resolve this problem. I am brand new to R and coding, so thank you for the help!

```<code>bat_avg <- Batting_average[,26]
team_name <- Batting_average[,100]
Batting_average <- cbind(bat_avg, team_name)
df.Batting_average <- as.data.frame(Batting_average)

aggdata <- aggregate(Batting_average$team_name, by list(Batting_average$bat_avg],
FUN = mean)
</code>```

Below is the top of my data

```<code>structure(c("0.5", "0", "0.5", "0", "0", "0", "Rockies", "Rockies",
"Rockies", "Rockies", "Rockies", "Rockies"), .Dim = c(6L, 2L),n.Dimnames = list(
NULL, c("bat_avg", "team_name")))
</code>```

答:
Here is some code that gave reasonable results to me

```<code>myDf <- data.frame(
  avg = c(0.5, 0, 0.5, 0, 0, 0, 0.4),
  team = c("Rockies", "Rockies",
    "Rockies", "Rockies", "Rockies", "Rockies", "Astros")
)

myDf
#   avg    team
# 1 0.5 Rockies
# 2 0.0 Rockies
# 3 0.5 Rockies
# 4 0.0 Rockies
# 5 0.0 Rockies
# 6 0.0 Rockies
# 7 0.4 Astros

aggregate(myDf$avg, by = list(myDf$team), FUN  = mean)
#   Group.1         x
# 1  Astros 0.4000000
# 2 Rockies 0.1666667
</code>```

If you want to run this with your data, replace myDf with

```<code>myDf <- data.frame(
  avg = as.numeric(Batting_average[,26]),
  team = as.factor(Batting_average[,100])
)
</code>```

The methods as.numeric and as.factor might be unnecessary if your data is already in the correct format.

Title: R: Atomic Number and averages in lists

Body:
I am attempting to find the average batting average per team. I have a matrix that is similar to what I have below:

        bat_avg      team_name
    [1,] "0.5"        "Rockies"
    [2,] "0"          "Astros"
    [3,] "0.5"        "Rockies"
    [4,] "0"          "Padres"
    [5,] "0"          "Padres"
    [6,] "0"          "Rockies"
    [7,] "0"          "Mets"
    [8,] "0.4"        "Red Sox"
    [9,] "0"          "Yankees"
   [10,] "0"          "Rockies"

To find the average bating average per team I tried to transform the matrix into a data frame and attempted to aggregate the data by team name. I am keep receiving the error that my data type is atomic. I am unsure what to do to resolve this problem. I am brand new to R and coding, so thank you for the help!

bat_avg <- Batting_average[,26]
team_name <- Batting_average[,100]
Batting_average <- cbind(bat_avg, team_name)
df.Batting_average <- as.data.frame(Batting_average)

aggdata <- aggregate(Batting_average$team_name, by list(Batting_average$bat_avg],
FUN = mean)

Below is the top of my data

structure(c("0.5", "0", "0.5", "0", "0", "0", "Rockies", "Rockies",
"Rockies", "Rockies", "Rockies", "Rockies"), .Dim = c(6L, 2L),n.Dimnames = list(
NULL, c("bat_avg", "team_name")))

Body:
Here is some code that gave reasonable results to me

myDf <- data.frame(
  avg = c(0.5, 0, 0.5, 0, 0, 0, 0.4),
  team = c("Rockies", "Rockies",
    "Rockies", "Rockies", "Rockies", "Rockies", "Astros")
)

myDf
#   avg    team
# 1 0.5 Rockies
# 2 0.0 Rockies
# 3 0.5 Rockies
# 4 0.0 Rockies
# 5 0.0 Rockies
# 6 0.0 Rockies
# 7 0.4 Astros

aggregate(myDf$avg, by = list(myDf$team), FUN  = mean)
#   Group.1         x
# 1  Astros 0.4000000
# 2 Rockies 0.1666667

If you want to run this with your data, replace myDf with

myDf <- data.frame(
  avg = as.numeric(Batting_average[,26]),
  team = as.factor(Batting_average[,100])
)

The methods as.numeric and as.factor might be unnecessary if your data is already in the correct format.


问:
matweb.com: How to get source of page?
I have url like:

http://www.matweb.com/search/DataSheet.aspx?MatGUID=849e2916ab1541be9ff6a17b78f95c82

I want to download source code from that page using this code:

```<code>private static string urlTemplate = @"http://www.matweb.com/search/DataSheet.aspx?MatGUID=";

static string GetSource(string guid)
{
    try
    {
        Uri url = new Uri(urlTemplate + guid);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";

        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        String result = responseStreamReader.ReadToEnd();

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}
</code>```

When I do so I get:

You do not seem to have cookies enabled. MatWeb Requires cookies to be enabled.

Ok, that I understand, so I added lines:

```<code>CookieContainer cc = new CookieContainer();
webRequest.CookieContainer = cc;
</code>```

I got:

Your IP Address has been restricted due to excessive use. The problem may be compounded when an IP address may be shared by many people in a company or through an internet service provider. We apologize for any inconvenience.

I can understand this but I'm not getting this message when I try to visit this page using web browser. What can I do to get the source code? Some cookies or http headers?

答:
It probably doesn't like your UserAgent. Try this:</p>

```<code>webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"; //maybe substitute your own in here
</code>```

Title: matweb.com: How to get source of page?

Body:
I have url like:

http://www.matweb.com/search/DataSheet.aspx?MatGUID=849e2916ab1541be9ff6a17b78f95c82

I want to download source code from that page using this code:

private static string urlTemplate = @"http://www.matweb.com/search/DataSheet.aspx?MatGUID=";

static string GetSource(string guid)
{
    try
    {
        Uri url = new Uri(urlTemplate + guid);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";

        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        String result = responseStreamReader.ReadToEnd();

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}

When I do so I get:

You do not seem to have cookies enabled. MatWeb Requires cookies to be enabled.

Ok, that I understand, so I added lines:

CookieContainer cc = new CookieContainer();
webRequest.CookieContainer = cc;

I got:

Your IP Address has been restricted due to excessive use. The problem may be compounded when an IP address may be shared by many people in a company or through an internet service provider. We apologize for any inconvenience.

I can understand this but I'm not getting this message when I try to visit this page using web browser. What can I do to get the source code? Some cookies or http headers?

Body:
It probably doesn't like your UserAgent. Try this:

webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)"; //maybe substitute your own in here


问:
Make div container auto-expand width to the left instead of the right when text is added
I have a little dropdown, which works just fine:

However, when more text is added to the dropdown, the div expands to the right, like so:

Whereas I'd rather it expand to the left.

Markup/Blade (I'm using Laravel):

```<code><div class="status-dropdown-arrow pointer" id="status-dropdown-arrow-{{ $status->id }}" data-value="{{ $status->id }}"><i class="fa fa-angle-down" aria-hidden="true"></i>
 <ul class="fallback">
    @if (Auth::user()->isFollowing($status->user))
     <a href="{{ route('get.following.add', ['username' => $status->user->username]) }}"><li>Unfollow</li></a>
    @else
     <a href="{{ route('get.following.add', ['username' => $status->user->username]) }}"><li>Follow</li></a>
    @endif
    <a href="{{ route('status.report', ['statusId' => $status->id]) }}"><li>Report</li></a>
 </ul>
</div>
</code>```

CSS:

```<code>.status-dropdown-arrow {
float:right;
margin-top: -58px;
color:#b9adad;
}

.status-dropdown-arrow ul.fallback {
position: absolute;
border: 1px solid #d8d8d8;
border-radius: 3px;
padding: 5px;
display: none;
z-index: 1000;
background-color: #f6f4f4;
list-style: none;
margin-top: 0px;
margin-left: -72px;
}
</code>```

How could I make the container expand to the left rather than the right?

答:
position: relative on the parent and right: 0 on the absolutely positioned child will align it to the right side of the parent, and the element will grow to the left.

Your ul/li structure is invalid, too. An a can't be a child of a ul - you should move the a's inside the li's

.status-dropdown-arrow {
  float: right;
  color: #b9adad;
  position: relative;
}

.status-dropdown-arrow ul.fallback {
  position: absolute;
  border: 1px solid #d8d8d8;
  border-radius: 3px;
  padding: 5px;
  z-index: 1000;
  background-color: #f6f4f4;
  list-style: none;
  margin-top: 0px;
  right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<div class="status-dropdown-arrow pointer">
  <i class="fa fa-angle-down" aria-hidden="true"></i>
  <ul class="fallback">
    <li>Unfollow</li>
    <li>Follow</li>
    <li>Report</li>
  </ul>
</div></code>```

Body:
I have a little dropdown, which works just fine:

However, when more text is added to the dropdown, the div expands to the right, like so:

Whereas I'd rather it expand to the left.

Markup/Blade (I'm using Laravel):

id }}" data-value="{{ $status->id }}">

    @if (Auth::user()->isFollowing($status->user))
      $status->user->username]) }}">
Unfollow

    @else
      $status->user->username]) }}">
Follow

    @endif
     $status->id]) }}">
Report

CSS:

.status-dropdown-arrow {
float:right;
margin-top: -58px;
color:#b9adad;
}

.status-dropdown-arrow ul.fallback {
position: absolute;
border: 1px solid #d8d8d8;
border-radius: 3px;
padding: 5px;
display: none;
z-index: 1000;
background-color: #f6f4f4;
list-style: none;
margin-top: 0px;
margin-left: -72px;
}

How could I make the container expand to the left rather than the right?

Body:
position: relative on the parent and right: 0 on the absolutely positioned child will align it to the right side of the parent, and the element will grow to the left.

Your ul/li structure is invalid, too. An a can't be a child of a ul - you should move the a's inside the li's

.status-dropdown-arrow {
  float: right;
  color: #b9adad;
  position: relative;
}

.status-dropdown-arrow ul.fallback {
  position: absolute;
  border: 1px solid #d8d8d8;
  border-radius: 3px;
  padding: 5px;
  z-index: 1000;
  background-color: #f6f4f4;
  list-style: none;
  margin-top: 0px;
  right: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

<div class="status-dropdown-arrow pointer">
  <i class="fa fa-angle-down" aria-hidden="true"></i>
  <ul class="fallback">
    <li><a href="">Unfollow</a></li>
    <li><a href="">Follow</a></li>
    <li><a href="">Report</a></li>
  </ul>
</div>


问:
Constructing a simple atomic lattice with VPython (Python 3.6.1)
I am currently working my way through Mark Newman's Computational Physics and I've encountered some trouble doing the exercises on 3D modelling using the VPython module.

I'm attempting to construct a simple L*L lattice and display it using the VPython module. I'm running Python 3.6.1.

My code looks like this:

```<code>from vpython import sphere

L = 5 # lattice size
R = 0.3 # atom radius

for i in range(-L,L+1):
    for j in range(-L,L+1):
        for k in range(-L,L+1):
            sphere(pos=[i,j,k],radius=R)
</code>```

I get the following attribute error:

```<code>Traceback (most recent call last):
  File "C:\Users\xxx\Desktop\python\computational physics\web resources\lattice.py", line 7, in <module>
    sphere(pos=[i,j,k],radius=R)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\vpython\vpython.py", line 1168, in __init__
    super(sphere, self).setup(args)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\vpython\vpython.py", line 631, in setup
    else: raise AttributeError(a+' must be a vector')
AttributeError: pos must be a vector
</code>```

The examples in the book use the visual module so I suspect that my problem is due to some compatibility issues between my version of Python and VPython.

Is there any way to fix my code so it displays the lattice using VPython? If not, is there an alternative to VPython?

答:
You need to create a vector:
http://vpython.org/contents/docs/vector.html

First, you have to import it via

```<code>from vpython import vector
</code>```

Now you change your last line to

```<code>sphere(pos=vector(i,j,k),radius=R)
</code>```

and it hopefully should work!

Body:
I am currently working my way through Mark Newman's Computational Physics and I've encountered some trouble doing the exercises on 3D modelling using the VPython module.

I'm attempting to construct a simple L*L lattice and display it using the VPython module. I'm running Python 3.6.1.

My code looks like this:

from vpython import sphere

L = 5 # lattice size
R = 0.3 # atom radius

for i in range(-L,L+1):
    for j in range(-L,L+1):
        for k in range(-L,L+1):
            sphere(pos=[i,j,k],radius=R)

I get the following attribute error:

Traceback (most recent call last):
  File "C:\Users\xxx\Desktop\python\computational physics\web resources\lattice.py", line 7, in <module>
    sphere(pos=[i,j,k],radius=R)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\vpython\vpython.py", line 1168, in __init__
    super(sphere, self).setup(args)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\site-packages\vpython\vpython.py", line 631, in setup
    else: raise AttributeError(a+' must be a vector')
AttributeError: pos must be a vector

The examples in the book use the visual module so I suspect that my problem is due to some compatibility issues between my version of Python and VPython.

Is there any way to fix my code so it displays the lattice using VPython? If not, is there an alternative to VPython?

Body:
You need to create a vector:
http://vpython.org/contents/docs/vector.html

First, you have to import it via

from vpython import vector

Now you change your last line to

sphere(pos=vector(i,j,k),radius=R)

and it hopefully should work!


问:
How to fix 'has no exported member 'VeiwChild'' error in Ionic
So I am trying to import google maps into my ionic 2 application. And so far all everything works. the problem arises with me importing the VeiwChild pack from @angular/core. Hence everytime I run the code it gives me the same error.

` Module '"C:/Users/Jay/Documents/maps/node_modules/@angular/core/core"' has no exported member 'VeiwChild'.

C:/Users/Jay/Documents/maps/src/pages/home/home.ts

import { Component, VeiwChild } from '@angular/core';

import { NavController } from 'ionic-angular'; `

Here is my index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <link href="build/main.css" rel="stylesheet">

  <ion-app></ion-app>

```
</div>
</div>
</p>

<p>This is the home.html code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
<div #map id="map"></div>
</ion-content></code>```

this is my home.scss code

page-home {
    .ios, .md {

        home-page {

          .scroll {
            height: 100%
          }

          #map {
            width: 100%;
            height: 100%;
          }

        }

    }

}
```

<p>And finally here is my home.ts code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, VeiwChild } from '@angular/core';
import { NavController } from 'ionic-angular';

declare var google;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 @VeiwChild('map') mapElement;
 map: any;

  constructor(public navCtrl: NavController) {

  }

  ionVeiwDidLoad()
  {
   this.loadMap();
  }

  loadMap(){

    let latLng = new google.maps.LatLng(-34.9290, 138.6010);

    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

  }
}</code>```

I'm not entirely sure why i keep on getting this error. This is the video i used as reference.
link

答:
Its just a typo.

This:

```<code>import { Component, VeiwChild } from '@angular/core';
</code>```

Should be this:

```<code>import { Component, ViewChild } from '@angular/core';
</code>```

View NOT Veiw

NOTE: It is also misspelled in several other places, such as here:

```<code>@VeiwChild('map') mapElement;
</code>```

Body:
So I am trying to import google maps into my ionic 2 application. And so far all everything works. the problem arises with me importing the VeiwChild pack from @angular/core. Hence everytime I run the code it gives me the same error.

` Module '"C:/Users/Jay/Documents/maps/node_modules/@angular/core/core"' has no exported member 'VeiwChild'.

C:/Users/Jay/Documents/maps/src/pages/home/home.ts

import { Component, VeiwChild } from '@angular/core';

import { NavController } from 'ionic-angular'; `

Here is my index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <link href="build/main.css" rel="stylesheet">

  <ion-app></ion-app>

This is the home.html code

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

</ion-content>

this is my home.scss code

page-home {
    .ios, .md {

        home-page {

          .scroll {
            height: 100%
          }

          #map {
            width: 100%;
            height: 100%;
          }

        }

    }

}

And finally here is my home.ts code

import { Component, VeiwChild } from '@angular/core';
import { NavController } from 'ionic-angular';

declare var google;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 @VeiwChild('map') mapElement;
 map: any;

  constructor(public navCtrl: NavController) {

  }

  ionVeiwDidLoad()
  {
   this.loadMap();
  }

  loadMap(){

    let latLng = new google.maps.LatLng(-34.9290, 138.6010);

    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

  }
}

I'm not entirely sure why i keep on getting this error. This is the video i used as reference.
link

Body:
Its just a typo.

This:

import { Component, VeiwChild } from '@angular/core';

Should be this:

import { Component, ViewChild } from '@angular/core';

View NOT Veiw

NOTE: It is also misspelled in several other places, such as here:

@VeiwChild('map') mapElement;


问:
PHP get variable from shell script
How can php get variable from shell script.
I have: shell_exec('php /var/www/html/test/kobi.php $param1');
And i want to recieved $parm1 in kobi.php
I tried to do it with: $imsi=$argv[1];
but it doesn't work.
can someone explain what's wrong?
How should i do that correct?

答:
You use the wrong function try  exec instead

http://php.net/manual/en/function.exec.php

exec ( string $command [, array &$output [, int &$return_var ]] )

```<code>   $param1 = escapeshellarg( $param1 );
   exec('php /var/www/html/test/kobi.php $param1', $output );
</code>```

And use this too.

http://php.net/manual/en/function.escapeshellarg.php

Otherwise someone take over your server maybee...

UPDATE

```<code>'php /var/www/html/test/kobi.php $param1'
</code>```

Is string literal, so your input is $param1 literally, not the value of it.  By the way.  You would use " double quotes for variable interpolation.

Title: PHP get variable from shell script

Body:
You use the wrong function try  exec instead

http://php.net/manual/en/function.exec.php

exec ( string $command [, array &$output [, int &$return_var ]] )

   $param1 = escapeshellarg( $param1 );
   exec('php /var/www/html/test/kobi.php $param1', $output );

And use this too.

http://php.net/manual/en/function.escapeshellarg.php

Otherwise someone take over your server maybee...

UPDATE

'php /var/www/html/test/kobi.php $param1'

Is string literal, so your input is $param1 literally, not the value of it.  By the way.  You would use " double quotes for variable interpolation.


问:
Can't get url request to show, 404
I'm completely new to backend, working through the djangobook tutorial. If I'm missing any vital information, let me know. The first task is to get 'Hello World' to show up on your development server, and it keeps returning 404. The two files in question being the views.py (my hello world file) and urls.py

this is the views.py:

```<code>from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")
</code>```

this is the urls.py:

```<code>from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
]
</code>```

I feel like its not finding the views file correctly? This is how there set up, exactly as he said to do it in the tutorial

答:
You need to change the URL's in two places. One in your app like you did, and the other in the django directory. This link has more information on how to do it.</p>

```<code>from django.conf.urls import patterns, include, url

urlpatterns = patterns(
    '',

    url(r'', include('hello.urls')),
)
</code>```

Title: Can't get url request to show, 404

Body:
I'm completely new to backend, working through the djangobook tutorial. If I'm missing any vital information, let me know. The first task is to get 'Hello World' to show up on your development server, and it keeps returning 404. The two files in question being the views.py (my hello world file) and urls.py

this is the views.py:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")

this is the urls.py:

from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
]

I feel like its not finding the views file correctly? This is how there set up, exactly as he said to do it in the tutorial

Body:
You need to change the URL's in two places. One in your app like you did, and the other in the django directory. This link has more information on how to do it.

from django.conf.urls import patterns, include, url

urlpatterns = patterns(
    '',

    url(r'', include('hello.urls')),
)


问:
Strip HTML tags from repeatable div
I am writing a code where have a HTML code like this, I want to strip/replace the HTML tags inside blog-excerpt area with 160 character.

After run my code showing the same text data in both div. But i need to show the actual text

```<code><div class="blog-item">
    <div class="blog-excerpt" style="color:red">
        <b>Here is the</b>  Sample Text <i> One (01) </i>
    </div>
</div>
<div class="blog-item"  style="color:blue">
    <div class="blog-excerpt">
       <b>Here is the</b>  Sample Text <i> Two (02) </i>
    </div>
</div>
</code>```

Now i want to stripe the HTML tags from inside of the "blog-excerpt" div. So all the HTML code will be plain text actually and i also want to give 160 character limit for  "blog-excerpt" content.

I used the follow jquery code to do that.

```<code>var str = $( ".blog-excerpt" ).text();
$( ".blog-excerpt" ).text( str );
$(".blog-excerpt").text(function(index, currentText) {
return currentText.substr(0, 160);
</code>```

And it works BUT Unfortunately there showing same text in both "blog-item" after run my jquery code.

Please help me to finish that code.

答:
I resolved that issue with the following code. $( ".blog-excerpt" ).text( str );
It was wrong on my code. I deleted that and it works

    var str = $( ".blog-excerpt" ).text();
    $(".blog-excerpt").text(function(index, currentText) {
    return currentText.substr(0, 160);
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blog-item">
    <div class="blog-excerpt" style="color:red">
     <b>Here is the</b>  Sample Text <i> One (01) </i>
 </div>
    </div>
    <div class="blog-item"  style="color:blue">
    <div class="blog-excerpt">
       <b>Here is the</b>  Sample Text <i> Two (02) </i>
    </div>
    </div></code>```

Title: Strip HTML tags from repeatable div

Body:
I am writing a code where have a HTML code like this, I want to strip/replace the HTML tags inside blog-excerpt area with 160 character.

After run my code showing the same text data in both div. But i need to show the actual text

        Here is the  Sample Text  One (01)

       Here is the  Sample Text  Two (02)

Now i want to stripe the HTML tags from inside of the "blog-excerpt" div. So all the HTML code will be plain text actually and i also want to give 160 character limit for  "blog-excerpt" content.

I used the follow jquery code to do that.

var str = $( ".blog-excerpt" ).text();
$( ".blog-excerpt" ).text( str );
$(".blog-excerpt").text(function(index, currentText) {
return currentText.substr(0, 160);

And it works BUT Unfortunately there showing same text in both "blog-item" after run my jquery code.

Please help me to finish that code.

Body:
I resolved that issue with the following code. $( ".blog-excerpt" ).text( str );
It was wrong on my code. I deleted that and it works

    var str = $( ".blog-excerpt" ).text();
    $(".blog-excerpt").text(function(index, currentText) {
    return currentText.substr(0, 160);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="blog-item">
    <div class="blog-excerpt" style="color:red">
     <b>Here is the</b>  Sample Text <i> One (01) </i>
 </div>
    </div>
    <div class="blog-item"  style="color:blue">
    <div class="blog-excerpt">
       <b>Here is the</b>  Sample Text <i> Two (02) </i>
    </div>
    </div>


问:
Select element with div and class and data attribute
How do I select a element using it's element type (Div), a class (spaceEvent) and a data attribute (data-event-id)?

here is an example of a element

```<code><div class="spaceEvent" data-event-id=112>
</code>```

and I want to find this element so that I can search for stuff inside it?

my guess would be something like

```<code>$("div.spaceEvent").find("[event-id=112]")
</code>```

but I'm not sure!

答:
Your selectors are almost correct, but you need to combine them in to a single jQuery object. Your use of find() means that you're currently looking for a child element of the div instead of looking for a div with all the specified attributes.

Try this instead:

```<code>$('div.spaceEvent[data-event-id="112"]')
</code>```

Body:
How do I select a element using it's element type (Div), a class (spaceEvent) and a data attribute (data-event-id)?

here is an example of a element

and I want to find this element so that I can search for stuff inside it?

my guess would be something like

$("div.spaceEvent").find("[event-id=112]")

but I'm not sure!

Body:
Your selectors are almost correct, but you need to combine them in to a single jQuery object. Your use of find() means that you're currently looking for a child element of the div instead of looking for a div with all the specified attributes.

Try this instead:

$('div.spaceEvent[data-event-id="112"]')


问:
"Permission Denied" using cygwin in Windows
Background:
I am trying to write a [.bat] file so I can double click it and a bash script will get invoked.  The bash script will start up a few windows GUI apps to monitor GPU/CPU temperatures.  I just did a fresh install of cygwin v1.7.7-1 (downloaded today) and windows 7.

Code:
monitor-temps.bat:

```<code>C:\cygwin\bin\bash.exe ~/bin/monitor-temps.bash
pause
</code>```

Code:
monitor-temps.bash:

```<code>#!/usr/bin/bash
"/cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe" &
</code>```

Output:
After I double click the [.bat] file, I get a:

```<code>C:\Users\michael\Desktop>C:\cygwin\bin\bash.exe ~/bin/monitor-temps.bash

C:\Users\michael\Desktop>pause
Press any key to continue . . . /home/michael/bin/monitor-temps.bash: line 2: /cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe: Permission denied
</code>```

I still get the same permissions error when I cd to the directory and manually execute the application.

Permissions:
From my experience with permission problems in Linux, everything looks good because I am the user I think I am, and the file has the expected permissions:

```<code>$ whoami
michael

$ ls -l GPU*
-rwx------+ 1 michael        None 890720 2010-12-01 19:23 GPU-Z.0.4.8.exe
</code>```

Question:
Does anyone know how to fix this?  Am I missing something?

答:
-rwx------+ might be the problem. Some hidden acl may forbid x for you.
Reset your acl with setfacl then.

```<code>$ cat >/tmp/faclx <<EOF
user::rwx
group::r--
mask:rwx
other:r--
EOF
$ setfacl -f /tmp/faclx /cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe
</code>```

Or you need elevated permissions:

```<code>$ cygstart  --action=runas /cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe
</code>```

Body:
Background:
I am trying to write a [.bat] file so I can double click it and a bash script will get invoked.  The bash script will start up a few windows GUI apps to monitor GPU/CPU temperatures.  I just did a fresh install of cygwin v1.7.7-1 (downloaded today) and windows 7.

Code:
monitor-temps.bat:

C:\cygwin\bin\bash.exe ~/bin/monitor-temps.bash
pause

Code:
monitor-temps.bash:

#!/usr/bin/bash
"/cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe" &

Output:
After I double click the [.bat] file, I get a:

C:\Users\michael\Desktop>C:\cygwin\bin\bash.exe ~/bin/monitor-temps.bash

C:\Users\michael\Desktop>pause
Press any key to continue . . . /home/michael/bin/monitor-temps.bash: line 2: /cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe: Permission denied

I still get the same permissions error when I cd to the directory and manually execute the application.

Permissions:
From my experience with permission problems in Linux, everything looks good because I am the user I think I am, and the file has the expected permissions:

$ whoami
michael

$ ls -l GPU*
-rwx------+ 1 michael        None 890720 2010-12-01 19:23 GPU-Z.0.4.8.exe

Question:
Does anyone know how to fix this?  Am I missing something?

Body:
-rwx------+ might be the problem. Some hidden acl may forbid x for you.
Reset your acl with setfacl then.

$ cat >/tmp/faclx <<EOF
user::rwx
group::r--
mask:rwx
other:r--
EOF
$ setfacl -f /tmp/faclx /cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe

Or you need elevated permissions:

$ cygstart  --action=runas /cygdrive/c/Users/michael/Desktop/apps_and_drivers/GPU-Z.0.4.8.exe


问:
PUT request in node.js using $http
I'm trying to make a PUT request to a SQL database through node.js using AngularJS. I keep getting a 400 bad request error. Not sure what's wrong with the request, since this format works using a straight $.ajax call. Any help would be appreciated </p>

```<code>  vm.approveUser = function(user_id){
    console.log('in approveUser');
    console.log('user_id', user_id);
    $http({
      method: 'PUT',
      url: '/admin/approve',
      data: user_id
    }).then(function(){
      console.log('back from the /approve');
      vm.getRequests();
    }); //end .then function
  }; //end approveUser
</code>```

答:
Try simplifying the request and add a return statement. See if it resolves.

vm.approve = function(user_id) {
  var url = '/admin/approve';
  return $http.put(url, user_id)
    .then(function(resp) {
      vm.getRequests();
    })
    .catch(function(error) {

    })
    .finally(function() {

    });
};
```

Title: PUT request in node.js using $http

Body:
I'm trying to make a PUT request to a SQL database through node.js using AngularJS. I keep getting a 400 bad request error. Not sure what's wrong with the request, since this format works using a straight $.ajax call. Any help would be appreciated

  vm.approveUser = function(user_id){
    console.log('in approveUser');
    console.log('user_id', user_id);
    $http({
      method: 'PUT',
      url: '/admin/approve',
      data: user_id
    }).then(function(){
      console.log('back from the /approve');
      vm.getRequests();
    }); //end .then function
  }; //end approveUser


问:
Curl_http_done: called premature
I'm building a new service, and when I curl it I see a message Curl_http_done: called premature. I can't find any documentation on what it means and am wondering if my service is not conforming to some http spec?</p>

```<code>➜  ~ git:(master) ✗ curl localhost:6764/health -vv
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 6764 (#0)
> GET /health HTTP/1.1
> Host: localhost:6764
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< content-encoding: application/json
< content-length: 16
< connection: close
<
{"status":"ok"}
* Curl_http_done: called premature == 0
* Closing connection 0
</code>```

答:
Curl_http_done: called premature == 0 was just a debug message, it served no real purpose for ordinary humans, only to libcurl developers...

It was removed in curl 7.53.0 (released Feb 22 2017)

(The debug output told if the transfer ended "naturally" or if something made it it end before it was originally intended to. So the premature would be 1 on such errors and 0 if everything was fine.)

Title: Curl_http_done: called premature

Body:
I'm building a new service, and when I curl it I see a message Curl_http_done: called premature. I can't find any documentation on what it means and am wondering if my service is not conforming to some http spec?

➜  ~ git:(master) ✗ curl localhost:6764/health -vv
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 6764 (#0)
> GET /health HTTP/1.1
> Host: localhost:6764
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< content-encoding: application/json
< content-length: 16
< connection: close
<
{"status":"ok"}
* Curl_http_done: called premature == 0
* Closing connection 0


答:
Simplest option:    </p>

```<code>$('div.spaceEvent[data-event-id="112"]')
</code>```

Title: Select element with div and class and data attribute

Body:
Simplest option:

$('div.spaceEvent[data-event-id="112"]')


问:
SceneKit editor set custom class for node
In the SpriteKit editor, I can assign a custom class to an SKNode, like so:

However,  I can't seem to find the equivalent functionality in the SceneKit editor. Does it even exist? And if I can't set a custom class for an SCNNode, is there a reason the feature isn't there, or has the Xcode team just not gotten around to it? (In other words, should I file a radar?)

答:
You can't do it in the scene editor. And you probably shouldn't do it at all. You'll have to implement your own serialization code (so that SCNScene loading works correctly). And all of the methods for searching nodes (by name, hit test, within a volume) return SCNNode, so you'll be forever casting your results.

Per Apple developers, SCNScene is not meant to be subclassed, and I think that extends to SCNNode. Write an extension instead.

See:

Trouble subclassing SCNScene

Subclassing SCNNode

Subclassing SCNScene and SceneKit Editor


问:
Makefile for project with code in multiple directories but same directory structure
I have the following directory structure for a C++ project:

```<code>.
├── bin
├── build
├── include
│   ├── dir1
│   │   ├── file1.hpp
│   │   └── file2.hpp
│   ├── dir2
│   │   ├── file3.hpp
│   │   └── file4.hpp
│   └── third_party
│       └── catch.hpp
├── Makefile
├── src
│   ├── dir1
│   │   ├── file1.cpp
│   │   └── file2.cpp
│   └── dir2
│       ├── file3.cpp
│       └── file4.cpp
└── test
    ├── dir1
    │   ├── file1.test.cpp
    │   └── file2.test.cpp
    └── dir2
        ├── file3.test.cpp
        └── file4.test.cpp
</code>```

How can I write the Makefile to compile the code in src and test directories and obtain the object files in the build directory and the binaries in the bin directory, maintaining the same directory structure within them, without having to name every file and its dependency explicitly? Would it be better to use multiple Makefiles in each dir* within src and test?

My Makefile currently looks like this: (it's probably nonsensical, sorry about that!)

```<code>binaries_dir = bin
build_dir = build
sources_dir = src
include_dir = include

compile_flags = -std=c++14 -Wall

binaries := $(wildcard *.out)
objects := $(wildcard *.o)
sources := $(wildcard *.cpp)
headers := $(wildcard *.hpp)

objects: $(sources)
    g++ $(compile_flags) -c $(sources_dir)/$(sources) -I $(include_dir)

binaries: $(objects)
    for object in $(objects); do
        g++ $(compile_flags) -o $(binaries_dir)/ $(build_dir)/$object
    done
</code>```

答:
I don't think this is fool proof but I think it pretty much does what you are after. You should study up on building Makefiles because it this turns out not to quite fit your needs, how are you going to fix it?

CXX := g++
RM  := rm -f
MD  := mkdir -p

# don't change, this is for dependencies
CXXFLAGS += -MMD -MP

# add compiler flags here
CXXFLAGS += -std=c++14 -pedantic-errors
CXXFLAGS += -Wall -Wextra
CXXFLAGS += -g3 -O0

# add external includes here
CPPFLAGS += -Iinclude

# add library flags here
LDFLAGS +=

DIRS := $(patsubst  src/%, %, $(wildcard  src/*))
DIRS += $(patsubst test/%, %, $(wildcard test/*))
PROG_SOURCES := $(wildcard  src/*/*.cpp)
TEST_SOURCES := $(wildcard test/*/*.cpp)
OBJECTS := $(patsubst  src/%.cpp, build/%.o, $(PROG_SOURCES))
OBJECTS += $(patsubst test/%.cpp, build/%.o, $(TEST_SOURCES))
EXECUTABLES := $(patsubst  src/%.cpp, bin/%, $(PROG_SOURCES))
EXECUTABLES += $(patsubst test/%.cpp, bin/%, $(TEST_SOURCES))
DEPENDENCIES := $(patsubst   src/%.cpp, build/%.d, $(PROG_SOURCES))
DEPENDENCIES += $(patsubst  test/%.cpp, build/%.d, $(TEST_SOURCES))

all: dirs $(EXECUTABLES)

build/%.o: src/%.cpp
    $(CXX) -c $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

build/%.o: test/%.cpp
    $(CXX) -c $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

bin/%: build/%.o
    $(CXX) $(CXXFLAGS) -o $@ $< $(LDFLAGS)

-include $(DEPENDENCIES)

clean:
    @echo Removing build files
    @$(RM) $(EXECUTABLES) $(OBJECTS) $(DEPENDENCIES)

dirs:
    @$(MD) $(patsubst %, build/%, $(DIRS)) $(patsubst %, bin/%, $(DIRS))

.PHONY: show dirs
```

Body:
I have the following directory structure for a C++ project:

.
├── bin
├── build
├── include
│   ├── dir1
│   │   ├── file1.hpp
│   │   └── file2.hpp
│   ├── dir2
│   │   ├── file3.hpp
│   │   └── file4.hpp
│   └── third_party
│       └── catch.hpp
├── Makefile
├── src
│   ├── dir1
│   │   ├── file1.cpp
│   │   └── file2.cpp
│   └── dir2
│       ├── file3.cpp
│       └── file4.cpp
└── test
    ├── dir1
    │   ├── file1.test.cpp
    │   └── file2.test.cpp
    └── dir2
        ├── file3.test.cpp
        └── file4.test.cpp

How can I write the Makefile to compile the code in src and test directories and obtain the object files in the build directory and the binaries in the bin directory, maintaining the same directory structure within them, without having to name every file and its dependency explicitly? Would it be better to use multiple Makefiles in each dir* within src and test?

My Makefile currently looks like this: (it's probably nonsensical, sorry about that!)

binaries_dir = bin
build_dir = build
sources_dir = src
include_dir = include

compile_flags = -std=c++14 -Wall

binaries := $(wildcard *.out)
objects := $(wildcard *.o)
sources := $(wildcard *.cpp)
headers := $(wildcard *.hpp)

objects: $(sources)
    g++ $(compile_flags) -c $(sources_dir)/$(sources) -I $(include_dir)

binaries: $(objects)
    for object in $(objects); do
        g++ $(compile_flags) -o $(binaries_dir)/ $(build_dir)/$object
    done