问:
-webkit-linear-gradient works well on Chrome and Safari but don't work on Firefox
The following html/css example works fine on Chrome/Firefox but doesn't look like it intended to be on Firefox.

http://codepen.io/anatoly314/pen/MpZKeM

HTML:

```<code><div class="job-card-body">
    <div class="job-card-body-text">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a dolor urna. Morbi mattis enim diam, ut laoreet nunc maximus ac. Mauris faucibus orci vel sem vulputate euismod. Donec dui arcu, interdum ut mi vel, iaculis rutrum magna. Mauris et bibendum augue, quis consequat mauris. Duis sagittis, massa nec dapibus sodales, ipsum tortor porta risus, ac fringilla ipsum lorem non orci. Integer ullamcorper sodales quam, id tempor nulla ornare vel. Sed posuere lacus velit, ut facilisis justo luctus at. Donec felis metus, pharetra id dolor a, pretium convallis dolor. Nam vel lectus venenatis, porta purus vel, gravida nisi.

Vivamus finibus ac mauris vitae porttitor. Aliquam euismod est at mi pellentesque rutrum. Proin accumsan a risus in sagittis. Nullam congue felis eu volutpat dapibus. Curabitur porta ligula libero, vitae tempus est euismod in. Aliquam erat volutpat. Pellentesque at dui vel leo malesuada vehicula. Nullam justo purus, aliquet id diam vel, fermentum ornare est.

Pellentesque maximus imperdiet enim, nec viverra ipsum elementum sit amet. Nulla nisl magna, ultricies nec egestas sit amet, lobortis a ligula. Sed sollicitudin, est in varius molestie, mi odio tincidunt nisl, vel bibendum justo est vel tortor. Sed id consequat erat. Proin tincidunt semper tincidunt. Sed sagittis risus.
    </div>
    <div class="job-card-body-link">
      <a href="">Show More...</a>
    </div>
  </div>
</code>```

CSS:

```<code>* {
  box-sizing: border-box;
}

.job-card-body{
  padding: 10px;
  height: 30vw;
  width: 30vw;
  border: 1px solid #000000;
  border-radius: 10px;
}

.job-card-body{
  height: 50%;
  overflow: hidden;

}

.job-card-body-text{
    padding: 5px;
  height: 80%;
  background: -webkit-linear-gradient(top, black 0px, white);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.job-card-body-link{
  height: 20%;
  background-color: white;
  color: black !important;
  text-align: right;
}
</code>```

It should looks like:

But looks on Firefox like this:

P.S. This is what I trying to accomplish: http://codepen.io/anatoly314/pen/bqQxxJ/

答:
You'll need to use -mox-linear-gradient. I've included ones for other browsers as well. See example:

```<code>.class {
  background-color: #F07575; /* fallback color if gradients are not supported */
  background-image: -webkit-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
  background-image:    -moz-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For Firefox (3.6 to 15) */
  background-image:      -o-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For old Opera (11.1 to 12.0) */
  background-image:         linear-gradient(to bottom, hsl(0, 80%, 70%), #bada55); /* Standard syntax; must be last */
}
</code>```

Body:
The following html/css example works fine on Chrome/Firefox but doesn't look like it intended to be on Firefox.

http://codepen.io/anatoly314/pen/MpZKeM

HTML:

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a dolor urna. Morbi mattis enim diam, ut laoreet nunc maximus ac. Mauris faucibus orci vel sem vulputate euismod. Donec dui arcu, interdum ut mi vel, iaculis rutrum magna. Mauris et bibendum augue, quis consequat mauris. Duis sagittis, massa nec dapibus sodales, ipsum tortor porta risus, ac fringilla ipsum lorem non orci. Integer ullamcorper sodales quam, id tempor nulla ornare vel. Sed posuere lacus velit, ut facilisis justo luctus at. Donec felis metus, pharetra id dolor a, pretium convallis dolor. Nam vel lectus venenatis, porta purus vel, gravida nisi.

Vivamus finibus ac mauris vitae porttitor. Aliquam euismod est at mi pellentesque rutrum. Proin accumsan a risus in sagittis. Nullam congue felis eu volutpat dapibus. Curabitur porta ligula libero, vitae tempus est euismod in. Aliquam erat volutpat. Pellentesque at dui vel leo malesuada vehicula. Nullam justo purus, aliquet id diam vel, fermentum ornare est.

Pellentesque maximus imperdiet enim, nec viverra ipsum elementum sit amet. Nulla nisl magna, ultricies nec egestas sit amet, lobortis a ligula. Sed sollicitudin, est in varius molestie, mi odio tincidunt nisl, vel bibendum justo est vel tortor. Sed id consequat erat. Proin tincidunt semper tincidunt. Sed sagittis risus.

      Show More...

CSS:

* {
  box-sizing: border-box;
}

.job-card-body{
  padding: 10px;
  height: 30vw;
  width: 30vw;
  border: 1px solid #000000;
  border-radius: 10px;
}

.job-card-body{
  height: 50%;
  overflow: hidden;

}

.job-card-body-text{
    padding: 5px;
  height: 80%;
  background: -webkit-linear-gradient(top, black 0px, white);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.job-card-body-link{
  height: 20%;
  background-color: white;
  color: black !important;
  text-align: right;
}

It should looks like:

But looks on Firefox like this:

P.S. This is what I trying to accomplish: http://codepen.io/anatoly314/pen/bqQxxJ/

Body:
You'll need to use -mox-linear-gradient. I've included ones for other browsers as well. See example:

.class {
  background-color: #F07575; /* fallback color if gradients are not supported */
  background-image: -webkit-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
  background-image:    -moz-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For Firefox (3.6 to 15) */
  background-image:      -o-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* For old Opera (11.1 to 12.0) */
  background-image:         linear-gradient(to bottom, hsl(0, 80%, 70%), #bada55); /* Standard syntax; must be last */
}


来源: stackexchange

问:
string.empty and string.isnullorempty
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

```<code>      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }
</code>```

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

答:
Change your IF condition to -</p>

```<code>if( string.IsNullOrEmpty(txtHost.Text) )
{
  ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: string.empty and string.isnullorempty

Body:
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

Body:
Change your IF condition to -

if( string.IsNullOrEmpty(txtHost.Text) )
{
  ...
}


问:
Multiplying arrays of matrices in MATLAB
I have a data set that consists of two 1800 x 900 x 3 x 3 arrays, which should each be interpreted as a 1800x900 array of 3x3 matrices. As part of the analysis, at one point I need to create another such array by, at each point of the 1800x900 array, multiplying the corresponding 3x3 matrices together.

There seem to be two ways to do this that I can think of. The obvious way is

```<code>C = zeros(size(A))
for i = 1:900
    for j = 1:1800
        C(i,j,:,:) = A(i,j,:,:)*B(i,j,:,:)
    end
end
</code>```

But that's quite a long loop and doesn't really take advantage of MATLAB's vectorization. The other way is

```<code>C = zeros(size(A))
for i = 1:3
    for j = 1:3
        for k = 1:3
            C(:,:,i,j) = C(:,:,i,j) + A(:,:,i,k).*B(:,:,k,j)
        end
    end
end
</code>```

where the large dimensions are getting vectorized and I'm basically using the for loops to implement the Einstein summation convention. This seems really inelegant, though, which makes me think there should be a better way. Is there?

答:
Perfect job for bsxfun with permute:

```<code>C = permute(sum(bsxfun(@times, A, permute(B, [1 2 5 3 4])), 4), [1 2 3 5 4]);
</code>```

In R2016b onwards you can avoid bsxfun thanks to implicit singleton expansion:

```<code>C = permute(sum(A .* permute(B, [1 2 5 3 4]), 4), [1 2 3 5 4]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data set that consists of two 1800 x 900 x 3 x 3 arrays, which should each be interpreted as a 1800x900 array of 3x3 matrices. As part of the analysis, at one point I need to create another such array by, at each point of the 1800x900 array, multiplying the corresponding 3x3 matrices together.

There seem to be two ways to do this that I can think of. The obvious way is

C = zeros(size(A))
for i = 1:900
    for j = 1:1800
        C(i,j,:,:) = A(i,j,:,:)*B(i,j,:,:)
    end
end

But that's quite a long loop and doesn't really take advantage of MATLAB's vectorization. The other way is

C = zeros(size(A))
for i = 1:3
    for j = 1:3
        for k = 1:3
            C(:,:,i,j) = C(:,:,i,j) + A(:,:,i,k).*B(:,:,k,j)
        end
    end
end

where the large dimensions are getting vectorized and I'm basically using the for loops to implement the Einstein summation convention. This seems really inelegant, though, which makes me think there should be a better way. Is there?

Body:
Perfect job for bsxfun with permute:

C = permute(sum(bsxfun(@times, A, permute(B, [1 2 5 3 4])), 4), [1 2 3 5 4]);

In R2016b onwards you can avoid bsxfun thanks to implicit singleton expansion:

C = permute(sum(A .* permute(B, [1 2 5 3 4]), 4), [1 2 3 5 4]);


问:
What's the easiest way to run a .js javascript file on windows?
When you try and run (not edit) a Javascript file, It will give an error that sounds like it is missing a reference in your code.  For Example, I got:

```<code>Line: 3 Char: 1

Error: 'document' is undefined'

Code: 800A1391

Source: Microsoft JScript runtime error
</code>```

Is it trying to execute a program similar to VBScript?  Should I be running it with another program?

答: Yes it works a lot like VBScript.  I suggest visiting w3schools.com if you want to learn javascript.  Also check out this similar question https://superuser.com/questions/276614/running-javascript-files-js</p>

Body:
When you try and run (not edit) a Javascript file, It will give an error that sounds like it is missing a reference in your code.  For Example, I got:

Line: 3 Char: 1

Error: 'document' is undefined'

Code: 800A1391

Source: Microsoft JScript runtime error

Is it trying to execute a program similar to VBScript?  Should I be running it with another program?


问:
How do I make a month and year pick in iOS/Phonegap

Is this a feature one can activate? Or can someone guide me where to look?

答: take a look at input type="month" in html5. But you will probably need some extra css</p>


问:
Using `apply` to modify string by `tolower`
I have a data.table with some character variables and numeric/integer variables, I would like to identify a variable that is of type character, and then run the tolower function to modify case.  Here is what I am doing but it does not seem to accomplish the check of type to only operate on character variables:

```<code>set.seed(426)
dt <- data.table(a = runif(5), b = sample(LETTERS, 5))

dt
           a b
1: 0.8472276 Y
2: 0.1567767 J
3: 0.9817384 L
4: 0.2250681 S
5: 0.5994389 H

sapply(dt, class)
        a           b
"numeric" "character"

dt2 <- as.data.table(sapply(dt, function(n){
    if(class(n) == "character"){
            n <- tolower(n)
    } else{
            n
    }
}))

dt2
                   a b
1: 0.847227579215541 y
2: 0.156776716466993 j
3: 0.981738423462957 l
4: 0.225068145431578 s
5: 0.599438918055966 h

sapply(dt2, class)
          a           b
"character" "character"
</code>```

I'm new to the apply family, any insight is appreciated

答:
All your variables are coerced to character by sapply as it tries to return a matrix. As you cant have more than one variable type in a matrix, all are converted to character. To avoid this you can use lapply.

For a more data.table way to approach this, courtesy of Frank, you could do

```<code># Find character columns
cols = names(dt)[sapply(dt, is.character)] # or which(sapply(dt, is.character))
# set these columns to lower
dt[, (cols) := lapply(.SD, tolower), .SDcols=cols]
</code>```

or this

```<code>dt[, lapply(.SD, function(x) if(is.character(x)) tolower(x) else x)]
</code>```

Body:
I have a data.table with some character variables and numeric/integer variables, I would like to identify a variable that is of type character, and then run the tolower function to modify case.  Here is what I am doing but it does not seem to accomplish the check of type to only operate on character variables:

set.seed(426)
dt <- data.table(a = runif(5), b = sample(LETTERS, 5))

dt
           a b
1: 0.8472276 Y
2: 0.1567767 J
3: 0.9817384 L
4: 0.2250681 S
5: 0.5994389 H

sapply(dt, class)
        a           b
"numeric" "character"

dt2 <- as.data.table(sapply(dt, function(n){
    if(class(n) == "character"){
            n <- tolower(n)
    } else{
            n
    }
}))

dt2
                   a b
1: 0.847227579215541 y
2: 0.156776716466993 j
3: 0.981738423462957 l
4: 0.225068145431578 s
5: 0.599438918055966 h

sapply(dt2, class)
          a           b
"character" "character"

I'm new to the apply family, any insight is appreciated

Body:
All your variables are coerced to character by sapply as it tries to return a matrix. As you cant have more than one variable type in a matrix, all are converted to character. To avoid this you can use lapply.

For a more data.table way to approach this, courtesy of Frank, you could do

# Find character columns
cols = names(dt)[sapply(dt, is.character)] # or which(sapply(dt, is.character))
# set these columns to lower
dt[, (cols) := lapply(.SD, tolower), .SDcols=cols]

or this

dt[, lapply(.SD, function(x) if(is.character(x)) tolower(x) else x)]


问:
Changing font size of a particular div that is built in run-time
Consider this:

```<code><div>
   <div class="h">header</div>
   <div class="m">menu</div>
   <div class="m">menu</div>
</div>
</code>```

The h and m classes are built by a tool that I am not permitted to modify.
I would like to change the 'h' font size in this and only this place. All other places that use the 'h' class must keep the same font size.

I was thinking about adding my own class like this:

```<code><div class='myheader'>
   <div class="h">header</div>
   <div class="m">menu</div>
   <div class="m">menu</div>
</div>
</code>```

and define this in my .css file like this:

```<code>.myheader > * {
}

.myheader.h {
   font-size:20px;
}
</code>```

Unfortunately it does not work for it does not 'see' .myheader.h. It applies only style read from .h and .myheader but not both at the same time.

Is there any other way to change the header font size?
Before you say "modify
header
" like I need to reiterate - these likes are being created by a tool - in run-time - so I cannot modify them.

PS. I am using angularJS, but I am not allowed to use jQuery calls.

Thank you in advance!
- Greg,

See http://plnkr.co/edit/R0elLsOdcOfsLpHB1NT1 for an example.
I am able to change font size, and that's cool, but when I add change of a color, it spreads down, and I don't want it. I want in this example to change Level 3, and that's it.

答:
looking at this  .myheader.h is inccorrect, what you need is  .myheader .h

.myheader .h {
  font-size: 20px;
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='myheader'>
  <div class="h">header</div>
  <div class="m">menu</div>
  <div class="m">menu</div>
</div></code>```

Next css children elements will inherit certain attributes, of their parents

The div .level4 is inside level3 so it will inherit from its parent (.level3) unless you override this behaviour.

You have the text content Level 3 in .level4 and afterwards a single div with class level4.You can simply override the inherited rule but making the children elements retain their "default" using color:initial

```<code>.level3 > * {
  color:initial;
}
</code>```

Snippet below

/* Put your css in here */

.level1 {
  font-size: 10px;
}

.level2 {
  font-size: 20px;
}

.level3 {
  font-size: 30px;
}

.level4 {
  font-size: 40px;
}

.changer .level3 {
  font-size: 100px;
  color: red;
}

.level3 {
  border: solid green;
}

.level3>* {
  color: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div class='level1, changer'>
    Level 1
    <div class='level2'>
      Level 2
      <div class='level3'>
        Level 3
        <div class='level4'>
          Level 4
        </div>
      </div>
    </div>
  </div>
</body>

</html></code>```

Body:
Consider this:

header

menu

menu

The h and m classes are built by a tool that I am not permitted to modify.
I would like to change the 'h' font size in this and only this place. All other places that use the 'h' class must keep the same font size.

I was thinking about adding my own class like this:

header

menu

menu

and define this in my .css file like this:

.myheader > * {
}

.myheader.h {
   font-size:20px;
}

Unfortunately it does not work for it does not 'see' .myheader.h. It applies only style read from .h and .myheader but not both at the same time.

Is there any other way to change the header font size?
Before you say "modify
header
" like I need to reiterate - these likes are being created by a tool - in run-time - so I cannot modify them.

PS. I am using angularJS, but I am not allowed to use jQuery calls.

Thank you in advance!
- Greg,

See http://plnkr.co/edit/R0elLsOdcOfsLpHB1NT1 for an example.
I am able to change font size, and that's cool, but when I add change of a color, it spreads down, and I don't want it. I want in this example to change Level 3, and that's it.

Body:
looking at this  .myheader.h is inccorrect, what you need is  .myheader .h

.myheader .h {
  font-size: 20px;
  color: red;
}

<div class='myheader'>
  <div class="h">header</div>
  <div class="m">menu</div>
  <div class="m">menu</div>
</div>

Next css children elements will inherit certain attributes, of their parents

The div .level4 is inside level3 so it will inherit from its parent (.level3) unless you override this behaviour.

You have the text content Level 3 in .level4 and afterwards a single div with class level4.You can simply override the inherited rule but making the children elements retain their "default" using color:initial

.level3 > * {
  color:initial;
}

Snippet below

/* Put your css in here */

.level1 {
  font-size: 10px;
}

.level2 {
  font-size: 20px;
}

.level3 {
  font-size: 30px;
}

.level4 {
  font-size: 40px;
}

.changer .level3 {
  font-size: 100px;
  color: red;
}

.level3 {
  border: solid green;
}

.level3>* {
  color: initial;
}

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div class='level1, changer'>
    Level 1
    <div class='level2'>
      Level 2
      <div class='level3'>
        Level 3
        <div class='level4'>
          Level 4
        </div>
      </div>
    </div>
  </div>
</body>

</html>


问:
Unable to Sort ArrayList<HashMap<String, Object>> by Single HashMap object field in Java Android
i am adding data to ArrayList < HashMap < String, Object>> contactList;

i want to sort the contactList as per their single field .

i am adding data like this :

```<code>HashMap<String, Object> docs = new HashMap<>();
                        docs.put("name", key);
                        docs.put("speciality", speci);
                        docs.put("status", status);  // sort by this field , if contains online it should appear first .
                        docs.put("picture", bp);
                        docs.put("education", educate);
                        docs.put("experience", experi);
                        docs.put("rating", ft);
                        contactList.add(docs);
</code>```

data is added in a loop and later i assign contactList to simpleAdapter for listview.

Now i want my contact list to compare the 'status' field , if status is 'online' show first or if all status are offline do nothing just show all ;

how can i sort my data , i need to use this data later in listView to show online status contacts first in listview. Any help Would be appreciated. Thanks

答:
You can define a comparator by anonymous inner class and sort based on value of status field assuming it's always going to be a String, e.g.:

```<code>contactList.sort(new Comparator<Map<String, Object>>() {
    @Override
    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
        if(null != o1.get("status") && null != o1.get("status")){
            return o2.get("status").toString().compareTo(o1.get("status").toString());
        }else if(null != o1.get("status")){
            return 1;
        }else{
            return -1;
        }
    }
});
</code>```

Update

You can use Collections.sort if list.sort is not compatible with current API version, e.g.:

```<code>Collections.sort(contactList, new Comparator<Map<String, Object>>() {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            if(null != o1.get("status") && null != o1.get("status")){
                return o2.get("status").toString().compareTo(o1.get("status").toString());
            }else if(null != o1.get("status")){
                return 1;
            }else{
                return -1;
            }
        }
    });
</code>```

Body:
i am adding data to ArrayList < HashMap < String, Object>> contactList;

i want to sort the contactList as per their single field .

i am adding data like this :

HashMap<String, Object> docs = new HashMap<>();
                        docs.put("name", key);
                        docs.put("speciality", speci);
                        docs.put("status", status);  // sort by this field , if contains online it should appear first .
                        docs.put("picture", bp);
                        docs.put("education", educate);
                        docs.put("experience", experi);
                        docs.put("rating", ft);
                        contactList.add(docs);

data is added in a loop and later i assign contactList to simpleAdapter for listview.

Now i want my contact list to compare the 'status' field , if status is 'online' show first or if all status are offline do nothing just show all ;

how can i sort my data , i need to use this data later in listView to show online status contacts first in listview. Any help Would be appreciated. Thanks

Body:
You can define a comparator by anonymous inner class and sort based on value of status field assuming it's always going to be a String, e.g.:

contactList.sort(new Comparator<Map<String, Object>>() {
    @Override
    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
        if(null != o1.get("status") && null != o1.get("status")){
            return o2.get("status").toString().compareTo(o1.get("status").toString());
        }else if(null != o1.get("status")){
            return 1;
        }else{
            return -1;
        }
    }
});

Update

You can use Collections.sort if list.sort is not compatible with current API version, e.g.:

Collections.sort(contactList, new Comparator<Map<String, Object>>() {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            if(null != o1.get("status") && null != o1.get("status")){
                return o2.get("status").toString().compareTo(o1.get("status").toString());
            }else if(null != o1.get("status")){
                return 1;
            }else{
                return -1;
            }
        }
    });


问:
Search for sub-directory and delete content if older than specified time
I am really new to python and coding in general and am looking for some help with optimizing my code. I am attempting to write a script that will locate all "Temp" folders under a certain path, find the newest file age for each, and proceed on with the deletion only if no files found are newer than 1 hour old. Currently the deletion mechanism is not implemented but that should be easy enough to add once the files have been located and checked.

My current iteration has no problem running on my test folder structure of a few thousand files but when I try and run it on the real thing (5b+ files) it of course takes forever. Almost all of these files reside outside of the "Temp" folders. Is there a way to isolate the searching of files to only Temp folders?

Below is my current code.

```<code>import os
import fnmatch
import time
import calendar

def find_newest_file(path):
    for cur_path, dirnames, filenames in os.walk(path):
        for filename in filenames:
            yield os.path.join(cur_path, filename)

matches = []
latest_file = []
for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    for filename in fnmatch.filter(dirnames, '*Temp'):
            matches.append(os.path.join(root, filename))
            latest_file.append(max(find_newest_file(os.path.join(root, filename)),
                              key=os.path.getmtime))

counter = 0
newestfileage = []
for name in matches:
    newestfileage.append((calendar.timegm(time.gmtime()) - os.stat(latest_file[counter]).st_mtime) / 3600)
    counter += 1

if min(newestfileage) < 1:
    print("\nToo new of an Entry in Temp folders, stopping.\nNewest file is only", min(newestfileage)*60,"Minutes Old")
else:
    print("\nAll Temp files are older than 1 hour old, proceeding.")
</code>```

If there is an entirely different approach to this I am all ears.

答:
It seems to me, you only need to do the following:

```<code>import re
import os

temp_regex = re.compile(r'.*Temp')
matches = []
latest_file = []
for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    if temp_regex.match(os.path.basename(root)):
        matches.append(root)
        fullnames = (os.path.join(root, filename) for filename in filenames)
        latest_file.append(max(fullnames, key=os.path.getmtime)
</code>```

And dispense with your find_newest_file function, which initiates more os.walks over matching directories, but you visit them as many times as they are below a root that you give to find_newest_file. This makes you scale horrifically.

As an aside, don't keep a counter variable if you are incrementing in every iteration, use enumerate instead:

```<code>newestfileage = []
for i, name in enumerate(matches):
    newestfileage.append((calendar.timegm(time.gmtime()) - os.stat(latest_file[i]).st_mtime) / 3600)
</code>```

Or better yet, I think you just need to iterate over for file in latest_file since you never use match and only use i to index into latest_file. Indeed, the above could probably be accomplished during your os.walk pass:

```<code>temp_regex = re.compile(r'.*Temp')
matches = []
latest_file = []
newestfileage = []

for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    if temp_regex.match(os.path.basename(root)):
        matches.append(root)
        fullnames = (os.path.join(root, filename) for filename in filenames)
        latest = max(fullnames, key=os.path.getmtime)
        latest_file.append(latest)
        newestfileage.append(calendar.timegm(time.gmtime()) - os.stat(latest).st_mtime) / 3600)
</code>```

Body:
I am really new to python and coding in general and am looking for some help with optimizing my code. I am attempting to write a script that will locate all "Temp" folders under a certain path, find the newest file age for each, and proceed on with the deletion only if no files found are newer than 1 hour old. Currently the deletion mechanism is not implemented but that should be easy enough to add once the files have been located and checked.

My current iteration has no problem running on my test folder structure of a few thousand files but when I try and run it on the real thing (5b+ files) it of course takes forever. Almost all of these files reside outside of the "Temp" folders. Is there a way to isolate the searching of files to only Temp folders?

Below is my current code.

import os
import fnmatch
import time
import calendar

def find_newest_file(path):
    for cur_path, dirnames, filenames in os.walk(path):
        for filename in filenames:
            yield os.path.join(cur_path, filename)

matches = []
latest_file = []
for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    for filename in fnmatch.filter(dirnames, '*Temp'):
            matches.append(os.path.join(root, filename))
            latest_file.append(max(find_newest_file(os.path.join(root, filename)),
                              key=os.path.getmtime))

counter = 0
newestfileage = []
for name in matches:
    newestfileage.append((calendar.timegm(time.gmtime()) - os.stat(latest_file[counter]).st_mtime) / 3600)
    counter += 1

if min(newestfileage) < 1:
    print("\nToo new of an Entry in Temp folders, stopping.\nNewest file is only", min(newestfileage)*60,"Minutes Old")
else:
    print("\nAll Temp files are older than 1 hour old, proceeding.")

If there is an entirely different approach to this I am all ears.

Body:
It seems to me, you only need to do the following:

import re
import os

temp_regex = re.compile(r'.*Temp')
matches = []
latest_file = []
for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    if temp_regex.match(os.path.basename(root)):
        matches.append(root)
        fullnames = (os.path.join(root, filename) for filename in filenames)
        latest_file.append(max(fullnames, key=os.path.getmtime)

And dispense with your find_newest_file function, which initiates more os.walks over matching directories, but you visit them as many times as they are below a root that you give to find_newest_file. This makes you scale horrifically.

As an aside, don't keep a counter variable if you are incrementing in every iteration, use enumerate instead:

newestfileage = []
for i, name in enumerate(matches):
    newestfileage.append((calendar.timegm(time.gmtime()) - os.stat(latest_file[i]).st_mtime) / 3600)

Or better yet, I think you just need to iterate over for file in latest_file since you never use match and only use i to index into latest_file. Indeed, the above could probably be accomplished during your os.walk pass:

temp_regex = re.compile(r'.*Temp')
matches = []
latest_file = []
newestfileage = []

for root, dirnames, filenames in os.walk("--Path To Network Share--"):
    if temp_regex.match(os.path.basename(root)):
        matches.append(root)
        fullnames = (os.path.join(root, filename) for filename in filenames)
        latest = max(fullnames, key=os.path.getmtime)
        latest_file.append(latest)
        newestfileage.append(calendar.timegm(time.gmtime()) - os.stat(latest).st_mtime) / 3600)


问:
Display a count for each unique value in a table column
How can I grab a count of each unique value from a table's column, plus the actual value, into another cell.

Table 1's status column

```<code>**status**
------
itemA
itemA
itemB
itemC
</code>```

desired results into a single cell:

```<code>Table 1 Status summary |2 itemA, 1 itemB, 1 itemC
</code>```

I would settle for a simple comma separated list of all the distinct values without the count.

BACKGROUND INFO:
I have an excel document we are using to keep track of acceptance testing of a new application. The document which holds multiple worksheets (each representing an area of code that needs to be tested) and each worksheet has multiple tables (which represent test cases where each case should be tested multiple times or in different ways etc.) and then there is a summary worksheet where I want a snap shot of the data. On the summary page there is line for each table in each worksheet and a status column. In that status column I want to display a count of each status selected in the corresponding table. I had originally created a lengthy formula that hard coded the values and their counts if count was > 0, but as we are testing we are finding the need to add new status values and the formula then becomes way to burdensome to keep updated.

EDIT: ADDING FORMULA
Here is the formula that I originally had in there

```<code>=IF(COUNTIF(Table1[Status],"itemA"),COUNTIF(Table1[Status],"itemA")&" itemA"," ") & IF(COUNTIF(Table1[Status],"itemB"), ", " &COUNTIF(Table1[Status],"itemB")&" itemB"," ") & IF(COUNTIF(Table1[Status],"itemC"), ", " &COUNTIF(Table1[Status],"itemC")&" itemC"," ")
</code>```

The problem with this is, the formula was repeated about 100 times on the summary page (once for each table in the underlying worksheets) and every time I wanted to add a status I would need to edit each of the formulas.

答:
If your cells are in A1:A4, put this array formula in cells B1:B4:

```<code>{=$A$1:$A$4&": "&COUNTIF($A$1:$A$4,$A$1:$A$4)}
</code>```

This will create your strings which look like itemA: 2 and itemB: 1, but there will be repetitions.

Then, you'd use the VBA code you suggested in the comments.  I'm putting it here for the sake of completeness:

```<code>Function ConcatUniq(ByRef rng As Range) As String
    Dim r As Range
    Static dic As Object
    If dic Is Nothing Then Set dic = CreateObject("Scripting.Dictionary")
    For Each r In rng
        If r.Value <> Empty Then
            dic(r.Value) = Empty
        End If
    Next
    ConcatUniq = Join$(dic.keys, ", ")
    dic.RemoveAll
End Function
</code>```

So your final string's cell formula will look like this:

```<code>=ConcatUniq(B1:B4)
</code>```

Body:
How can I grab a count of each unique value from a table's column, plus the actual value, into another cell.

Table 1's status column

**status**
------
itemA
itemA
itemB
itemC

desired results into a single cell:

Table 1 Status summary |2 itemA, 1 itemB, 1 itemC

I would settle for a simple comma separated list of all the distinct values without the count.

BACKGROUND INFO:
I have an excel document we are using to keep track of acceptance testing of a new application. The document which holds multiple worksheets (each representing an area of code that needs to be tested) and each worksheet has multiple tables (which represent test cases where each case should be tested multiple times or in different ways etc.) and then there is a summary worksheet where I want a snap shot of the data. On the summary page there is line for each table in each worksheet and a status column. In that status column I want to display a count of each status selected in the corresponding table. I had originally created a lengthy formula that hard coded the values and their counts if count was > 0, but as we are testing we are finding the need to add new status values and the formula then becomes way to burdensome to keep updated.

EDIT: ADDING FORMULA
Here is the formula that I originally had in there

=IF(COUNTIF(Table1[Status],"itemA"),COUNTIF(Table1[Status],"itemA")&" itemA"," ") & IF(COUNTIF(Table1[Status],"itemB"), ", " &COUNTIF(Table1[Status],"itemB")&" itemB"," ") & IF(COUNTIF(Table1[Status],"itemC"), ", " &COUNTIF(Table1[Status],"itemC")&" itemC"," ")

The problem with this is, the formula was repeated about 100 times on the summary page (once for each table in the underlying worksheets) and every time I wanted to add a status I would need to edit each of the formulas.

Body:
If your cells are in A1:A4, put this array formula in cells B1:B4:

{=$A$1:$A$4&": "&COUNTIF($A$1:$A$4,$A$1:$A$4)}

This will create your strings which look like itemA: 2 and itemB: 1, but there will be repetitions.

Then, you'd use the VBA code you suggested in the comments.  I'm putting it here for the sake of completeness:

Function ConcatUniq(ByRef rng As Range) As String
    Dim r As Range
    Static dic As Object
    If dic Is Nothing Then Set dic = CreateObject("Scripting.Dictionary")
    For Each r In rng
        If r.Value <> Empty Then
            dic(r.Value) = Empty
        End If
    Next
    ConcatUniq = Join$(dic.keys, ", ")
    dic.RemoveAll
End Function

So your final string's cell formula will look like this:

=ConcatUniq(B1:B4)


问:
Parse Json data
```<code>a=  [{
    "data" : {
        "check": true,
    },
    "AMI": {
        "status": 1,
        "firewall":{
            "status": enable
        },
        "d_suffix": "x.y.com",
        "id": 4
    },
    "tags": [  #Sometime tags could be like "tags":  ["default","auto"]
        "default"
    ],
    "hostname": "abc.com",
}
]
</code>```

How to get a hostname on the basis of tags?I am trying to implement it using

```<code>for i in a:
  if i['tags'] == 'default':
     output = i['hostname']
</code>```

but it's failing because 'tags' is a list which is not mapping to hostname key.Is there any way i can get hostname on the basis of 'tags'?

答:
Make sure that you have everything in Json format like

a=  [{
    "data" : {
        "check": True,
    },
    "AMI": {
        "status": 1,
        "firewall":{
            "status": "enable"
        },
        "d_suffix": "x.y.com",
        "id": 4
    },
    "tags": [
        "default"
    ],
    "hostname": "abc.com",
}
]```
</div>
</div>
</p>

<p>and then you can easily get it by using <code>in</code> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for i in a:
    if 'default' in i['tags']:
        output = i['hostname']</code>```

Title: Parse Json data

Body:
a=  [{
    "data" : {
        "check": true,
    },
    "AMI": {
        "status": 1,
        "firewall":{
            "status": enable
        },
        "d_suffix": "x.y.com",
        "id": 4
    },
    "tags": [  #Sometime tags could be like "tags":  ["default","auto"]
        "default"
    ],
    "hostname": "abc.com",
}
]

How to get a hostname on the basis of tags?I am trying to implement it using

for i in a:
  if i['tags'] == 'default':
     output = i['hostname']

but it's failing because 'tags' is a list which is not mapping to hostname key.Is there any way i can get hostname on the basis of 'tags'?

Body:
Make sure that you have everything in Json format like

a=  [{
    "data" : {
        "check": True,
    },
    "AMI": {
        "status": 1,
        "firewall":{
            "status": "enable"
        },
        "d_suffix": "x.y.com",
        "id": 4
    },
    "tags": [
        "default"
    ],
    "hostname": "abc.com",
}
]

and then you can easily get it by using in

for i in a:
    if 'default' in i['tags']:
        output = i['hostname']


问:
Ruby on rails - Sort data with SQL/ActiveRecord instead of ruby
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :

```<code>@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }
</code>```

Is their a way to do the same thing only with SQL/ActiveRecord?

答:
To run sql queries in Rails you could do this:

```<code>sql_statement = "Select * from ..."
@data = ActiveRecord::Base.connection.execute(sql_statement)
</code>```

Then in your view you could simply reference the @data object

Body:
I'm working with two tables Video and Picture and I would like to regroup them using SQL instead of ruby. This is how I do it now :

@medias = (Video.all + Picture.all).sort_by { |model| model.created_at }

Is their a way to do the same thing only with SQL/ActiveRecord?

Body:
To run sql queries in Rails you could do this:

sql_statement = "Select * from ..."
@data = ActiveRecord::Base.connection.execute(sql_statement)

Then in your view you could simply reference the @data object


问:
Possible to use Akavanche with Azure Mobile Apps?
I seem to have 3 different installs of SQLLite and want to see if I can consolidate them, or if that is even a good idea to do so.  (or if there are conflicts).

Below I have

Akavanche.sqlite3

Microsoft.Azure.Mobile.Client.SQLiteStore

Some SQLite raw references.

I'm not sure where some of these came from (aside from Akavanche and Azure), but I want to save space within my app. (Apple App Store is 100MB)

What should I do with all these references, is it OK?

答:
For each library, you need the dependency tree.

Microsoft.Azure.Mobile.Client.SQLiteStore depends on:

SQLitePCLRaw.core

SQLitePCLRaw.bundle_green

This latter has a huge list of platform-specific dependencies, some of which you see in your list.  Akavache has a dependency on a different SQLite database edition (the e_sqlite3 version).  So, I think you need all of the SQLite libraries because of the differing dependencies.


问:
Get XML node attribute value Java
I have an XML Document which contains XML elements containing attributes from which I would like to get it's value and store it in a Hashmap.

Example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Nodes>
    <Node name="test1">
        <mou>
            <line3>hello</line3>
        </mou>
    </Node>

    <Node name="test2">
        <mou>
            <line3>hello</line3>
        </mou>
    </Node>

    <InputNode name="Chance">
        <Test>
            <RoundTo>100</RoundTo>
        </Test>
    </InputNode>
    <InputNode name="total" />
</Nodes>
</code>```

I'd like to parse this xml and retrieve the values attributes from all the elements named 'Node' and store it in a map object. So from the example above I would get

```<code>[name=test1,name=test2]
</code>```

The problem is with maps the keys must be unique. How can I accomplish my goal using Java?

答: Sorry, I got your question wrong. You can parse the xml already. You want to store it in a map. You can create objects out of all the nodes. Node { nodeName, attribute1, attribute2} then you can save it as a map by {key,value} = {name, nodeObj}</p>

Title: Get XML node attribute value Java

Body:
I have an XML Document which contains XML elements containing attributes from which I would like to get it's value and store it in a Hashmap.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<Nodes>
    <Node name="test1">
        <mou>
            <line3>hello</line3>
        </mou>
    </Node>

    <Node name="test2">
        <mou>
            <line3>hello</line3>
        </mou>
    </Node>

    <InputNode name="Chance">
        <Test>
            <RoundTo>100</RoundTo>
        </Test>
    </InputNode>
    <InputNode name="total" />
</Nodes>

I'd like to parse this xml and retrieve the values attributes from all the elements named 'Node' and store it in a map object. So from the example above I would get

[name=test1,name=test2]

The problem is with maps the keys must be unique. How can I accomplish my goal using Java?


问:
Strategy Pattern the right thing?
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

```<code>switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}
</code>```

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

```<code>abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}
</code>```

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

答:
That's more or less the right way to do this in a beautiful fashion.
At some point in your code, you'll have to make a decision whether v1 or v2 has to be used, so you'll have to have a conditional statement (if or switch) anyway.  However, when using a strategy and a factory (factory method or factory class), you've centralized that decision.

I would make my factory method on the abstract class static though.
Also, I would make use of the template-method pattern: that is, a public, non overridable GetData method which calls a protected virtual (abstract) method that should be overriden in a concrete implementation.

```<code>public abstract class SoapProcessor
{

    protected SoapProcessor() { /* protected constructor since public is of no use */  }

    public static SoapProcessor Create( SoapVersion version )
    {
          switch( version )
          {
               case SoapVersion.Version1 : return new SoapV1Processor();
               case SoapVersion.Version2 : return new SoapV2Processor();
               default: throw new NOtSupportedException();
          }
    }

    public string[] GetData()
    {
         return GetDataCore();
    }

    protected abstract GetDataCore();
 }
</code>```

}

Title: Strategy Pattern the right thing?

Body:
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

Body:
That's more or less the right way to do this in a beautiful fashion.
At some point in your code, you'll have to make a decision whether v1 or v2 has to be used, so you'll have to have a conditional statement (if or switch) anyway.  However, when using a strategy and a factory (factory method or factory class), you've centralized that decision.

I would make my factory method on the abstract class static though.
Also, I would make use of the template-method pattern: that is, a public, non overridable GetData method which calls a protected virtual (abstract) method that should be overriden in a concrete implementation.

public abstract class SoapProcessor
{

    protected SoapProcessor() { /* protected constructor since public is of no use */  }

    public static SoapProcessor Create( SoapVersion version )
    {
          switch( version )
          {
               case SoapVersion.Version1 : return new SoapV1Processor();
               case SoapVersion.Version2 : return new SoapV2Processor();
               default: throw new NOtSupportedException();
          }
    }

    public string[] GetData()
    {
         return GetDataCore();
    }

    protected abstract GetDataCore();
 }

}


问:
Create a startup script for meteor in linux server
I have followed some posts and tutorials as well to create a script to start meteor project when server restart. i have followed answer mentioned in : How to run meteor on startup on Ubuntu server

Then I gave  executable permission to script with "chmod +x meteor-server.sh".

I have tried to put this script in /etc/init.d and /etc/init folders but meteor project does not start at the reboot. I'm using ubuntu 16.04.

I would be grateful if you can show me the fault that i have done. Following code is my "meteor.server.sh" script file.

```<code>     # meteorjs - meteorjs job file

     description "MeteorJS"
     author "Jc"

     # When to start the service
     start on runlevel [2345]

     # When to stop the service
     stop on runlevel [016]

     # Automatically restart process if crashed
     respawn

     # Essentially lets upstart know the process will detach itself to the background
     expect fork

     # Run before process
     pre-start script
    cd /home/me/projects/cricket
    echo ""
    end script

   # Start the process
   exec meteor run -p 4000 --help -- production
</code>```

答:
I used this configurations successfully

In /etc/init.d add a file called meteor.sh

```<code>#!/bin/sh
export HOME="/home/user"
cd /home/user/meteor/sparql-fedquest
meteor --allow-superuser
</code>```

You must give executions permissions to meteor.sh

```<code>sudo chmod 644 meteor.sh
</code>```

Also you must create meteor.service in /etc/systemd/system

```<code>[Unit]
   Description =Portal of bibliographic resources of University of Cuenca
   Author = Freddy Sumba
   [Service]
   ExecStart=/etc/init.d/meteor.sh
   Restart=always
   StandardOutput=syslog
   StandardError=syslog
   SyslogIdentifier=meteor
  [Install]
  WantedBy=multi-user.target
</code>```

Also you must give permissions to meteor.service

```<code>$ sudo chmod 644 meteor.service
</code>```

Then, we need add the service to this start each time that the server reboot

```<code>$  systemctl enable meteor.service
</code>```

And finally start the service

```<code>$ service meteor start
</code>```

Body:
I have followed some posts and tutorials as well to create a script to start meteor project when server restart. i have followed answer mentioned in : How to run meteor on startup on Ubuntu server

Then I gave  executable permission to script with "chmod +x meteor-server.sh".

I have tried to put this script in /etc/init.d and /etc/init folders but meteor project does not start at the reboot. I'm using ubuntu 16.04.

I would be grateful if you can show me the fault that i have done. Following code is my "meteor.server.sh" script file.

     # meteorjs - meteorjs job file

     description "MeteorJS"
     author "Jc"

     # When to start the service
     start on runlevel [2345]

     # When to stop the service
     stop on runlevel [016]

     # Automatically restart process if crashed
     respawn

     # Essentially lets upstart know the process will detach itself to the background
     expect fork

     # Run before process
     pre-start script
    cd /home/me/projects/cricket
    echo ""
    end script

   # Start the process
   exec meteor run -p 4000 --help -- production

Body:
I used this configurations successfully

In /etc/init.d add a file called meteor.sh

#!/bin/sh
export HOME="/home/user"
cd /home/user/meteor/sparql-fedquest
meteor --allow-superuser

You must give executions permissions to meteor.sh

sudo chmod 644 meteor.sh

Also you must create meteor.service in /etc/systemd/system

[Unit]
   Description =Portal of bibliographic resources of University of Cuenca
   Author = Freddy Sumba
   [Service]
   ExecStart=/etc/init.d/meteor.sh
   Restart=always
   StandardOutput=syslog
   StandardError=syslog
   SyslogIdentifier=meteor
  [Install]
  WantedBy=multi-user.target

Also you must give permissions to meteor.service

$ sudo chmod 644 meteor.service

Then, we need add the service to this start each time that the server reboot

$  systemctl enable meteor.service

And finally start the service

$ service meteor start


问:
Why is $GLOBALS significately slower than global keywords?
I'Ve made a few test on global vs function parameter and the difference is futile.

But as i was testing stuff, i found that $GLOBALS is about 10% slower. than using function parameter or global keyword. Anyone care to explain why?

I wish to understand further the mechanism behind PHP. This so i can make better compromise on futur dev. Not that i ever use $GLOBALS except in some exception case.

```<code>$md5 = md5(1000000);
function byGlobal() {
  global $md5;
  $c = 0;
  while( md5($c) != $md5 ){
    $c++;
  }
}
function superGlobal() {
  $c = 0;
  while( md5($c) != $GLOBALS[ 'md5' ] ){
    $c++;
  }
}
function asParam($md5) {
  $c = 0;
  while( md5($c) != $md5 ){
    $c++;
  }
}
$time3 = microtime(true);
asParam($md5);
echo (microtime(true) - $time3);

echo "<br/>";
$time1 = microtime(true);
byGlobal();
echo (microtime(true) - $time1);

echo "<br/>";
$time2 = microtime(true);
superGlobal();
echo (microtime(true) - $time2);
echo "<br/>";
</code>```

I'm not arguing about function vs global or good practice. I really just wonder why so much difference. Ran the test 20 times and results are pretty much all consistent.

i move the calls up and down in the code to avoid caching influence.

I'm doing a million md5 iteration on each call so the server works a
load.

Time results are cosistent with other hashing function (tested sha1, crc32) and they are all in the same +10% slower)

Ran on a VM with PHP 5.4.16 on CentOs7.

1st run

as param : 0.8601s

as global : 0.8262s

as $GLOBALS : 0.9463s (more than 10% slower)

2nd run

as param : 0.8100s

as global : 0.8058s

as $GLOBALS : 0.9624s (more than 10% slower again)

Related studies : (mainely debate about global best practice, nothing about $GLOBALS vs global performance.

The advantage / disadvantage between global variables and function parameters in PHP?

php global variable overhead in a framework

Does using global create any overhead?

答:
EDIT: New version, I made a mistake in the first one.

I've rewritten your tests, so it does test the things you want:

```<code><?php

$value = 6235;

function byGlobal() {
  global $value;
  return $value++;
}

function superGlobal() {
  return $GLOBALS['value']++;
}

function asParam($parameter) {
  return $parameter++;
}

$time = microtime(true);
for ($i = 0;$i < 10000000;$i++) $value = asParam($value);
echo 'asParam: '.(microtime(true)-$time).'<br/>';

$time = microtime(true);
for ($i = 0;$i < 10000000;$i++) $value = byGlobal();
echo 'byGlobal: '.(microtime(true)-$time).'<br/>';

$time = microtime(true);
for ($i = 0;$i < 10000000;$i++) $value = superGlobal();
echo 'superGlobal: '.(microtime(true)-$time).'<br/>';
</code>```

Example results for PHP 7.0.17 on CentOs7:

```<code>asParam: 0.43703699111938
byGlobal: 0.55213189125061
superGlobal: 0.70462608337402
</code>```

and

```<code>asParam: 0.4569981098175
byGlobal: 0.55681920051575
superGlobal: 0.76146912574768
</code>```

So, the superGlobal is the slowest, but not by that much. I guess the reason is that it is an array.

What I take away from this is that PHP is fast! I would not worry about the small differences in these tiny time slices. Having readable code is far more important. I my experiences the slowest thing in a website are the database queries.

Body:
I'Ve made a few test on global vs function parameter and the difference is futile.

But as i was testing stuff, i found that $GLOBALS is about 10% slower. than using function parameter or global keyword. Anyone care to explain why?

I wish to understand further the mechanism behind PHP. This so i can make better compromise on futur dev. Not that i ever use $GLOBALS except in some exception case.

$md5 = md5(1000000);
function byGlobal() {
  global $md5;
  $c = 0;
  while( md5($c) != $md5 ){
    $c++;
  }
}
function superGlobal() {
  $c = 0;
  while( md5($c) != $GLOBALS[ 'md5' ] ){
    $c++;
  }
}
function asParam($md5) {
  $c = 0;
  while( md5($c) != $md5 ){
    $c++;
  }
}
$time3 = microtime(true);
asParam($md5);
echo (microtime(true) - $time3);

echo "
";
$time1 = microtime(true);
byGlobal();
echo (microtime(true) - $time1);

echo "
";
$time2 = microtime(true);
superGlobal();
echo (microtime(true) - $time2);
echo "
";

I'm not arguing about function vs global or good practice. I really just wonder why so much difference. Ran the test 20 times and results are pretty much all consistent.

i move the calls up and down in the code to avoid caching influence.

I'm doing a million md5 iteration on each call so the server works a
load.

Time results are cosistent with other hashing function (tested sha1, crc32) and they are all in the same +10% slower)

Ran on a VM with PHP 5.4.16 on CentOs7.

1st run

as param : 0.8601s

as global : 0.8262s

as $GLOBALS : 0.9463s (more than 10% slower)

2nd run

as param : 0.8100s

as global : 0.8058s

as $GLOBALS : 0.9624s (more than 10% slower again)

Related studies : (mainely debate about global best practice, nothing about $GLOBALS vs global performance.

The advantage / disadvantage between global variables and function parameters in PHP?

php global variable overhead in a framework

Does using global create any overhead?

Body:
EDIT: New version, I made a mistake in the first one.

I've rewritten your tests, so it does test the things you want:

<?php

$value = 6235;

function byGlobal() {
  global $value;
  return $value++;
}

function superGlobal() {
  return $GLOBALS['value']++;
}

function asParam($parameter) {
  return $parameter++;
}

$time = microtime(true);
for ($i = 0;$i < 10000000;$i++) $value = asParam($value);
echo 'asParam: '.(microtime(true)-$time).'<br/>';

$time = microtime(true);
for ($i = 0;$i < 10000000;$i++) $value = byGlobal();
echo 'byGlobal: '.(microtime(true)-$time).'<br/>';

$time = microtime(true);
for ($i = 0;$i < 10000000;$i++) $value = superGlobal();
echo 'superGlobal: '.(microtime(true)-$time).'<br/>';

Example results for PHP 7.0.17 on CentOs7:

asParam: 0.43703699111938
byGlobal: 0.55213189125061
superGlobal: 0.70462608337402

and

asParam: 0.4569981098175
byGlobal: 0.55681920051575
superGlobal: 0.76146912574768

So, the superGlobal is the slowest, but not by that much. I guess the reason is that it is an array.

What I take away from this is that PHP is fast! I would not worry about the small differences in these tiny time slices. Having readable code is far more important. I my experiences the slowest thing in a website are the database queries.


问:
Google Cloud App Engine app.yaml for multiple environments
I currently have my app up and running, the app.yaml and dispatch.yaml are in the root of the application and I deploy through Google Cloud CLI.

This works well for the moment, though as I move to having a dev, staging and prod environment I can see that it's no longer viable.

The main issue I see is that I have to edit the variables in the app.yaml file so they are appropriate for environment (for example I use env_variables to store mysql credentials...).

I can't find anything in the docs that points to the correct way to manage this, any ideas?

Also... When deploying from a GIT repo it seems that the app.yaml needs to be in the repo, is this correct? It doesn't seem right to me... There must be a better way!

答:
You can use a configuration file or datastore settings to keep track of this environment information. At minute 26 in this talk I give some examples of how to customize your environment without needing different app.yaml files.

gcloud app deploy also accepts a list of yaml files on the command line, with the default being app.yaml.


问:
Visual Studio C++ Creating executable in executable
I want to create 2 executable with only 1 executable. How can i do that in Visual Studio 2015? I looked in internet but couldnt find something. Is there any way i can do that without wizard? Simply there will be 2 project in  1 solution and project1's exe will create project2's exe. Or something that will do what i want.

The purpose is user will not have to download 2 separate  exe, he will only download 1 and otherone will be created beside exe1( both program has different purposes, so exe1 will not be onl for creating exe2)

答:
Use CreateProcess in first executable to create second process from another executaable.
https://msdn.microsoft.com/en-us/library/ms682512(v=vs.85).aspx

If you need two output from one project:
use post build events:

1- Make a copy of output.

2- Change whatever you want to change.

3- Build same project again:
Build another project by prebuild event without adding reference
In your case another project is the same project.


问:
string.empty and string.isnullorempty
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

```<code>      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }
</code>```

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

答:
My guess is you tried to use it as if it were an instance method, like this:

```<code>if (txtHost.Text.IsNullOrEmpty())
</code>```

It's not an instance method - it's a static method, so you use it like this:

```<code>if (string.IsNullOrEmpty(txtHost.Text))
</code>```

It's not an instance method because otherwise if txtHost.Text was null, the method call would throw a NullReferenceException, which is precisely what we're trying to avoid.

You could write an extension method which could cope with null, but there isn't one in the framework as far as I know.

Title: string.empty and string.isnullorempty

Body:
I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox.

      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }

but when I tried to use string,isnullorempty then I am not getting the seterror icon..
Can you guys plz tell me what is the proper way of using string.isnullorempty in this case..

Body:
My guess is you tried to use it as if it were an instance method, like this:

if (txtHost.Text.IsNullOrEmpty())

It's not an instance method - it's a static method, so you use it like this:

if (string.IsNullOrEmpty(txtHost.Text))

It's not an instance method because otherwise if txtHost.Text was null, the method call would throw a NullReferenceException, which is precisely what we're trying to avoid.

You could write an extension method which could cope with null, but there isn't one in the framework as far as I know.


问:
How to Add an Object Inside Another List Object
I have an object class A, and a list object for class B

```<code>A a = a.findById(aId);
List<B> b = b.findById(bId);
</code>```

Class B has A class

```<code>public class B {
   private int id;
   private A a;
   ...getters setters
}
</code>```

Is it possible to add object a in object list b?

I get error when I try to add a in object list.
b.add(a); This tells me to change object a as B a...

How can I add object a in the list object b?

答: You can add object a if you wrap it in object B. Otherwise, you will not be able to add object a of type A to List of B objects because of the type mismatch: you are trying to add object of type A to the list of B objects which is not allowed in Java.

Body:
I have an object class A, and a list object for class B

A a = a.findById(aId);
List b = b.findById(bId);

Class B has A class

public class B {
   private int id;
   private A a;
   ...getters setters
}

Is it possible to add object a in object list b?

I get error when I try to add a in object list.
b.add(a); This tells me to change object a as B a...

How can I add object a in the list object b?

Body: You can add object a if you wrap it in object B. Otherwise, you will not be able to add object a of type A to List<B> of B objects because of the type mismatch: you are trying to add object of type A to the list of B objects which is not allowed in Java.


问:
-webkit-linear-gradient works well on Chrome and Safari but don't work on Firefox
The following html/css example works fine on Chrome/Firefox but doesn't look like it intended to be on Firefox.

http://codepen.io/anatoly314/pen/MpZKeM

HTML:

```<code><div class="job-card-body">
    <div class="job-card-body-text">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a dolor urna. Morbi mattis enim diam, ut laoreet nunc maximus ac. Mauris faucibus orci vel sem vulputate euismod. Donec dui arcu, interdum ut mi vel, iaculis rutrum magna. Mauris et bibendum augue, quis consequat mauris. Duis sagittis, massa nec dapibus sodales, ipsum tortor porta risus, ac fringilla ipsum lorem non orci. Integer ullamcorper sodales quam, id tempor nulla ornare vel. Sed posuere lacus velit, ut facilisis justo luctus at. Donec felis metus, pharetra id dolor a, pretium convallis dolor. Nam vel lectus venenatis, porta purus vel, gravida nisi.

Vivamus finibus ac mauris vitae porttitor. Aliquam euismod est at mi pellentesque rutrum. Proin accumsan a risus in sagittis. Nullam congue felis eu volutpat dapibus. Curabitur porta ligula libero, vitae tempus est euismod in. Aliquam erat volutpat. Pellentesque at dui vel leo malesuada vehicula. Nullam justo purus, aliquet id diam vel, fermentum ornare est.

Pellentesque maximus imperdiet enim, nec viverra ipsum elementum sit amet. Nulla nisl magna, ultricies nec egestas sit amet, lobortis a ligula. Sed sollicitudin, est in varius molestie, mi odio tincidunt nisl, vel bibendum justo est vel tortor. Sed id consequat erat. Proin tincidunt semper tincidunt. Sed sagittis risus.
    </div>
    <div class="job-card-body-link">
      <a href="">Show More...</a>
    </div>
  </div>
</code>```

CSS:

```<code>* {
  box-sizing: border-box;
}

.job-card-body{
  padding: 10px;
  height: 30vw;
  width: 30vw;
  border: 1px solid #000000;
  border-radius: 10px;
}

.job-card-body{
  height: 50%;
  overflow: hidden;

}

.job-card-body-text{
    padding: 5px;
  height: 80%;
  background: -webkit-linear-gradient(top, black 0px, white);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.job-card-body-link{
  height: 20%;
  background-color: white;
  color: black !important;
  text-align: right;
}
</code>```

It should looks like:

But looks on Firefox like this:

P.S. This is what I trying to accomplish: http://codepen.io/anatoly314/pen/bqQxxJ/

答:
If you need to support IE/Edge too you can't use this CSS Rule, it's very experimental and not supported by IE/Edge and Firefox < 49.

If you have a solid background color, like white you could try to get the effect by using a container with a transparent gradient on top of the text.

Try it out here: https://jsfiddle.net/z3japLqm/

```<code>.content {
    max-height: 120px;
    position: relative;
    overflow: hidden;
}
.content .overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    text-align: center;
    margin: 0; padding: 30px 0;
    background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
}
</code>```

Body:
The following html/css example works fine on Chrome/Firefox but doesn't look like it intended to be on Firefox.

http://codepen.io/anatoly314/pen/MpZKeM

HTML:

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce a dolor urna. Morbi mattis enim diam, ut laoreet nunc maximus ac. Mauris faucibus orci vel sem vulputate euismod. Donec dui arcu, interdum ut mi vel, iaculis rutrum magna. Mauris et bibendum augue, quis consequat mauris. Duis sagittis, massa nec dapibus sodales, ipsum tortor porta risus, ac fringilla ipsum lorem non orci. Integer ullamcorper sodales quam, id tempor nulla ornare vel. Sed posuere lacus velit, ut facilisis justo luctus at. Donec felis metus, pharetra id dolor a, pretium convallis dolor. Nam vel lectus venenatis, porta purus vel, gravida nisi.

Vivamus finibus ac mauris vitae porttitor. Aliquam euismod est at mi pellentesque rutrum. Proin accumsan a risus in sagittis. Nullam congue felis eu volutpat dapibus. Curabitur porta ligula libero, vitae tempus est euismod in. Aliquam erat volutpat. Pellentesque at dui vel leo malesuada vehicula. Nullam justo purus, aliquet id diam vel, fermentum ornare est.

Pellentesque maximus imperdiet enim, nec viverra ipsum elementum sit amet. Nulla nisl magna, ultricies nec egestas sit amet, lobortis a ligula. Sed sollicitudin, est in varius molestie, mi odio tincidunt nisl, vel bibendum justo est vel tortor. Sed id consequat erat. Proin tincidunt semper tincidunt. Sed sagittis risus.

      Show More...

CSS:

* {
  box-sizing: border-box;
}

.job-card-body{
  padding: 10px;
  height: 30vw;
  width: 30vw;
  border: 1px solid #000000;
  border-radius: 10px;
}

.job-card-body{
  height: 50%;
  overflow: hidden;

}

.job-card-body-text{
    padding: 5px;
  height: 80%;
  background: -webkit-linear-gradient(top, black 0px, white);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.job-card-body-link{
  height: 20%;
  background-color: white;
  color: black !important;
  text-align: right;
}

It should looks like:

But looks on Firefox like this:

P.S. This is what I trying to accomplish: http://codepen.io/anatoly314/pen/bqQxxJ/

Body:
If you need to support IE/Edge too you can't use this CSS Rule, it's very experimental and not supported by IE/Edge and Firefox < 49.

If you have a solid background color, like white you could try to get the effect by using a container with a transparent gradient on top of the text.

Try it out here: https://jsfiddle.net/z3japLqm/

.content {
    max-height: 120px;
    position: relative;
    overflow: hidden;
}
.content .overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    text-align: center;
    margin: 0; padding: 30px 0;
    background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
}


问:
How to store the content of a JTextArea into a class?
I'm working on a program that serves as a hypothetical email system in which users can be created and can send messages to other users that have been created.

The message will be stored in a "Message" class, and the text is typed in a JTextArea in a GUI.  What I want to know is how I would go about storing the text typed into the JTextArea, in the exact same layout (indentations and all), within the Message class.  I thought about text files but then there would have to be one for each message, potentially creating an infinite number of them, and I don't like the concept of having to make a system for coming up with unique names for each text file.

Can you please give me some advice?

答:
Simply implement the DocumentListener interface, then do the following:

```<code>JTextArea someMessage = new JTextArea();
someMessage.getDocument().addDocumentListener(new MyDocumentListener());
someMessage.getDocument().putProperty("name", "Text Area");
</code>```

Here, we assume the name of the listener you implement is called MyDocumentListener, and the implementation could be as simple as:

```<code>class MyDocumentListener implements DocumentListener {
    String newline = "\n";

    @Override
    public void insertUpdate(DocumentEvent e) {
        updateLog(e, "inserted into");
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        updateLog(e, "removed from");
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        //Plain text components do not fire these events
    }

    public void updateLog(DocumentEvent e, String action) {
        Document doc = (Document)e.getDocument();
        int changeLength = e.getLength();
        displayArea.append(
            changeLength + " character" +
            ((changeLength == 1) ? " " : "s ") +
            action + doc.getProperty("name") + "." + newline +
            "  Text length = " + doc.getLength() + newline);
    }
}
</code>```

Examples taken from Oracle website. I recommend reading the rest of that article as it goes into much depth of how to effectively listen for updates to the internal document model.

How to get text that was inserted

insertUpdate is what notifies you when new text has been typed into the textarea. You can get the freshly inserted text by calling off to the DocumentEvent#getOffset and DocumentEvent#getLength. Using both methods, you can get the offset (index) within document where the insertion happened, as well as the length of the change.
Then to get the actual text that was inserted, you call DocumentEvent#getDocument#getText and supplying the offset and length you got from the event.

How to get all the text in the textarea

You can use this similar method to get the entire text in the document by making use of Document#getStartPosition and Document#getEndPosition, then calling Document#getText.

Or even easier, JTextArea#getText

Body:
Simply implement the DocumentListener interface, then do the following:

JTextArea someMessage = new JTextArea();
someMessage.getDocument().addDocumentListener(new MyDocumentListener());
someMessage.getDocument().putProperty("name", "Text Area");

Here, we assume the name of the listener you implement is called MyDocumentListener, and the implementation could be as simple as:

class MyDocumentListener implements DocumentListener {
    String newline = "\n";

    @Override
    public void insertUpdate(DocumentEvent e) {
        updateLog(e, "inserted into");
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        updateLog(e, "removed from");
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        //Plain text components do not fire these events
    }

    public void updateLog(DocumentEvent e, String action) {
        Document doc = (Document)e.getDocument();
        int changeLength = e.getLength();
        displayArea.append(
            changeLength + " character" +
            ((changeLength == 1) ? " " : "s ") +
            action + doc.getProperty("name") + "." + newline +
            "  Text length = " + doc.getLength() + newline);
    }
}

Examples taken from Oracle website. I recommend reading the rest of that article as it goes into much depth of how to effectively listen for updates to the internal document model.

How to get text that was inserted

insertUpdate is what notifies you when new text has been typed into the textarea. You can get the freshly inserted text by calling off to the DocumentEvent#getOffset and DocumentEvent#getLength. Using both methods, you can get the offset (index) within document where the insertion happened, as well as the length of the change.
Then to get the actual text that was inserted, you call DocumentEvent#getDocument#getText and supplying the offset and length you got from the event.

How to get all the text in the textarea

You can use this similar method to get the entire text in the document by making use of Document#getStartPosition and Document#getEndPosition, then calling Document#getText.

Or even easier, JTextArea#getText


问:
Spark-Csv Write quotemode not working
I am trying to write a DataFrame as a CSV file using Spark-CSV (https://github.com/databricks/spark-csv)

I am using the command below

```<code>res1.write.option("quoteMode", "NONE").format("com.databricks.spark.csv").save("File")
</code>```

But my CSV file is always written as

"London"

"Copenhagen"

"Moscow"

instead of

London

Copenhagen

Moscow

答:
Yes. The way to turn off the default escaping of the double quote character (") with the backslash character (\), you must add an .option() method call with just the right parameters after the .write() method call. The goal of the option() method call is to change how the csv() method "finds" instances of the "quote" character. To do this, you must change the default of what a "quote" actually means; i.e. change the character sought from being a double quote character (") to a Unicode "\u0000" character (essentially providing the Unicode NUL character which won't ever occur within a well formed JSON document).

```<code>val dataFrame =
  spark.sql("SELECT * FROM some_table_with_a_json_column")
val unitEmitCsv =
  dataframe
    .write
    .option("header", true)
    .option("delimiter", "\t")
    .option("quote", "\u0000") //magic is happening here
    .csv("/FileStore/temp.tsv")
</code>```

This was only one of several lessons I learned attempting to work with Apache Spark and emitting .csv files. For more information and context on this, please see the blog post I wrote titled "Example Apache Spark ETL Pipeline Integrating a SaaS".

Title: Spark-Csv Write quotemode not working

Body:
I am trying to write a DataFrame as a CSV file using Spark-CSV (https://github.com/databricks/spark-csv)

I am using the command below

res1.write.option("quoteMode", "NONE").format("com.databricks.spark.csv").save("File")

But my CSV file is always written as

"London"

"Copenhagen"

"Moscow"

instead of

London

Copenhagen

Moscow

Body:
Yes. The way to turn off the default escaping of the double quote character (") with the backslash character (\), you must add an .option() method call with just the right parameters after the .write() method call. The goal of the option() method call is to change how the csv() method "finds" instances of the "quote" character. To do this, you must change the default of what a "quote" actually means; i.e. change the character sought from being a double quote character (") to a Unicode "\u0000" character (essentially providing the Unicode NUL character which won't ever occur within a well formed JSON document).

val dataFrame =
  spark.sql("SELECT * FROM some_table_with_a_json_column")
val unitEmitCsv =
  dataframe
    .write
    .option("header", true)
    .option("delimiter", "\t")
    .option("quote", "\u0000") //magic is happening here
    .csv("/FileStore/temp.tsv")

This was only one of several lessons I learned attempting to work with Apache Spark and emitting .csv files. For more information and context on this, please see the blog post I wrote titled "Example Apache Spark ETL Pipeline Integrating a SaaS".


问:
Element width decreasing in one direction
I ran into situation earlier where I have a position relative container with a position absolute element inside. The element inside contains an image that has a max width of 100%. If I move this element which I have called "item" in the fiddle below using "left" the width of the element decreases the further I go to the right (does not happen if moving to the left with negative values). This happens the opposite way if use the css rule "right". If I take the width declaration off the image this no longer occurs. Does anyone know why this is the case. Here is a fiddle I created to show the issue.

```<code>.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

<div class="content">
<div class = "container">
  <div class = "item">
    <a href='https://postimg.org/image/h3h0e82rx/' target='_blank'><img src='https://s22.postimg.org/kabjxun81/banner.jpg' border='0' alt='banner'/><br /><a target='_blank' href='https://postimage.org/'></a><br /><br />
  </div>
</div>
</div>
</code>```

https://jsfiddle.net/rv9wcqh2/

An explanation would be greatly appreciated.

答:
Percentage based widths, according to the W3C, "refer to width of containing block." When you offset the child element (.item), it bases its percentage width on the remaining space within its containing block. Again, according to the spec:

Note: For absolutely positioned elements whose containing block is based on a block container element, the percentage is calculated with respect to the width of the padding box of that element. This is a change from CSS1, where the percentage width was always calculated with respect to the content box of the parent element.

Two tests to visualize this.

1: Remove the left:N on .item and instead add padding-left to one of the container elements. Will have the same effect (presuming you've set box-sizing: border-box on the container, otherwise the whole thing will grow).

1a: Double down. padding-left: 100px on the container and left: 100px on .item. Image will continue to fill 100% of the remaining space (now very small).

2: Use a px width on the image. This will keep the image the same size as the original, moved over by left: Npx. Since you have overflow: hidden on the parent, the right side of the image will be truncated by the containing block's right edge.

Edit for comment:

Unfortunately I'm struggling to understand why this decrease in width doesn't happen if I use negative values. i.e left -50% moves it to the left and item maintains it dimensions. right - 50% moves it to the right and it also keeps it's dimensions.

Yeah, it's a little odd but left: -50%, when the containing block is 400px, means the targeted element now has 600px from its left edge to the right edge of the containing block. Still, the percentage based max-width value on the targeted element remains relative to the containing block's computed width. So max-width: 100% on an element inside of a containing block that is set to width: 400px will never exceed 400px. Since it now has 600px to 'work with', it grows to its max width of 400px.

Body:
I ran into situation earlier where I have a position relative container with a position absolute element inside. The element inside contains an image that has a max width of 100%. If I move this element which I have called "item" in the fiddle below using "left" the width of the element decreases the further I go to the right (does not happen if moving to the left with negative values). This happens the opposite way if use the css rule "right". If I take the width declaration off the image this no longer occurs. Does anyone know why this is the case. Here is a fiddle I created to show the issue.

.container {
  position:relative;
  overflow:hidden;
  padding-bottom:32%;
}

.item {
  position:absolute;
}

.content {
  width:400px;
  margin:auto;

}

img {
  max-width:100%;
}

https://jsfiddle.net/rv9wcqh2/

An explanation would be greatly appreciated.


问:
How can the client connect to the server when the server is in a busy loop?
Server looks like this:

```<code>public class Server {
public static void main(String[] args) {
    Server server = new Server();
    server.start(5006);
}

private void start(int port) {
    try(ServerSocket serverSocket = new ServerSocket(port);
        Socket clientSocket = serverSocket.accept();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));) {
        String line;
        while (true) {
            while((line = bufferedReader.readLine())!=null){
                System.out.println("line = " + line);
            }
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
</code>```

The client looks like this:

```<code>public class Client {
public static void main(String[] args) {
    Client client = new Client();
    client.start("localhost", 5006);
}

private void start(String localhost, int port) {
    Random random = new Random();
    try (Socket socket = new Socket(localhost, port);
         BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"))) {
        while (true) {
            int i = random.nextInt();
            bufferedWriter.write(String.valueOf(i));
            bufferedWriter.newLine();
            System.out.println("i = " + i);

            //sleep(bufferedWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void sleep(BufferedWriter bufferedWriter) throws Exception{
        //bufferedWriter.flush(); //Has to enabled if the wait below is to work
        TimeUnit.SECONDS.sleep(3);
}
</code>```

Context:

As is evident from the code, the server is single threaded. It accepts a connection from the client and goes into a busy loop processing data from the client socket. The server is intentionally handicapped.

Running one instance of the client program works as intended. The client ends random integers and the same are printed on the server's console.

Questions:

1) While one instance of the client is still running, spin up another instance of the client program.

How is this instance of the client able to connect to the server when the server is still in the busy loop (while(true))?
The client goes so far as to fill up the buffered writer and then just hangs; waiting for the server to consume the stream.

2) In the client program, uncomment the 'sleep' method and re-run.

The client program hangs. The server does not receive anything. Why? I just want to write to the buffer every 3 seconds. Nonsensical but let's suppose it is a sane thing to do for arguments sake. I also put in the sleep after we send the new line to the server just to make sure the server prints its input.

If you uncomment the flush in the sleep method, it starts working again. Why?

答:
1) Two clients:

A. Client 1 steps:

(As EJP said), Connection established on OS level and placed in backlog queue.
Then it is waiting for ServerSocket to pick it and start reading from clientSocket InputStream

Client 1 writes data to its socket OutputStream - server's reader reads data from clientSocket InputStream
Server is busy, because infinite loop.

B. Client 2 steps:

(As EJP said), Connection established on OS level and placed in backlog queue.

By this code it will never be picked by ServerSocket. Server is indefinitely busy with indefinitely open Socket to Client 1.

All data written from Client 2 stays in the buffer on Client 2 side.

Note: Client 2 will never go beyond that point with current code even if Client 1 process be killed and connection from it to server be broken, server will end. There is no second accept() call to process request from Client 2

2) flush

when Client writes bytes to its socket OutputStream bytes goes to the buffer first not over network to the server.

flush forces OutputStream to send whatever is in the buffer at this moment.

Without flush data be send to the server when buffer is full.

If you do not have flush somewhere in the code flow, server never receives anything. It keeps waiting for data indefinitely in current code. But all data stay in buffer at client side waiting for flush or buffer be full.

3)

The client program hangs.

Assumption is not correct. Client program does not hang. It is running  and fill the buffer, but nothing sends to the server until buffer is full.

With or without flush it does not matter is there sleep or not.

"No sleep" - buffer fills very quickly. "sleep" buffer fills once per 3 sec. It just need a time to fill the buffer.

If you uncomment the flush in the sleep method, it starts working again. Why?

Only server starts receiving data earlier, because client does not wait to fill the buffer to send data and flushes buffer after each write.

Body:
Server looks like this:

public class Server {
public static void main(String[] args) {
    Server server = new Server();
    server.start(5006);
}

private void start(int port) {
    try(ServerSocket serverSocket = new ServerSocket(port);
        Socket clientSocket = serverSocket.accept();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));) {
        String line;
        while (true) {
            while((line = bufferedReader.readLine())!=null){
                System.out.println("line = " + line);
            }
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

The client looks like this:

public class Client {
public static void main(String[] args) {
    Client client = new Client();
    client.start("localhost", 5006);
}

private void start(String localhost, int port) {
    Random random = new Random();
    try (Socket socket = new Socket(localhost, port);
         BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"))) {
        while (true) {
            int i = random.nextInt();
            bufferedWriter.write(String.valueOf(i));
            bufferedWriter.newLine();
            System.out.println("i = " + i);

            //sleep(bufferedWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void sleep(BufferedWriter bufferedWriter) throws Exception{
        //bufferedWriter.flush(); //Has to enabled if the wait below is to work
        TimeUnit.SECONDS.sleep(3);
}

Context:

As is evident from the code, the server is single threaded. It accepts a connection from the client and goes into a busy loop processing data from the client socket. The server is intentionally handicapped.

Running one instance of the client program works as intended. The client ends random integers and the same are printed on the server's console.

Questions:

1) While one instance of the client is still running, spin up another instance of the client program.

How is this instance of the client able to connect to the server when the server is still in the busy loop (while(true))?
The client goes so far as to fill up the buffered writer and then just hangs; waiting for the server to consume the stream.

2) In the client program, uncomment the 'sleep' method and re-run.

The client program hangs. The server does not receive anything. Why? I just want to write to the buffer every 3 seconds. Nonsensical but let's suppose it is a sane thing to do for arguments sake. I also put in the sleep after we send the new line to the server just to make sure the server prints its input.

If you uncomment the flush in the sleep method, it starts working again. Why?


问:
Get the last record in a belongsToMany association
I have a belongsToMany association between Appointment and Status models. The below query returns all of the statuses and I want to alter it to pull the last status assigned to the appointment.

```<code>$query = Appointment::query();
            $query->with('statuses');
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);
</code>```

I have tried altering the query with this but it doesn't work.

```<code>$query->with('statuses')->latest();
</code>```

This is my raw query:

```<code>select * from `users` where `users`.`id` = '1' limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments`) count_row_table

select * from `appointments` limit 100 offset 0

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc

select * from `agents` where `agents`.`id` in ('1')

select * from `instruction_types` where `instruction_types`.`id` in ('1')

select * from `organisations` where `organisations`.`id` in ('1')
</code>```

So this works, but it runs two queries on Statuses

```<code>$query = Appointment::with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);
</code>```

答:
try

```<code>$query->with(["statuses"=>function($q){
    $q->latest();
}])->get()
</code>```

not tested but guess it should work

Body:
I have a belongsToMany association between Appointment and Status models. The below query returns all of the statuses and I want to alter it to pull the last status assigned to the appointment.

$query = Appointment::query();
            $query->with('statuses');
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

I have tried altering the query with this but it doesn't work.

$query->with('statuses')->latest();

This is my raw query:

select * from `users` where `users`.`id` = '1' limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments`) count_row_table

select * from `appointments` limit 100 offset 0

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc

select * from `agents` where `agents`.`id` in ('1')

select * from `instruction_types` where `instruction_types`.`id` in ('1')

select * from `organisations` where `organisations`.`id` in ('1')

So this works, but it runs two queries on Statuses

$query = Appointment::with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

Body:
try

$query->with(["statuses"=>function($q){
    $q->latest();
}])->get()

not tested but guess it should work