问:
Normalize data frame by levels
Good evening,

I am still new to R, so sorry in advance if this question seems obvious to you.
I am currently working on a drug screening protocol and I created .csv table in Excel with the output of my analysis. I imported it as data frame as raw.data into R with the following structure:

```<code>| Sample        | Group | Parameter Drug 1 | Parameter Drug 2 | Time Parameter Drug 1 (ms) |
|---------------|-------|------------------|------------------|----------------------------|
| Heart_Sample1 | Heart | 2.4              | 9.0              | 1.5                        |
| Heart_Sample1 | Heart | 2.29             | 22.2             | 3.4                        |
| Heart_Sample1 | Heart | 3.4              | 3.5              | 4.5                        |
| Heart_Sample1 | Heart | 5.2              | 8.4              | 6.5                        |
| Heart_Sample1 | Heart | 2.3              | 34.1             | 7.8                        |
| ...           | Organ | value            | value            | time                       |
| Heart_Sample2 | Heart | 10.4             | 10.2             | 1.5                        |
| Heart_Sample2 | Heart | 8.4              | 2.45             | 3.6                        |
| ...           | Organ | value            | value            | time                       |
| Liver_Sample1 | Liver | 13.4             | 44.5             | 2.8                        |
| ...           | Organ | 2.3              | value            | time                       |
</code>```

Parameter indicates the value of a certain parameter I am experimentally measuring (e.g. neuronal spikes). Time of Parameter indicates the time of the recording at which the spikes occur.

I transformed raw.data into mod.data with gather with the following formula:

```<code>  mod.data <- gather(raw.data, `Parameter Drug 1`, `Parameter Drug 2`, `Parameter Drug 3`, key = "Drug", value = "value")

| Sample        | Group | Time Parameter Drug 1 (ms) | Drug            | value |
|---------------|-------|----------------------------|-----------------|-------|
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 2 |       |
</code>```

Then I generated the plots, separated by Sample and , in order to have a clear overview of what is happening to the parameter, over time, in all the samples. The results is a huge plot array, with ~200 plots.

Since different organs have different values, and also within the same organ I can find very different values, the scales have to be matched within each Sample to clearly understand what is going in the sample.

I then tried to normalize with the following function:

```<code>    normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
  }
</code>```

Where x is my parameter of interest. Unfortunately, it takes as min and max the respective min and max of the whole Parameter, regardless of the Sample and the Group. I also try to subset, but it would mean to create a single subset for each Sample and then merge them together in a figure. I also try with group_by(Sample, Group), as described in the RStudio cheatsheet, but I was not able to apply the normalize function to the generated data frame.

tl;dr My question is: how can I normalize, from 0 to 1, within each Sample, my values?

Thank you in advance for the answers.

Regards

答:
Using data.table you could go about this using the following approach.

Toy example:

```<code>library(data.table)
normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
}

df <- data.table(group = c(1, 1, 1, 1, 2, 2, 2), measure = c(10, 20, 0, 2, 1, 1, 10))
df[, measure_normalized := normalize(measure), by = group]
</code>```

Title: Normalize data frame by levels

Body:
Good evening,

I am still new to R, so sorry in advance if this question seems obvious to you.
I am currently working on a drug screening protocol and I created .csv table in Excel with the output of my analysis. I imported it as data frame as raw.data into R with the following structure:

| Sample        | Group | Parameter Drug 1 | Parameter Drug 2 | Time Parameter Drug 1 (ms) |
|---------------|-------|------------------|------------------|----------------------------|
| Heart_Sample1 | Heart | 2.4              | 9.0              | 1.5                        |
| Heart_Sample1 | Heart | 2.29             | 22.2             | 3.4                        |
| Heart_Sample1 | Heart | 3.4              | 3.5              | 4.5                        |
| Heart_Sample1 | Heart | 5.2              | 8.4              | 6.5                        |
| Heart_Sample1 | Heart | 2.3              | 34.1             | 7.8                        |
| ...           | Organ | value            | value            | time                       |
| Heart_Sample2 | Heart | 10.4             | 10.2             | 1.5                        |
| Heart_Sample2 | Heart | 8.4              | 2.45             | 3.6                        |
| ...           | Organ | value            | value            | time                       |
| Liver_Sample1 | Liver | 13.4             | 44.5             | 2.8                        |
| ...           | Organ | 2.3              | value            | time                       |

Parameter indicates the value of a certain parameter I am experimentally measuring (e.g. neuronal spikes). Time of Parameter indicates the time of the recording at which the spikes occur.

I transformed raw.data into mod.data with gather with the following formula:

  mod.data <- gather(raw.data, `Parameter Drug 1`, `Parameter Drug 2`, `Parameter Drug 3`, key = "Drug", value = "value")

| Sample        | Group | Time Parameter Drug 1 (ms) | Drug            | value |
|---------------|-------|----------------------------|-----------------|-------|
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Baseline        |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 1 |       |
| Heart_Sample1 | Heart |                            | Concentration 2 |       |

Then I generated the plots, separated by Sample and , in order to have a clear overview of what is happening to the parameter, over time, in all the samples. The results is a huge plot array, with ~200 plots.

Since different organs have different values, and also within the same organ I can find very different values, the scales have to be matched within each Sample to clearly understand what is going in the sample.

I then tried to normalize with the following function:

    normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
  }

Where x is my parameter of interest. Unfortunately, it takes as min and max the respective min and max of the whole Parameter, regardless of the Sample and the Group. I also try to subset, but it would mean to create a single subset for each Sample and then merge them together in a figure. I also try with group_by(Sample, Group), as described in the RStudio cheatsheet, but I was not able to apply the normalize function to the generated data frame.

tl;dr My question is: how can I normalize, from 0 to 1, within each Sample, my values?

Thank you in advance for the answers.

Regards

Body:
Using data.table you could go about this using the following approach.

Toy example:

library(data.table)
normalize <- function(x){
  (x - min(x))/(max(x)-min(x))
}

df <- data.table(group = c(1, 1, 1, 1, 2, 2, 2), measure = c(10, 20, 0, 2, 1, 1, 10))
df[, measure_normalized := normalize(measure), by = group]


来源: stackexchange

问:
Issue with background color and Google Chrome
Sometimes I get a broken background in Chrome. I do not get this error with any other browser.

This is the simple CSS line responsible for the background color of body:

```<code>body
{
   background: black;
   color: white;
   font-family: Chaparral Pro, lucida grande, verdana, sans-serif;
}
</code>```

This is exactly how I get this problem. I click a link included in an Gmail's email and I get something wrong (no background). I then refresh the page and the background is colored completely.

How do fix this problem?

答:
I would try what Logan and 1mdm suggested, tho tweak the CSS, but I would really wait for a new Chrome version to come out with fixed bugs, before growing white hair.  </p>

<p>IMHO the current Chrome version is still alpha version and was released so that it can spread while it is in development. I personally had issues with table widths, my code worked fine in EVERY browser but could not make it work in Chrome.  </p>

OwnerDisplayName: Sergio del Amo

ContentLicense: CC BY-SA 3.0

Body:
Sometimes I get a broken background in Chrome. I do not get this error with any other browser.

This is the simple CSS line responsible for the background color of body:

body
{
   background: black;
   color: white;
   font-family: Chaparral Pro, lucida grande, verdana, sans-serif;
}

This is exactly how I get this problem. I click a link included in an Gmail's email and I get something wrong (no background). I then refresh the page and the background is colored completely.

How do fix this problem?

Body:
I would try what Logan and 1mdm suggested, tho tweak the CSS, but I would really wait for a new Chrome version to come out with fixed bugs, before growing white hair.

IMHO the current Chrome version is still alpha version and was released so that it can spread while it is in development. I personally had issues with table widths, my code worked fine in EVERY browser but could not make it work in Chrome.

OwnerDisplayName: Germstorm

ContentLicense: CC BY-SA 2.5


问:
"abline" doesn't work after "plot" when inside "with"
I want to create a scatterplot and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

```<code>with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))
</code>```

What is the correct way to give a command like this? Can I do it with a one-liner?

答:
From ?with: with ... evaluates expr in a local environment created using data.  You're passing abline() via ....  You need to do something like this:

```<code>with(subset(CO2,Type=="Quebec"),{plot(conc,uptake);abline(lm(uptake~conc))})
</code>```

Body:
I want to create a scatterplot and draw the regression line for a subset of a dataset. To give a reproducible example I'll use the CO2 dataset.

I tried this but the regression line doesn't appear for some reason

with(subset(CO2,Type=="Quebec"),plot(conc,uptake),abline(lm(uptake~conc)))

What is the correct way to give a command like this? Can I do it with a one-liner?

Body:
From ?with: with ... evaluates expr in a local environment created using data.  You're passing abline() via ....  You need to do something like this:

with(subset(CO2,Type=="Quebec"),{plot(conc,uptake);abline(lm(uptake~conc))})


问:
Dynamically add row in TableView grouped style
I have TableView grouped style with 3 section, I need dynamically add row to this section. When I add:

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
</code>```

It's okay, but when I change number numberOfRowsInSection I got error:

```<code>2017-03-29 04:21:42.032 TableView-Grouped[81597:7624167] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106cc5d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000103fd821e objc_exception_throw + 48
    2   CoreFoundation                      0x0000000106d1ec2f
</code>```

My code:

```<code>import UIKit

class ViewController: UITableViewController {

    var arr = ["Row 1", "Row 2", "Row 3"]
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.reloadData()

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = arr[indexPath.row]
        return cell
    }

}
</code>```

enter image description here

答:
When i add a row for my custom TableView i need to reload manually the data for the rows:

```<code>//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

//swift 3
DispatchQueue.main.async{
    self.tableView.reloadData()
}
</code>```

If you have a function that append the data arr need to reload in that moment like:

```<code> func refresh() {
        //remove if need
        arr.removeAll()
        self.GetData()
        DispatchQueue.main.async(execute: {
            self.myTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)

        })
    }
</code>```

Body:
I have TableView grouped style with 3 section, I need dynamically add row to this section. When I add:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

It's okay, but when I change number numberOfRowsInSection I got error:

2017-03-29 04:21:42.032 TableView-Grouped[81597:7624167] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106cc5d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000103fd821e objc_exception_throw + 48
    2   CoreFoundation                      0x0000000106d1ec2f

My code:

import UIKit

class ViewController: UITableViewController {

    var arr = ["Row 1", "Row 2", "Row 3"]
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.reloadData()

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = arr[indexPath.row]
        return cell
    }

}

enter image description here

Body:
When i add a row for my custom TableView i need to reload manually the data for the rows:

//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

//swift 3
DispatchQueue.main.async{
    self.tableView.reloadData()
}

If you have a function that append the data arr need to reload in that moment like:

 func refresh() {
        //remove if need
        arr.removeAll()
        self.GetData()
        DispatchQueue.main.async(execute: {
            self.myTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)

        })
    }


问:
PHP fopen write filename with php variable and file extension
I have a variable $id from URL parameter that contains a name ID-number like 1234.5Z

How can I use fopen to write a file called 1234.5Z.json?

I tried the following syntax:

```<code>$fp = fopen($id+'.json', 'w');
</code>```

But I end up with a file named 1243.5

答:
In PHP, you don't concatenate strings using the + sign, you use the . instead.

So, your code will look more like

```<code>$fp = fopen($id . '.json', 'w');
</code>```

What happens when you were using the +, is that PHP was thinking you were doing an arithmetic operation, and thus, it does it's best to parse the number within the first string, and as a result 1234.5Z -> 1234.5, and .json -> 0, and therein 1234.5 + 0 = 1234.5, which then will be used as the string for the name.

Body:
I have a variable $id from URL parameter that contains a name ID-number like 1234.5Z

How can I use fopen to write a file called 1234.5Z.json?

I tried the following syntax:

$fp = fopen($id+'.json', 'w');

But I end up with a file named 1243.5

Body:
In PHP, you don't concatenate strings using the + sign, you use the . instead.

So, your code will look more like

$fp = fopen($id . '.json', 'w');

What happens when you were using the +, is that PHP was thinking you were doing an arithmetic operation, and thus, it does it's best to parse the number within the first string, and as a result 1234.5Z -> 1234.5, and .json -> 0, and therein 1234.5 + 0 = 1234.5, which then will be used as the string for the name.


问:
Place holder not working in textarea
I am using this code to display placeholder:

```<code> <input type="email" name="email" value="Email" onfocus="if(this.value=='Email')this.value='';" onblur="if(this.value=='')this.value='Email';">
<textarea onfocus="if(this.value=='Message')this.value='';" onblur="if(this.value=='')this.value='Message';"> </textarea>
</code>```

Placeholder is displaying in input field, but not displaying in textarea.

Here is my page link where I am using this code.
http://realinvestors.businesscatalyst.com/contact.html

答:
For IE 11 users

In IE11 my textarea was rendering the placeholder text as innerhtml, here is one way you can work around the issue

```<code>// IE 11 Hack
handleTextAreaClick(event) {
  if (event.currentTarget.innerHTML === event.currentTarget.placeholder) {
    event.currentTarget.innerHTML = ''
  }
}
</code>```

Not the most elegant of solutions but it works for my case. The problem was that IE treats placeholder text as innerHTML - more info here

https://connect.microsoft.com/IE/feedback/details/811408

Title: Place holder not working in textarea

Body:
I am using this code to display placeholder:

 <input type="email" name="email" value="Email" onfocus="if(this.value=='Email')this.value='';" onblur="if(this.value=='')this.value='Email';">
<textarea onfocus="if(this.value=='Message')this.value='';" onblur="if(this.value=='')this.value='Message';"> </textarea>

Placeholder is displaying in input field, but not displaying in textarea.

Here is my page link where I am using this code.
http://realinvestors.businesscatalyst.com/contact.html

Body:
For IE 11 users

In IE11 my textarea was rendering the placeholder text as innerhtml, here is one way you can work around the issue

// IE 11 Hack
handleTextAreaClick(event) {
  if (event.currentTarget.innerHTML === event.currentTarget.placeholder) {
    event.currentTarget.innerHTML = ''
  }
}

Not the most elegant of solutions but it works for my case. The problem was that IE treats placeholder text as innerHTML - more info here

https://connect.microsoft.com/IE/feedback/details/811408


问:
Is it possible to create Interactive voice response systems from home, if so, what is the best solution
I am trying to build an IVR and hook it up to my website, what are the different (inexpensive) ways that I can do it. </p>

答: I would use Twilio open vbx It's pretty easy, easy to customize, and cheap</p>


问:
Git changes to a visual studio .csproj file don't reflect as changes to the origin. Why?

On master branch, I did a git pull to get the latest changes to master

Then I did git checkout -b new_branch

On this branch I deleted a few lines to a .csproj file

The diff showed the correct change, i.e.

zach@DESKTOP...:<path>$ git diff master, showed:

```<code>diff --git a/<path>.csproj
index 58a5da4..8062eb5 100644
--- a/<path>.csproj
+++ b/<path>.csproj
@@ -79,9 +79,6 @@
     <None Include="App.config">
       <SubType>Designer</SubType>
     </None>
-    <None Include="env-config.json">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-    </None>
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="<path>.csproj">
</code>```

Then I ran git add .

Then I ran git commit -m "new changes added"

Then I ran git push

At this point I expected to be prompted to --set-upstream a path. But instead I got back a message that said everything was up-to-date.

Looking at the source on Bitbucket, neither the new branch with the recently committed change, nor the change itself in the master branch appeared.

Why is this?

I should note that I'm using the Windows 10 implementation of bash (i.e. a virtualized Ubuntu 14.04 machine), but changes to regular source code seem to work fine.

I'm also running Windows 10 Home on an Apple by Bootcamp.

答:
When the command line does not specify where to push with the
   argument, branch.*.remote configuration for the current
  branch is
         consulted to determine where to push. If the configuration is missing, it defaults to origin.

When the command line does not specify what to push with ... arguments or --all, --mirror, --tags options, the command
  finds the default
          by consulting remote.*.push configuration, and if it is not found, honors push.default configuration to decide what to push
  (See git-
         config(1) for the meaning of push.default).

When neither the command-line nor the configuration specify what to push, the default behavior is used, which corresponds to the
  simple value for
         push.default: the current branch is pushed to the corresponding upstream branch, but as a safety measure, the push is aborted if the
  upstream branch
         does not have the same name as the local one.

This means, when the new created branch not already exists and is the current one for the remote, that the push is aborted

Body:
On master branch, I did a git pull to get the latest changes to master

Then I did git checkout -b new_branch

On this branch I deleted a few lines to a .csproj file

The diff showed the correct change, i.e.

zach@DESKTOP...:<path>$ git diff master, showed:

diff --git a/<path>.csproj
index 58a5da4..8062eb5 100644
--- a/<path>.csproj
+++ b/<path>.csproj
@@ -79,9 +79,6 @@
     <None Include="App.config">
       <SubType>Designer</SubType>
     </None>
-    <None Include="env-config.json">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-    </None>
   </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="<path>.csproj">

Then I ran git add .

Then I ran git commit -m "new changes added"

Then I ran git push

At this point I expected to be prompted to --set-upstream a path. But instead I got back a message that said everything was up-to-date.

Looking at the source on Bitbucket, neither the new branch with the recently committed change, nor the change itself in the master branch appeared.

Why is this?

I should note that I'm using the Windows 10 implementation of bash (i.e. a virtualized Ubuntu 14.04 machine), but changes to regular source code seem to work fine.

I'm also running Windows 10 Home on an Apple by Bootcamp.


问:
Launch ec2 instance with chef
I started working recently on chef. I want to launch ec2 instance in my aws account using chef.
I have chef workstation(windows), chef node(windows 2012 R2), and chef server.
I need information about this, can anyone suggest me?</p>

答:
There are 2 approaches:

1) https://github.com/chef/chef-provisioning-aws
  This one uses gem "aws-sdk", this is most right way of doing provisioning in AWS cloud. In this case you must have in your ChefDK's Gemfile: "chef-provisioning-aws" gem

2) https://github.com/chef/chef-provisioning-fog
  This provisioning solution is based on "Fog" gem and in fact it is multi-cloud solution and supports many popular clouds. To use that you must have in your ChefDK's Gemfile: "chef-provisioning-fog" gem

Please, see the README, it has clear explanation, but the common steps are:

Set credentials via ENV[] or create profile for AWS in home directory of user

Call machine resource with right machine_options and driver

Here is an example, in your recipe/provider/library you can do:

```<code>ENV['AWS_REGION'] = 'eu-central-1'
ENV['AWS_ACCESS_KEY_ID'] = 'YOUR_KEY_HERE'
ENV['AWS_SECRET_ACCESS_KEY'] = 'YOUR_SECRET_KEY_HERE'

require 'chef/provisioning/aws_driver'
with_driver 'aws::eu-central-1'

machine 'instance-1' do
  action :converge
  machine_options :machine_options => {REFER TO MACHINE OPTIONS}
end
</code>```

Title: Launch ec2 instance with chef

Body:
There are 2 approaches:

1) https://github.com/chef/chef-provisioning-aws
  This one uses gem "aws-sdk", this is most right way of doing provisioning in AWS cloud. In this case you must have in your ChefDK's Gemfile: "chef-provisioning-aws" gem

2) https://github.com/chef/chef-provisioning-fog
  This provisioning solution is based on "Fog" gem and in fact it is multi-cloud solution and supports many popular clouds. To use that you must have in your ChefDK's Gemfile: "chef-provisioning-fog" gem

Please, see the README, it has clear explanation, but the common steps are:

Set credentials via ENV[] or create profile for AWS in home directory of user

Call machine resource with right machine_options and driver

Here is an example, in your recipe/provider/library you can do:

ENV['AWS_REGION'] = 'eu-central-1'
ENV['AWS_ACCESS_KEY_ID'] = 'YOUR_KEY_HERE'
ENV['AWS_SECRET_ACCESS_KEY'] = 'YOUR_SECRET_KEY_HERE'

require 'chef/provisioning/aws_driver'
with_driver 'aws::eu-central-1'

machine 'instance-1' do
  action :converge
  machine_options :machine_options => {REFER TO MACHINE OPTIONS}
end


问:
Where are examples for the latest Neo4j codebase?
http://neo4j.com/docs/java-reference/current/
... seems old.
Section 4.2 points to a dead link.

Starting with version 3.0, I can't find examples on github.
https://github.com/neo4j/neo4j/tree/3.0/community

Where are they?

答: The first link to the java reference should be current for 3.1. As far as the broken link, there's a /manual/ part of the path which really shouldn't be there, try this instead.


问:
Use regular expression to find and replace the string from Textfield in NSString
I would like to use regular expression to find and replace the string. In my scenario {3} and {2} are UITextField tag values. Based on the tag value, I would like to replace the respective textfield values and calculate the string value using NSExpression.

Sample Input String :

```<code>NSString *cumputedValue = @"{3}*0.42/({2}/100)^2";
</code>```

Note: The textFields are created dynamically based on JSON response.

答:
I got the answer for this question. Here the computedString contains the value as "{3}*0.42/({2}/100)^2".</p>

```<code>- (NSString *)autoCalculationField: (NSString *)computedString {
    NSString *computedStringFormula = [NSString stringWithFormat:@"%@",computedString];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\d+)\\}"
                                                                           options:0
                                                                             error:nil];
    NSArray *matches = [regex matchesInString:computedStringFormula
                                      options:0
                                        range:NSMakeRange(0, computedStringFormula.length)];
    NSString *expressionStr = computedStringFormula;
    for (NSTextCheckingResult *r in matches)
    {
        NSRange numberRange = [r rangeAtIndex:1];
        NSString *newString = [NSString stringWithFormat:@"%.2f",[self getInputFieldValue:[computedStringFormula substringWithRange:numberRange]]];
        expressionStr = [expressionStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"{%@}",[computedStringFormula substringWithRange:numberRange]] withString:newString];
    }
    NSExpression *expression = [NSExpression expressionWithFormat:expressionStr];
    return [expression expressionValueWithObject:nil context:nil];
}

- (float)getInputFieldValue: (NSString *)tagValue {
    UITextField *tempTextFd = (UITextField *)[self.view viewWithTag:[tagValue intValue]];
    return [tempTextFd.text floatValue];
}
</code>```

Body:
I would like to use regular expression to find and replace the string. In my scenario {3} and {2} are UITextField tag values. Based on the tag value, I would like to replace the respective textfield values and calculate the string value using NSExpression.

Sample Input String :

NSString *cumputedValue = @"{3}*0.42/({2}/100)^2";

Note: The textFields are created dynamically based on JSON response.

Body:
I got the answer for this question. Here the computedString contains the value as "{3}*0.42/({2}/100)^2".

- (NSString *)autoCalculationField: (NSString *)computedString {
    NSString *computedStringFormula = [NSString stringWithFormat:@"%@",computedString];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\d+)\\}"
                                                                           options:0
                                                                             error:nil];
    NSArray *matches = [regex matchesInString:computedStringFormula
                                      options:0
                                        range:NSMakeRange(0, computedStringFormula.length)];
    NSString *expressionStr = computedStringFormula;
    for (NSTextCheckingResult *r in matches)
    {
        NSRange numberRange = [r rangeAtIndex:1];
        NSString *newString = [NSString stringWithFormat:@"%.2f",[self getInputFieldValue:[computedStringFormula substringWithRange:numberRange]]];
        expressionStr = [expressionStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"{%@}",[computedStringFormula substringWithRange:numberRange]] withString:newString];
    }
    NSExpression *expression = [NSExpression expressionWithFormat:expressionStr];
    return [expression expressionValueWithObject:nil context:nil];
}

- (float)getInputFieldValue: (NSString *)tagValue {
    UITextField *tempTextFd = (UITextField *)[self.view viewWithTag:[tagValue intValue]];
    return [tempTextFd.text floatValue];
}


问:
In AngularJS, any inline javascript code that included in HTML templates doesn't work
In AngularJS, any inline javascript code that included in HTML templates doesn't work.

For Example:

main.html file:

```<code><div ng-include="'/templates/script.html'"></div>
</code>```

And script.html file:

```<code><script type="text/javascript">
    alert('yes');
</script>
</code>```

When I open main page, I expect an alert message that say 'yes' but nothing happens. I think some security restrictions in the AngularJS is preventing inline scripts, but I couldn't find any workaround about that.

Note: I don't use jQuery or any other framework, only AngularJS 1.2.7.

答: Include jQuery and change order of the angular.js and jquery.js. jQuery must be first, otherwise it does not work

Body:
In AngularJS, any inline javascript code that included in HTML templates doesn't work.

For Example:

main.html file:

And script.html file:

When I open main page, I expect an alert message that say 'yes' but nothing happens. I think some security restrictions in the AngularJS is preventing inline scripts, but I couldn't find any workaround about that.

Note: I don't use jQuery or any other framework, only AngularJS 1.2.7.


问:
How to replace numbers in a div?
With the following code, I'm getting the values of "id"(almost 35), and then add 1 to each "id", so 1 will be 2 and so on. Where I'm stock, it is on how to replace that id number in the html.

This is the code that use to get the values of each id, then I push them into an array, then I run another "for loop" to add 1 to each value, but I don't how to return them to the html.

var x = document.getElementsByClassName('p-divs');

var portfolio = new Array;

for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    portfolio.push(y);
}

console.log(portfolio);

var portfolio2 = new Array;

for (var i = 0; i<portfolio.length; i++)
{
    var newId;
    newId = parseInt(portfolio[i]) + 1;

    portfolio2.push(newId);
}

console.log(portfolio2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 p-divs" id="1">
  <div class="portfolio">
    <center>
      <img src="images/pace.png" width="230" height="190" alt="" class="img-responsive">
    </center>
  </div>
</div></code>```

答:
I'd suggest, assuming I'm not missing something, and that you're able to us ES6 methods:

```<code>// converting the NodeList returned from document.querySelectorAll()
// into an Array, and iterating over that Array using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('.p-divs') ).forEach(

  // using an Arrow function to work with the current element
  // (divElement) of the Array of elements,
  // here we use parseInt() to convert the id of the current
  // element into a number (with no sanity checking), adding 1
  // and assigning that result to be the new id:
  divElement => divElement.id = parseInt( divElement.id, 10 ) + 1
);
</code>```

Note that updating, changing or otherwise modifying an id shouldn't be necessary in most circumstances, and having a purely numeric id may present problems for CSS selecting those elements (it's valid, but only in HTML 5, but will still be problematic).

Title: How to replace numbers in a div?

Body:
I'd suggest, assuming I'm not missing something, and that you're able to us ES6 methods:

// converting the NodeList returned from document.querySelectorAll()
// into an Array, and iterating over that Array using
// Array.prototype.forEach():
Array.from( document.querySelectorAll('.p-divs') ).forEach(

  // using an Arrow function to work with the current element
  // (divElement) of the Array of elements,
  // here we use parseInt() to convert the id of the current
  // element into a number (with no sanity checking), adding 1
  // and assigning that result to be the new id:
  divElement => divElement.id = parseInt( divElement.id, 10 ) + 1
);

Note that updating, changing or otherwise modifying an id shouldn't be necessary in most circumstances, and having a purely numeric id may present problems for CSS selecting those elements (it's valid, but only in HTML 5, but will still be problematic).


问:
including leading whitespaces when using fgets in php
I am using PHP to read a simple text file with the fgets() command:

```<code>$file = fopen("filename.txt", "r") or exit('oops');
$data = "";

while(!feof($file)) {
    $data .= fgets($file) . '<br>';
}

fclose($file);
</code>```

The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:

```<code>$data = str_replace(" ", " ", $data);
</code>```

Not sure where to go from here.

Thanks in advance,

Doug

UPDATE:

The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.

答:
I currently have the same requirement and experienced that some characters are written as a tab character.

What i did was:

```<code>$tabChar = '    ';
$regularChar = ' '

$file = fopen('/file.txt');
while($line = fgets($file)) {

   $l = str_replace("\t", $tabChar, $line);
   $l = str_replace(" ", $regularChar, $line);
   // ...
   // replacing can be done till it matches your needs

   $lines .= $l; // maybe append <br /> if neccessary

}

$result = '<pre'> . $lines . '```';
```

This one worked for me, maybe it helps you too :-).

Body:
I am using PHP to read a simple text file with the fgets() command:

$file = fopen("filename.txt", "r") or exit('oops');
$data = "";

while(!feof($file)) {
    $data .= fgets($file) . '
';
}

fclose($file);

The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:

$data = str_replace(" ", " ", $data);

Not sure where to go from here.

Thanks in advance,

Doug

UPDATE:

The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.

Body:
I currently have the same requirement and experienced that some characters are written as a tab character.

What i did was:

$tabChar = '&nbsp;&nbsp;&nbsp;&nbsp;';
$regularChar = '&nbsp;'

$file = fopen('/file.txt');
while($line = fgets($file)) {

   $l = str_replace("\t", $tabChar, $line);
   $l = str_replace(" ", $regularChar, $line);
   // ...
   // replacing can be done till it matches your needs

   $lines .= $l; // maybe append <br /> if neccessary

}

$result = '<pre'> . $lines . '</pre>';

This one worked for me, maybe it helps you too :-).


问:
Forcing Cache refresh after deploying new code
We are running into issue where our clients are served stale js, css files after  code is deployed. We are using IIS as our webserver and our code is in ASP.Net 4.5. I did some research and figured out that ETag in conjunction with Cache-control should work. As I understand ETag is automatically generated by web server based on datetime stamp of file so I ran following steps to see why the system is not sending the latest version of js and css files.

Navigated to my website to a webpage let's call is demo.aspx.(Now assuming that demo.aspx contains reference to a.js, b.js and c.css)

Verified that a.js, b.js and c.css file were requested by browser and webserver delivered those files after I hard refersh a page(Ctrl + F5) on my website.

Clicked on some other webpage

Went to webserve and manually updated files (a.js, b.js and c.css to update datetime stamp of those files)

Navigated to demo.aspx again.

This time I see only request made to demo.aspx but not to any of the resource file (a.js, b.js and c.css).

I am at loss as to why .js files are not requested when I access my demo.aspx page.

Also, Is there any easy way to force client browsers to download latest version of .js and .css files every time I deploy code. Based on my research, I did find out that one way to do would be to rename .js and .css file. Please note that this soution won't work for us.

We do use update panel in our projects. Not sure if that has anything to do with browser not requesting js files second time

答:
A widely used trick is to add a query string parameter that is incremented with every new version of the css or js file.

Like myScript.js?version=12. When the the number changes the browser sees it as a new file and it's downloaded rather than retrieved from cache.

Just changing the timestamp by editing the file won't work, the browser does not get the timestamp from the server. You can try this by saving an image or file from the website, they all have the timestamp of when they were being downloaded.


问:
Is this crypto code thread safe?
I have a pool of immutable encryption helper objects which contain instances of the java JCA Cipher and MessageDigest objects:

```<code>AlgorithmInstance( Cipher encCipher, Cipher decCipher, MessageDigest digest ) { ... }
private BlockingQueue< AlgorithmInstance > pool = new ArrayBlockingQueue< AlgorithmInstance >(poolSize);
</code>```

Various threads in my application, needing encryption or decryption, contend for AlgorithmInstance objects by accessing a pool.  Each thread uses them to encrypt or decrypt, and then returns them to the pool when they are done.  Threads don't synchronize on any of JCA objects since there is no concurrent access.  Decrypt works roughly the same way.

```<code>public byte[] encryptMessage( byte data[] ) { ...
 try {
  AlgorithmInstance inst = pool.take();

  inst.digest.reset();
  byte[] digest = inst.digest.digest(message);

  inst.encryptCipher.init( Cipher.ENCRYPT_MODE, m_currentKey, ivParams );
  inst.encryptCipher.doFinal( messageBuffer );
 }
 finally {
  pool.put(inst)
 }
}
</code>```

This works 99.99% of the time; and 100% of the time in unit tests.  However, once in a blue moon, I get a message whose computed digest does not come out right -- normally this indicates message tampering or network errors; but sender and receiver are on the same machine (in different processes).

Q: Is there some internal state for a Cipher or Digest which can suffer from memory consistency effects -- I'm on a 2 core windows box so I don't see how I could even suffer from memory consistency effects.  I re-initialize the cipher and digest each call so it should not matter.

Q: Is there any way I could have ended up with a padding mode that sometimes fails based on the message length?  The decryptor and encryptor use exactly the same algorithms (AES/CBC/Pkcs5Padding + SHA-256, and a key size of 128).

答:
I changed the code so that I synchronize on the AlgorithmInstance while I use any of its contained objects.  I have not seen this problem since; however its not clear why; since the queue.put() and queue.take() operations should form EXACTLY the same happens-before relationship formed by the monitor unlock:

```<code>synchronized (inst) {
 ...
 // do crypto opperations
}
</code>```

The only other possibility I can come up with is that the IVParamSpec is modified during the Cipher.init() computation and then restored at the end.  Since the ivParams are assumed read only and shared across all objects in the pool, if true, this could lead to un-synchronized access and possibly MCE.

Title: Is this crypto code thread safe?

Body:
I have a pool of immutable encryption helper objects which contain instances of the java JCA Cipher and MessageDigest objects:

AlgorithmInstance( Cipher encCipher, Cipher decCipher, MessageDigest digest ) { ... }
private BlockingQueue< AlgorithmInstance > pool = new ArrayBlockingQueue< AlgorithmInstance >(poolSize);

Various threads in my application, needing encryption or decryption, contend for AlgorithmInstance objects by accessing a pool.  Each thread uses them to encrypt or decrypt, and then returns them to the pool when they are done.  Threads don't synchronize on any of JCA objects since there is no concurrent access.  Decrypt works roughly the same way.

public byte[] encryptMessage( byte data[] ) { ...
 try {
  AlgorithmInstance inst = pool.take();

  inst.digest.reset();
  byte[] digest = inst.digest.digest(message);

  inst.encryptCipher.init( Cipher.ENCRYPT_MODE, m_currentKey, ivParams );
  inst.encryptCipher.doFinal( messageBuffer );
 }
 finally {
  pool.put(inst)
 }
}

This works 99.99% of the time; and 100% of the time in unit tests.  However, once in a blue moon, I get a message whose computed digest does not come out right -- normally this indicates message tampering or network errors; but sender and receiver are on the same machine (in different processes).

Q: Is there some internal state for a Cipher or Digest which can suffer from memory consistency effects -- I'm on a 2 core windows box so I don't see how I could even suffer from memory consistency effects.  I re-initialize the cipher and digest each call so it should not matter.

Q: Is there any way I could have ended up with a padding mode that sometimes fails based on the message length?  The decryptor and encryptor use exactly the same algorithms (AES/CBC/Pkcs5Padding + SHA-256, and a key size of 128).

Body:
I changed the code so that I synchronize on the AlgorithmInstance while I use any of its contained objects.  I have not seen this problem since; however its not clear why; since the queue.put() and queue.take() operations should form EXACTLY the same happens-before relationship formed by the monitor unlock:

synchronized (inst) {
 ...
 // do crypto opperations
}

The only other possibility I can come up with is that the IVParamSpec is modified during the Cipher.init() computation and then restored at the end.  Since the ivParams are assumed read only and shared across all objects in the pool, if true, this could lead to un-synchronized access and possibly MCE.


问:
How to align the button right next to the search box
I am trying to align the search button right next to the search box however button seems to be below. This is what I got:</p>

```<code>        <form action="{linkto page="search.php"}" method="get" id="searchFormTest">
           <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" value="{$lang.enterKeywords}" placeholder="Suchbegriff oder Bildnummer">
              <div style="display: inline;">
                <button type="submit" value="Submit">
                  <i style="font-size: 40px;" class="fa fa-search" aria-hidden="true"></i>
               </button>
              </div>
        </form>
</code>```

答:
Float your search input to the left, float your submit button to the left. Ready. </p>

```<code>input[type="search"],
button {
    float: left;
}
</code>```

Body:
I am trying to align the search button right next to the search box however button seems to be below. This is what I got:

        <form action="{linkto page="search.php"}" method="get" id="searchFormTest">
           <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" value="{$lang.enterKeywords}" placeholder="Suchbegriff oder Bildnummer">

                <button type="submit" value="Submit">

               </button>

        </form>

Body:
Float your search input to the left, float your submit button to the left. Ready.

input[type="search"],
button {
    float: left;
}


答:
Since you're using jQuery library the code could be simple than what you've so far using .each() method :

```<code>$('.p-divs').each(function(){
  $(this).attr('id', Number(this.id) + 1);
});
</code>```

Or shorter using using .attr() method callback like :

```<code>$('.p-divs').attr('id', function(){
    return Number(this.id) + 1;
});
</code>```

The more clear version could be :

```<code>$('.p-divs').each(function(){
  var current_id = Number(this.id); //Get current id
  var new_id = current_id + 1;  //Increment to define the new one

  $(this).attr('id', new_id); //Set the new_id to the current element 'id'
});
</code>```

Hope this helps.

$(function(){
  $('.p-divs').attr('id', function(){
    return Number(this.id) + 1;
  });

  //Just for Debug
  console.log( $('body').html() );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="p-divs" id="1">
  <div class="portfolio">
    <center>Image 1</center>
  </div>
</div>
<div class="p-divs" id="2">
  <div class="portfolio">
    <center>Image 2</center>
  </div>
</div>
<div class="p-divs" id="3">
  <div class="portfolio">
    <center>Image 3</center>
  </div>
</div>
<div class="p-divs" id="4">
  <div class="portfolio">
    <center>Image 4</center>
  </div>
</div></code>```

Title: How to replace numbers in a div?

Body:
With the following code, I'm getting the values of "id"(almost 35), and then add 1 to each "id", so 1 will be 2 and so on. Where I'm stock, it is on how to replace that id number in the html.

This is the code that use to get the values of each id, then I push them into an array, then I run another "for loop" to add 1 to each value, but I don't how to return them to the html.

var x = document.getElementsByClassName('p-divs');

var portfolio = new Array;

for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    portfolio.push(y);
}

console.log(portfolio);

var portfolio2 = new Array;

for (var i = 0; i<portfolio.length; i++)
{
    var newId;
    newId = parseInt(portfolio[i]) + 1;

    portfolio2.push(newId);
}

console.log(portfolio2);

Body:
Since you're using jQuery library the code could be simple than what you've so far using .each() method :

$('.p-divs').each(function(){
  $(this).attr('id', Number(this.id) + 1);
});

Or shorter using using .attr() method callback like :

$('.p-divs').attr('id', function(){
    return Number(this.id) + 1;
});

The more clear version could be :

$('.p-divs').each(function(){
  var current_id = Number(this.id); //Get current id
  var new_id = current_id + 1;  //Increment to define the new one

  $(this).attr('id', new_id); //Set the new_id to the current element 'id'
});

Hope this helps.

$(function(){
  $('.p-divs').attr('id', function(){
    return Number(this.id) + 1;
  });

  //Just for Debug
  console.log( $('body').html() );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="p-divs" id="1">
  <div class="portfolio">
    <center>Image 1</center>
  </div>
</div>
<div class="p-divs" id="2">
  <div class="portfolio">
    <center>Image 2</center>
  </div>
</div>
<div class="p-divs" id="3">
  <div class="portfolio">
    <center>Image 3</center>
  </div>
</div>
<div class="p-divs" id="4">
  <div class="portfolio">
    <center>Image 4</center>
  </div>
</div>


问:
Changes in package.json for Angular 2 to 4 migration
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

```<code>"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}
</code>```

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

```<code>{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}
</code>```

答:
You shouldn't need to make changes to ts.config.
The changes you have in package.json seem to be correct.

Couple of points:

I think "typescript" should be in the "devDependencies" since you won't need that in prod mode.

I recommend removing "^" from all your dependencies b.c. it's better to lock down the exact version

I also highly recommend using "shrinkwrap" to avoid loose dependencies within your dependencies.

To install Angular latest version, remove/move your current node_modules folder. Then:

```<code>npm cache clean
npm install
</code>```

For reference, see the section 'Updating to 4.0.0'
http://angularjs.blogspot.com/2017/03/angular-400-now-available.html

Body:
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}

Body:
You shouldn't need to make changes to ts.config.
The changes you have in package.json seem to be correct.

Couple of points:

I think "typescript" should be in the "devDependencies" since you won't need that in prod mode.

I recommend removing "^" from all your dependencies b.c. it's better to lock down the exact version

I also highly recommend using "shrinkwrap" to avoid loose dependencies within your dependencies.

To install Angular latest version, remove/move your current node_modules folder. Then:

npm cache clean
npm install

For reference, see the section 'Updating to 4.0.0'
http://angularjs.blogspot.com/2017/03/angular-400-now-available.html


问:
Is an Android ViewParent guaranteed to be a Viewgroup?
Is there any real case where View.getParent() returns an object that is not of type ViewGroup ? Or can I safely cast it without checking its type first like in my code sample below ?

```<code> if (getParent() == null){
     throw new IllegalStateException("View does not have a parent, it cannot be rootview!");
 }
 ViewGroup parent = (ViewGroup) getParent();
</code>```

答: If you aren't doing anything fancy, it should be safe. The only unsafe case is when you reach the root of your view hiearchy. The ViewParent will then be a ViewRootImpl</p>

Body:
Is there any real case where View.getParent() returns an object that is not of type ViewGroup ? Or can I safely cast it without checking its type first like in my code sample below ?

 if (getParent() == null){
     throw new IllegalStateException("View does not have a parent, it cannot be rootview!");
 }
 ViewGroup parent = (ViewGroup) getParent();


问:
Can't get POST value from AJAX
Can't get value of filter. Don't know why. Am I doing AJAX wrong?
For the record, I'm new to ajax and have looked many places, with many not getting real answers to the same issue.

JQUERY: index.php

```<code>$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    });
});
</code>```

HTML: index.php

```<code><div>
    <div>
        <? include($_SERVER['DOCUMENT_ROOT']."/news/news.php"); ?>
    </div>
</div>
</code>```

PHP: news.php

```<code>$sbFilter = $_POST['filter'];
echo "select* from test_table where status='3'and ('". $sbFilter."') ORDER BY  `test_table`.`date` DESC, nid DESC   limit 0 , 6"
</code>```

Console Log:

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 36

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php on line 36

// HERE IS MY ECHO
select* from test_table where status='3'and press<>1 and ('some value') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 42

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php

On the page, I get:

select* from test_table where status='3' and ('') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

答:
You're probably not looking at the right place to see if your php code is returning the correct value. Your AJAX request only asks for data, but does not do anything with it, you're not saving it in a variable, using it in a callback function or modifying your webpage.

You could do something like:

```<code>$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    }).done(function(data) {
         // Do something with your data here, say output to console
         console.log(data);
    });
});
</code>```

This only outputs the server output to console, you're gonna have to do something else in order to see a change in your webpage. What you do here is up to you and what you want to see exactly.

You should be able to view the server response as well on the network tabs of whatever browser you use.

As for your question updates:

First off, you should be using mysqli functions, not mysql as they are deprecated.

In any case, you need to create a connection object, which evidently you're not using from your warning error (see here for an example of both these points).

Most importantly, you're not sanitizing your inputs or using prepared statements (see the last link for an example with these). If you don't do this, you're opening yourself up to SQL injection.

As for your webpage not having any changes, you have two problems here:

You need to have your JS do something with server output.

You're not using mysqli correctly to perform queries.

The solution to 1 is modifying the console.log part of the callback function to modify a webpage.

The solution to 2 is using the MySQL php interface correctly.

To reiterate, please look into prepared statements and reformulate your queries, they're very important and a very simple element to implement for a comparatively big security boost.

Title: Can't get POST value from AJAX

Body:
Can't get value of filter. Don't know why. Am I doing AJAX wrong?
For the record, I'm new to ajax and have looked many places, with many not getting real answers to the same issue.

JQUERY: index.php

$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    });
});

HTML: index.php

        <? include($_SERVER['DOCUMENT_ROOT']."/news/news.php"); ?>

PHP: news.php

$sbFilter = $_POST['filter'];
echo "select* from test_table where status='3'and ('". $sbFilter."') ORDER BY  `test_table`.`date` DESC, nid DESC   limit 0 , 6"

Console Log:

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 36

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php on line 36

// HERE IS MY ECHO
select* from test_table where status='3'and press<>1 and ('some value') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Warning:  mysql_query() [function.mysql-query]: Access denied for user ''@'localhost' (using password: NO) in /home/news/news.php on line 42

Warning:  mysql_query() [function.mysql-query]: A link to the server could not be established in /home/news/news.php

On the page, I get:

select* from test_table where status='3' and ('') ORDER BY  test_table.date DESC, nid DESC   limit 0 , 6

Body:
You're probably not looking at the right place to see if your php code is returning the correct value. Your AJAX request only asks for data, but does not do anything with it, you're not saving it in a variable, using it in a callback function or modifying your webpage.

You could do something like:

$(document).ready(function(){
    $.ajax({
        url: 'news.php',
        type: "POST",
        data: {filter:'some value'},
    }).done(function(data) {
         // Do something with your data here, say output to console
         console.log(data);
    });
});

This only outputs the server output to console, you're gonna have to do something else in order to see a change in your webpage. What you do here is up to you and what you want to see exactly.

You should be able to view the server response as well on the network tabs of whatever browser you use.

As for your question updates:

First off, you should be using mysqli functions, not mysql as they are deprecated.

In any case, you need to create a connection object, which evidently you're not using from your warning error (see here for an example of both these points).

Most importantly, you're not sanitizing your inputs or using prepared statements (see the last link for an example with these). If you don't do this, you're opening yourself up to SQL injection.

As for your webpage not having any changes, you have two problems here:

You need to have your JS do something with server output.

You're not using mysqli correctly to perform queries.

The solution to 1 is modifying the console.log part of the callback function to modify a webpage.

The solution to 2 is using the MySQL php interface correctly.

To reiterate, please look into prepared statements and reformulate your queries, they're very important and a very simple element to implement for a comparatively big security boost.


问:
Java-based Config that creates Parameterized Singleton Spring Bean
I have the following list of bean definitions in XML:

```<code><bean id="version201627" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="27"/>
</bean>

<bean id="version201628" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="28"/>
</bean>

... // the list goes on
</code>```

Is there a way to convert this to Java-based @Configuration, and not creating so many methods?

something like:

```<code>@Bean
public ClientVersionPredicate somePredicate(String year, String week) {
    return new ClientVersionPredicate(year, week);
}
</code>```

but I can specify the args somewhere? Thanks.

答:
This can be done using a BeanDefinitionRegistryPostProcessor (Javadoc) and a BeanDefinitionBuilder.

```<code>@Component
public class ClientVersionPredicateDefiner implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
            throws BeansException {
        // no need for post processing
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
            throws BeansException {
        IntStream.range(27, 47).forEach(week -> {
            String year = "2016";
            BeanDefinitionBuilder builder = BeanDefinitionBuilder
                    .genericBeanDefinition(ClientVersionPredicate.class);
            builder.addPropertyValue("year", year);
            builder.addPropertyValue("week", String.valueOf(week));
            registry.registerBeanDefinition("version" + year + week,
                    builder.getBeanDefinition());
        });
    }

}
</code>```

For this example, I assumed you were needing a version for weeks 27 to 46 in the year 2016. How you define your configuration values is up to you (and depending on your actual configuration needs).

The beans can now be obtained by name:

```<code>ClientVersionPredicate version201627 = ctx.getBean("version201627");
ClientVersionPredicate version201628 = ctx.getBean("version201628");
...
</code>```

Body:
I have the following list of bean definitions in XML:

<bean id="version201627" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="27"/>
</bean>

<bean id="version201628" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="28"/>
</bean>

... // the list goes on

Is there a way to convert this to Java-based @Configuration, and not creating so many methods?

something like:

@Bean
public ClientVersionPredicate somePredicate(String year, String week) {
    return new ClientVersionPredicate(year, week);
}

but I can specify the args somewhere? Thanks.

Body:
This can be done using a BeanDefinitionRegistryPostProcessor (Javadoc) and a BeanDefinitionBuilder.

@Component
public class ClientVersionPredicateDefiner implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
            throws BeansException {
        // no need for post processing
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
            throws BeansException {
        IntStream.range(27, 47).forEach(week -> {
            String year = "2016";
            BeanDefinitionBuilder builder = BeanDefinitionBuilder
                    .genericBeanDefinition(ClientVersionPredicate.class);
            builder.addPropertyValue("year", year);
            builder.addPropertyValue("week", String.valueOf(week));
            registry.registerBeanDefinition("version" + year + week,
                    builder.getBeanDefinition());
        });
    }

}

For this example, I assumed you were needing a version for weeks 27 to 46 in the year 2016. How you define your configuration values is up to you (and depending on your actual configuration needs).

The beans can now be obtained by name:

ClientVersionPredicate version201627 = ctx.getBean("version201627");
ClientVersionPredicate version201628 = ctx.getBean("version201628");
...


问:
SQL, MS access VBA update
I would like to seek help in my update statement in ms access. I don't know if possible but can we incorporate SELECT statement in UPDATE statement?

Here's the code that I have problem.

```<code>  DoCmd.RunSQL _
        "UPDATE tab_lists " & _
        "SET " & _
        "total_calls                = ((SELECT COUNT(filler3) FROM table WHERE [attempt_counter] = 5)  " & _
        "WHERE " & _
        "listid                     = " & listid1 & ""
</code>```

答:
Yes, you can.

I prefer CurrentDb.Execute:

CurrentDb.Execute ("UPDATE tab_lists SET total_calls = (SELECT COUNT(filler3) AS CountFill FROM table WHERE [attempt_counter] = 5) WHERE listid = " & listid1)

However, saving aggregate data is usually a bad idea. Should just calculate when needed.

Your table is named table? That is also not good.

Title: SQL, MS access VBA update

Body:
I would like to seek help in my update statement in ms access. I don't know if possible but can we incorporate SELECT statement in UPDATE statement?

Here's the code that I have problem.

  DoCmd.RunSQL _
        "UPDATE tab_lists " & _
        "SET " & _
        "total_calls                = ((SELECT COUNT(filler3) FROM table WHERE [attempt_counter] = 5)  " & _
        "WHERE " & _
        "listid                     = " & listid1 & ""


问:
SQL - Select latest messages on a chat table
i'm currently trying to make an online chat with Ajax and the messages are sent via a php file to my database. I would like to be able to list all the conversations where a user is involved. Let's take this as an example :
exemple of table

I would like to list the conversations ordered from the most recent one to the oldest.

I should have conversation with user 25846.... since it's the last message, then with 10206...... and finally with 11627.....

My desired output is a table of 3 records with the fields ID_to and content_msg, order as above.
This is the current SQL request i'm trying :

```<code>SELECT DISTINCT ID_to
FROM (
    SELECT *
    FROM messages
    WHERE ID_to = 1140816689329214 OR ID_from = 1140816689329214
    ORDER BY timestamp_msg DESC
    ) as tmp
</code>```

Even with this the output is not in the right order, and I can't understand why since I have a order by on my request.

Thank you in advance for any help

答:
Ordering is determined by the ORDER BY in the outermost query.  Ordering in subqueries doesn't matter.

This would seem to be what you want:

```<code>SELECT id_to
FROM messages
WHERE ID_to = 1140816689329214 OR ID_from = 1140816689329214
GROUP BY id_to
ORDER BY MAX(timestamp_msg) DESC;
</code>```

Body:
i'm currently trying to make an online chat with Ajax and the messages are sent via a php file to my database. I would like to be able to list all the conversations where a user is involved. Let's take this as an example :
exemple of table

I would like to list the conversations ordered from the most recent one to the oldest.

I should have conversation with user 25846.... since it's the last message, then with 10206...... and finally with 11627.....

My desired output is a table of 3 records with the fields ID_to and content_msg, order as above.
This is the current SQL request i'm trying :

SELECT DISTINCT ID_to
FROM (
    SELECT *
    FROM messages
    WHERE ID_to = 1140816689329214 OR ID_from = 1140816689329214
    ORDER BY timestamp_msg DESC
    ) as tmp

Even with this the output is not in the right order, and I can't understand why since I have a order by on my request.

Thank you in advance for any help

Body:
Ordering is determined by the ORDER BY in the outermost query.  Ordering in subqueries doesn't matter.

This would seem to be what you want:

SELECT id_to
FROM messages
WHERE ID_to = 1140816689329214 OR ID_from = 1140816689329214
GROUP BY id_to
ORDER BY MAX(timestamp_msg) DESC;


问:
trying to display a list of data in a datagrid
I'm trying to display a list of data in a WPF data grid because a textblock just threw the data together without any type of formatting (this is me hoping that formatting of this data is done for me).

This is the code behind

```<code>public void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
    try
    {
        if (e == null)
            return;

        if (e.CmsData != null)
        {
            List<string> mylist = new List<string>();
            foreach (var item in e.CmsData.Agents)
            {
                mylist.Add(item.AgName);
                mylist.Add(item.AuxReasonDescription);
            }
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                this.datagrid.ItemsSource = mylist;
            }));
        }
    }
}
</code>```

The XAML I'm using to populate the data grid

```<code><Grid Height="100" Width="178.201">
    <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Path=mylist, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"   x:Name="datagrid" Background="{x:Null}" Loaded="textBlock_Loaded"/>
</Grid>
</code>```

this is the agents.cs file that has variables i'm trying to pull into my data grid just incase it is needed.

```<code>public class Agent : IEquatable<Agent>
{
    public int Extension { get; set; }
    public int WorkModeDirection { get; set; }
    public string WorkModeDirectionDescription { get; set; }
    public TimeSpan AgTime { get; set; }
    public int AuxReason { get; set; }
    public string AuxReasonDescription { get; set; }
    public int DaInQueue { get; set; }
    public int WorkSkill { get; set; }
    public int OnHold { get; set; }
    public int Acd { get; set; }
    public String LoginId { get; set; }
    public string AgName { get; set; }
    public int EId { get; set; }
    public int Preference { get; set; }
    public DateTime DateTimeCreated { get; set; }
    public DateTime DateTimeUpdated { get; set; }
    public int CmId { get; set; }
    #region Implementation of IEquatable<Agent>

    public bool Equals(Agent other)
    {
        if (ReferenceEquals(null, other))
            return false;

        if (ReferenceEquals(this, other))
            return true;

        return (other.LoginId == LoginId & other.CmId == CmId);
    }

    #endregion

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
            return false;

        if (ReferenceEquals(this, obj))
            return true;

        if (obj.GetType() != typeof(Agent))
            return false;

        return Equals((Agent)obj);
    }

    //public override int GetHashCode()
    //{
    //    return LoginId;
    //}
    public override int GetHashCode()
    {
        string combinedNumber = "" + CmId + LoginId;
        int hash = Convert.ToInt32(combinedNumber);
        return hash;
    }

    public static bool operator ==(Agent left, Agent right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(Agent left, Agent right)
    {
        return !Equals(left, right);
    }

    public override string ToString()
    {
        return " Ag: [Ext:" + Extension + " login:" + LoginId + " AgName:" + AgName + " CmId:" + CmId + "]";
    }
    public bool IsValid()
    {
        return LoginId != null;
    }
}
</code>```

This is what is currently being displayed...of which contains no information that I am telling it to print out and I have no idea where the numbers are coming from.

答:
You should set the ItemsSource of the DataGrid to a List<Agent>:

```<code>public void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
    try
    {
        if (e == null)
            return;

        if (e.CmsData != null)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                this.datagrid.ItemsSource = e.CmsData.Agents.ToList();
            }));
        }
    }
}
</code>```

...and define a column for each property of the Agent class that you want to display in the DataGrid in your XAML markup:

```<code><DataGrid AutoGenerateColumns="False"
                      x:Name="datagrid" Background="{x:Null}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="AgName" Binding="{Binding AgName}" />
        <DataGridTextColumn Header="AuxReasonDescription" Binding="{Binding AuxReasonDescription}" />
    </DataGrid.Columns>
</DataGrid>
</code>```

Body:
I'm trying to display a list of data in a WPF data grid because a textblock just threw the data together without any type of formatting (this is me hoping that formatting of this data is done for me).

This is the code behind

public void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
    try
    {
        if (e == null)
            return;

        if (e.CmsData != null)
        {
            List<string> mylist = new List<string>();
            foreach (var item in e.CmsData.Agents)
            {
                mylist.Add(item.AgName);
                mylist.Add(item.AuxReasonDescription);
            }
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                this.datagrid.ItemsSource = mylist;
            }));
        }
    }
}

The XAML I'm using to populate the data grid

<Grid Height="100" Width="178.201">
    <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding Path=mylist, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"   x:Name="datagrid" Background="{x:Null}" Loaded="textBlock_Loaded"/>
</Grid>

this is the agents.cs file that has variables i'm trying to pull into my data grid just incase it is needed.

public class Agent : IEquatable<Agent>
{
    public int Extension { get; set; }
    public int WorkModeDirection { get; set; }
    public string WorkModeDirectionDescription { get; set; }
    public TimeSpan AgTime { get; set; }
    public int AuxReason { get; set; }
    public string AuxReasonDescription { get; set; }
    public int DaInQueue { get; set; }
    public int WorkSkill { get; set; }
    public int OnHold { get; set; }
    public int Acd { get; set; }
    public String LoginId { get; set; }
    public string AgName { get; set; }
    public int EId { get; set; }
    public int Preference { get; set; }
    public DateTime DateTimeCreated { get; set; }
    public DateTime DateTimeUpdated { get; set; }
    public int CmId { get; set; }
    #region Implementation of IEquatable<Agent>

    public bool Equals(Agent other)
    {
        if (ReferenceEquals(null, other))
            return false;

        if (ReferenceEquals(this, other))
            return true;

        return (other.LoginId == LoginId & other.CmId == CmId);
    }

    #endregion

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj))
            return false;

        if (ReferenceEquals(this, obj))
            return true;

        if (obj.GetType() != typeof(Agent))
            return false;

        return Equals((Agent)obj);
    }

    //public override int GetHashCode()
    //{
    //    return LoginId;
    //}
    public override int GetHashCode()
    {
        string combinedNumber = "" + CmId + LoginId;
        int hash = Convert.ToInt32(combinedNumber);
        return hash;
    }

    public static bool operator ==(Agent left, Agent right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(Agent left, Agent right)
    {
        return !Equals(left, right);
    }

    public override string ToString()
    {
        return " Ag: [Ext:" + Extension + " login:" + LoginId + " AgName:" + AgName + " CmId:" + CmId + "]";
    }
    public bool IsValid()
    {
        return LoginId != null;
    }
}

This is what is currently being displayed...of which contains no information that I am telling it to print out and I have no idea where the numbers are coming from.

Body:
You should set the ItemsSource of the DataGrid to a List<Agent>:

public void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
    try
    {
        if (e == null)
            return;

        if (e.CmsData != null)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                this.datagrid.ItemsSource = e.CmsData.Agents.ToList();
            }));
        }
    }
}

...and define a column for each property of the Agent class that you want to display in the DataGrid in your XAML markup:

<DataGrid AutoGenerateColumns="False"
                      x:Name="datagrid" Background="{x:Null}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="AgName" Binding="{Binding AgName}" />
        <DataGridTextColumn Header="AuxReasonDescription" Binding="{Binding AuxReasonDescription}" />
    </DataGrid.Columns>
</DataGrid>


问:
SQL Server 2012: am I missing something when working with an If-Else if-Else block?
Overall I am attempting to look through an auditing table to see if a specific date range has already been processed. In this specific case, @fstartrangedate will be NULL, as the 2016-11-01 start date has not been found. This should make it to the main else condition. @superceded should be set to 0, @type (sumtype) should be set to WEEKLY, @days should be set to 7.

I make it to the correct main else condition. Even make it to Weekly -- and yet, somehow @type is set to SPECIAL.

Can someone please take a look @this. I've probably done something really silly, but I just don't see it.

Here's the code:

```<code>-- determine if this is a daily, weekly, monthly or special run
declare @superceded bit
declare @type varchar(50)
declare @foundSameStartDate bit
declare @days int
declare @vdays int
declare @fLoadId int

-- incoming parameters
declare @startrangedate date
declare @endrangedate date

-- found startdate
declare @fstartrangedate date

--debug
select @fstartrangedate as fstartrangedate

-- validation test --
declare @vstartrangedate date
declare @vendrangedate date

set @startrangedate = cast('2016-11-01' as date);
-- debug
select @startrangedate as startrangedate

set @endrangedate = cast('2016-11-08' as date);

select
    @fstartrangedate = StartRangeDateTime,
    @fLoadId = LoadId
from
    FleetMatching.Audit_LoadTracker
where
    StartRangeDateTime IN (select StartRangeDateTime
                           from FleetMatching.Audit_LoadTracker
                           where IsSuperceded = 0
                             and IsLoadCompleted = 1
                             and StartRangeDateTime = @startrangedate)

 -- debug
 select @fstartrangedate as fstartrangedate

 IF(@fstartrangedate is not null)
 BEGIN
     print 'found start date does = startdate'
     -- valid start/end dates for a full month

     select @vstartrangedate = dateadd(month, datediff(month, 0, @startrangedate), 0)
     select @vendrangedate = dateadd(day, -1, dateadd(month, datediff(month, -1, @startrangedate), 0))

     select @days =  datediff(day, @startrangedate, @endrangedate)
     select @vdays = datediff(day, @vstartrangedate, @vendrangedate)

     -- we found an existing range which will be superseded by this
     -- execution/load
     set @superceded = 1

  -- debug
  select @days as [Days]
  select @type as SumType

  if(@days = 1)
    set @type = 'DAILY'
  else if(@days = 7)
    set @type = 'WEEKLY'
  else if((@days >= 27) AND (@days <= 31))
    set @type = 'MONTHLY'
  else
    print 'found condition-special'
    set @type = 'SPECIAL'
  END
ELSE
 Begin
  print 'Reached MAIN-IF Else Condition'
  print 'found start date does NOT .eq. startdate'
  set @superceded = 0
  select @days = datediff(day,@startrangedate,@endrangedate)
  -- debug
  select @days as [Days]
  select @type as SumType

  if(@days = 0)
    begin
     print 'daily as 0'
     set @type = 'DAILY'
    end
  else if(@days = 7)
    begin
      print 'weekly as 7';
      set @type = 'WEEKLY';
    end
  else if(@days >= 28 AND @days <= 31)
   begin
     print 'monthly as 28->31'
     set @type = 'MONTHLY'
   end
  else
    print 'else condition=special'
    set @type = 'SPECIAL'
 END

 -- DEBUG
 select @superceded as IsSuperceded
 select @type as SumType
</code>```

Here are the debug output messages when executed:

```<code> (1 row(s) affected)

 (1 row(s) affected)

 (1 row(s) affected)

 Reached MAIN-IF Else Condition

 found start date does NOT .eq. startdate

 (1 row(s) affected)

 (1 row(s) affected)

 weekly as 7

 (1 row(s) affected)

 (1 row(s) affected)*
</code>```

Here are the variable output messages when executed:

答:
Let me introduce you to my buddy case!

```<code>set @type = case
     when @days = 0 then 'Daily'
     when @days = 7 then 'Weekly'
     when @days >=28 and @days <= 31 then 'Monthly'
     else 'Special'
     end;
</code>```

The error is here:

```<code>if (@days = 0)
 begin
  print 'daily as 0'
  set @type = 'DAILY'
 end
 else if (@days = 7)
 begin
  print 'weekly as 7';
  set @type = 'WEEKLY';
 end
 else if (@days >= 28 and @days <= 31)
 begin
  print 'monthly as 28->31'
  set @type = 'MONTHLY'
 end
 else
  print 'else condition=special' /* < -----
                       without begin and end, else stops after the print
                       and the following `set` is outside of the flow control */
 set @type = 'SPECIAL'
</code>```

Ironically, you would not have had (found?) that error if you were not debugging your code with those print statements.

rextester demo to show the error, and how begin/end would fix it: http://rextester.com/CSUM92647

Body:
Overall I am attempting to look through an auditing table to see if a specific date range has already been processed. In this specific case, @fstartrangedate will be NULL, as the 2016-11-01 start date has not been found. This should make it to the main else condition. @superceded should be set to 0, @type (sumtype) should be set to WEEKLY, @days should be set to 7.

I make it to the correct main else condition. Even make it to Weekly -- and yet, somehow @type is set to SPECIAL.

Can someone please take a look @this. I've probably done something really silly, but I just don't see it.

Here's the code:

-- determine if this is a daily, weekly, monthly or special run
declare @superceded bit
declare @type varchar(50)
declare @foundSameStartDate bit
declare @days int
declare @vdays int
declare @fLoadId int

-- incoming parameters
declare @startrangedate date
declare @endrangedate date

-- found startdate
declare @fstartrangedate date

--debug
select @fstartrangedate as fstartrangedate

-- validation test --
declare @vstartrangedate date
declare @vendrangedate date

set @startrangedate = cast('2016-11-01' as date);
-- debug
select @startrangedate as startrangedate

set @endrangedate = cast('2016-11-08' as date);

select
    @fstartrangedate = StartRangeDateTime,
    @fLoadId = LoadId
from
    FleetMatching.Audit_LoadTracker
where
    StartRangeDateTime IN (select StartRangeDateTime
                           from FleetMatching.Audit_LoadTracker
                           where IsSuperceded = 0
                             and IsLoadCompleted = 1
                             and StartRangeDateTime = @startrangedate)

 -- debug
 select @fstartrangedate as fstartrangedate

 IF(@fstartrangedate is not null)
 BEGIN
     print 'found start date does = startdate'
     -- valid start/end dates for a full month

     select @vstartrangedate = dateadd(month, datediff(month, 0, @startrangedate), 0)
     select @vendrangedate = dateadd(day, -1, dateadd(month, datediff(month, -1, @startrangedate), 0))

     select @days =  datediff(day, @startrangedate, @endrangedate)
     select @vdays = datediff(day, @vstartrangedate, @vendrangedate)

     -- we found an existing range which will be superseded by this
     -- execution/load
     set @superceded = 1

  -- debug
  select @days as [Days]
  select @type as SumType

  if(@days = 1)
    set @type = 'DAILY'
  else if(@days = 7)
    set @type = 'WEEKLY'
  else if((@days >= 27) AND (@days <= 31))
    set @type = 'MONTHLY'
  else
    print 'found condition-special'
    set @type = 'SPECIAL'
  END
ELSE
 Begin
  print 'Reached MAIN-IF Else Condition'
  print 'found start date does NOT .eq. startdate'
  set @superceded = 0
  select @days = datediff(day,@startrangedate,@endrangedate)
  -- debug
  select @days as [Days]
  select @type as SumType

  if(@days = 0)
    begin
     print 'daily as 0'
     set @type = 'DAILY'
    end
  else if(@days = 7)
    begin
      print 'weekly as 7';
      set @type = 'WEEKLY';
    end
  else if(@days >= 28 AND @days <= 31)
   begin
     print 'monthly as 28->31'
     set @type = 'MONTHLY'
   end
  else
    print 'else condition=special'
    set @type = 'SPECIAL'
 END

 -- DEBUG
 select @superceded as IsSuperceded
 select @type as SumType

Here are the debug output messages when executed:

 (1 row(s) affected)

 (1 row(s) affected)

 (1 row(s) affected)

 Reached MAIN-IF Else Condition

 found start date does NOT .eq. startdate

 (1 row(s) affected)

 (1 row(s) affected)

 weekly as 7

 (1 row(s) affected)

 (1 row(s) affected)*

Here are the variable output messages when executed:

Body:
Let me introduce you to my buddy case!

set @type = case
     when @days = 0 then 'Daily'
     when @days = 7 then 'Weekly'
     when @days >=28 and @days <= 31 then 'Monthly'
     else 'Special'
     end;

The error is here:

if (@days = 0)
 begin
  print 'daily as 0'
  set @type = 'DAILY'
 end
 else if (@days = 7)
 begin
  print 'weekly as 7';
  set @type = 'WEEKLY';
 end
 else if (@days >= 28 and @days <= 31)
 begin
  print 'monthly as 28->31'
  set @type = 'MONTHLY'
 end
 else
  print 'else condition=special' /* < -----
                       without begin and end, else stops after the print
                       and the following `set` is outside of the flow control */
 set @type = 'SPECIAL'

Ironically, you would not have had (found?) that error if you were not debugging your code with those print statements.

rextester demo to show the error, and how begin/end would fix it: http://rextester.com/CSUM92647


问:
How can I make my background colour for section 1/2 fill full screen?
How can I make my background colour for section 1/2 fill full screen?

http://codepen.io/ldocherty1/pen/KWGWxz

```<code><div id="sections">

        <div class="section one">

        <a href="#section two"> <i class="fa fa-angle-down" style="font-size:100px;"></i></a>

        </div>
        <div class="section two"></div>
    </div>
</code>```

答:
You want to use the VH length unit in CSS, this stand for Viewport Height and there is also its counterpart vw which stands for Viewport Width.

A quick example with these would be:

CSS:

```<code>div {
     display:block;
     height: 50vh;
     background-color:#c00;
}
</code>```

HTML:

```<code><div>
This div will take up 50% height of the viewport that contains it</div>
</code>```

Without seeing your CSS code in the question I can't give you an absolute answer but you will learn more by playing with your code yourself, with this knowledge. To make a
 half the screen height simply set: div { height: 50vh; }.

(you may have to set things like min-height as well and/or take into account other more-complex CSS flow things depending on your exact DOM structure)

Body:
You want to use the VH length unit in CSS, this stand for Viewport Height and there is also its counterpart vw which stands for Viewport Width.

A quick example with these would be:

CSS:

div {
     display:block;
     height: 50vh;
     background-color:#c00;
}

HTML:

<div>
This div will take up 50% height of the viewport that contains it</div>

Without seeing your CSS code in the question I can't give you an absolute answer but you will learn more by playing with your code yourself, with this knowledge. To make a <div> half the screen height simply set: div { height: 50vh; }.

(you may have to set things like min-height as well and/or take into account other more-complex CSS flow things depending on your exact DOM structure)


问:
Interactive Quiz: How to keep input values when hidden?
I've created an interactive quiz and created functions that showed the next question and goes back to the previous questions. My problem is that when it changes questions, the information I input in is erased. For example Question 1 and 2, I would write in an animal and then I go onto Question 3, but when I go back to Question 1 and 2, the animals I wrote in are gone. Same with the radio choices. Sorry if code is tedious, I'm just starting. Any tips on how I can fix that?

Quiz link: https://repl.it/GSiI/latest

```<code>    function initialize()
    {
      questionList = document.getElementsByClassName("questions");
      quizOutput = document.getElementById("showQuiz");
      beginBtn = document.getElementById("initiate");
      button = document.getElementById("button");
      next = document.getElementById("next");
      previous = document.getElementById("previous");
      questionIndex = 0;
      totalQuestions = questionList.length - 1;
    }

    function beginQuiz()
    {
     currentQuestion = questionList.item(questionIndex).innerHTML;
     button.style.visibility = "visible";
     quizOutput.innerHTML = currentQuestion;
     beginBtn.style.display = "none";
     quizOutput.style.display = "block";
    }

    function changeQuestion(factor)
    {
       if(factor == -1 && questionIndex > 0)
       {
        questionIndex--;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
       if(factor == 1 && questionIndex < totalQuestions)
       {
        questionIndex++;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
   }

    function writeNumber(el, num)
    {
     input = document.getElementById(el);
        if(input.value.length < 2)
        {
            input.value += num;
        }
    }

    function clearAnswer(el)
    {
     document.getElementById(el).value = "";
    }

    function takeValues()
    {
     var x = document.getElementById("frm1");
     var text = "";
     var i;
     for (i = 0; i < x.length ;i++)
        {
          text += x.elements[i].value + "<br>";
        }
     document.getElementById("demo").innerHTML = text;
    }
</code>```

答: Its because every time you load a different question, you are actually removing the DOM elements without saving them.  When you return to the previous questions, you aren't loading their values from anywhere.  You need to build a state into your app for it to work.</p>

Body:
I've created an interactive quiz and created functions that showed the next question and goes back to the previous questions. My problem is that when it changes questions, the information I input in is erased. For example Question 1 and 2, I would write in an animal and then I go onto Question 3, but when I go back to Question 1 and 2, the animals I wrote in are gone. Same with the radio choices. Sorry if code is tedious, I'm just starting. Any tips on how I can fix that?

Quiz link: https://repl.it/GSiI/latest

    function initialize()
    {
      questionList = document.getElementsByClassName("questions");
      quizOutput = document.getElementById("showQuiz");
      beginBtn = document.getElementById("initiate");
      button = document.getElementById("button");
      next = document.getElementById("next");
      previous = document.getElementById("previous");
      questionIndex = 0;
      totalQuestions = questionList.length - 1;
    }

    function beginQuiz()
    {
     currentQuestion = questionList.item(questionIndex).innerHTML;
     button.style.visibility = "visible";
     quizOutput.innerHTML = currentQuestion;
     beginBtn.style.display = "none";
     quizOutput.style.display = "block";
    }

    function changeQuestion(factor)
    {
       if(factor == -1 && questionIndex > 0)
       {
        questionIndex--;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
       if(factor == 1 && questionIndex < totalQuestions)
       {
        questionIndex++;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
   }

    function writeNumber(el, num)
    {
     input = document.getElementById(el);
        if(input.value.length < 2)
        {
            input.value += num;
        }
    }

    function clearAnswer(el)
    {
     document.getElementById(el).value = "";
    }

    function takeValues()
    {
     var x = document.getElementById("frm1");
     var text = "";
     var i;
     for (i = 0; i < x.length ;i++)
        {
          text += x.elements[i].value + "
";
        }
     document.getElementById("demo").innerHTML = text;
    }


问:
ServerSocket accept() method
Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

```<code>ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();
</code>```

答:
A TCP connection consists of four parts:

Client IP

Client Port

Server IP

Server Port

There can be, for example, multiple clients connected to the same server port - as long as the clients don't have the same IP and the same prt, it's ok. And for that part, the Operating System takes care.

So it's totally ok to listen just on one port.

Title: ServerSocket accept() method

Body:
Who knows how the port is chosen when I'm using accept method of ServerSocket class? Is it possible to define a range for the ports the method can choose from? Can I 'take' ports one by one just in order?

ServerSocket sSocket = new ServerSocket(5050);
Socket socket = sSocket.accept();


答:
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

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

            </button>

```

this should work to have the icon right next to the search box.

Title: How to align the button right next to the search box

Body:
I am trying to align the search button right next to the search box however button seems to be below. This is what I got:

        <form action="{linkto page="search.php"}" method="get" id="searchFormTest">
           <input type="text" id="searchPhrase" name="searchPhrase" class="searchInputBox" value="{$lang.enterKeywords}" placeholder="Suchbegriff oder Bildnummer">

                <button type="submit" value="Submit">

               </button>

        </form>

Body:
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  </head>
  <div style="display: inline;">
  <input type="text"/>
         <span>   <button type="submit" value="Submit">
                <i style="font-size: 20px;" class="fa fa-search" aria-hidden="true"></i></span>
            </button>
        </div>

this should work to have the icon right next to the search box.