问:
How to convert List of Maps to CSV
I need to convert List of Maps to CSV object which should like below

```<code>List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
</code>```

maps object contains the value in below format

map 1 :

```<code>(header 1, value1)

(header 2, value2)

(header 3, value3)

(header 4, value4)
</code>```

map 2 :

```<code>(header 1, value5)

(header 2, value6)

(header 3, value7)

(header 4, value8)
</code>```

I am looking for CSV which should like below

```<code>header1, header2,header3, header4

value1, value2,value3,value4

value5,value6,value7,value8
</code>```

I have tried to read the map (key, value) and writing to CSV files, but its writing to the format

header 1, value1

header2, value2

header 3,value3

header4,value4

header1,value5

like this below is the code snippet which I have tried for

```<code>(Map<String, Object> map : maps) {

 for (Map.Entry<String, Object> entry : map.entrySet()) {

w.append(entry.getKey()).append(",").append(entry.getValue().toString()).append("\n"); } }
</code>```

答:
the following code solves your problem:</p>

```<code>import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class SomeMaps {

    public static void main(String[] args) {
        Map<String, String> firstMap = new HashMap<>();
        Map<String, String> secondMap = new HashMap<>();

        firstMap.put("header 1", "value1");
        firstMap.put("header 2", "value2");
        firstMap.put("header 3", "value3");
        firstMap.put("header 4", "value4");

        secondMap.put("header 1", "value5");
        secondMap.put("header 2", "value6");
        secondMap.put("header 3", "value7");
        secondMap.put("header 4", "value8");

        List<Map<String, String>> maps = new ArrayList<>();
        maps.add(firstMap);
        maps.add(secondMap);

        // extract all headers
        SortedSet<String> keys = new TreeSet<>(firstMap.keySet());
        for(Map<String, String> map : maps){
            keys.addAll(map.keySet());
        }

        String header = StringUtils.join(keys, ",");
        System.out.println(header);

        // generate content of CSV file
        for(Map<String, String> map : maps){
            String line = getLineFromMap(map, keys);
            System.out.println(line);
        }
    }

    private static String getLineFromMap(Map<String, String> someMap, SortedSet<String> keys) {
        List<String> values = new ArrayList<>();
        for (String key : keys) {
            values.add(someMap.get(key) == null ? " " : someMap.get(key));
        }
        return StringUtils.join(values, ",");
    }
}
</code>```

Title: How to convert List of Maps to CSV

Body:
I need to convert List of Maps to CSV object which should like below

List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();

maps object contains the value in below format

map 1 :

(header 1, value1)

(header 2, value2)

(header 3, value3)

(header 4, value4)

map 2 :

(header 1, value5)

(header 2, value6)

(header 3, value7)

(header 4, value8)

I am looking for CSV which should like below

header1, header2,header3, header4

value1, value2,value3,value4

value5,value6,value7,value8

I have tried to read the map (key, value) and writing to CSV files, but its writing to the format

header 1, value1

header2, value2

header 3,value3

header4,value4

header1,value5

like this below is the code snippet which I have tried for

(Map<String, Object> map : maps) {

 for (Map.Entry<String, Object> entry : map.entrySet()) {

w.append(entry.getKey()).append(",").append(entry.getValue().toString()).append("\n"); } }

Body:
the following code solves your problem:

import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class SomeMaps {

    public static void main(String[] args) {
        Map<String, String> firstMap = new HashMap<>();
        Map<String, String> secondMap = new HashMap<>();

        firstMap.put("header 1", "value1");
        firstMap.put("header 2", "value2");
        firstMap.put("header 3", "value3");
        firstMap.put("header 4", "value4");

        secondMap.put("header 1", "value5");
        secondMap.put("header 2", "value6");
        secondMap.put("header 3", "value7");
        secondMap.put("header 4", "value8");

        List<Map<String, String>> maps = new ArrayList<>();
        maps.add(firstMap);
        maps.add(secondMap);

        // extract all headers
        SortedSet<String> keys = new TreeSet<>(firstMap.keySet());
        for(Map<String, String> map : maps){
            keys.addAll(map.keySet());
        }

        String header = StringUtils.join(keys, ",");
        System.out.println(header);

        // generate content of CSV file
        for(Map<String, String> map : maps){
            String line = getLineFromMap(map, keys);
            System.out.println(line);
        }
    }

    private static String getLineFromMap(Map<String, String> someMap, SortedSet<String> keys) {
        List<String> values = new ArrayList<>();
        for (String key : keys) {
            values.add(someMap.get(key) == null ? " " : someMap.get(key));
        }
        return StringUtils.join(values, ",");
    }
}


来源: stackexchange

问:
Elasticsearch 5 connector in Apache Flink 1.3
By reading the documentation I understood that with Apache Flink 1.3 I should be able to use Elasticsearch 5.x.

However, in my pom.xml :

```<code>    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-elasticsearch5_2.10</artifactId>
        <version>1.3.0</version>
    </dependency>
</code>```

I got this :

Dependency
  "org.apache.flink:flink-connector-elasticsearch5_2.10:1.3.0" not found

Any idea why this dependency is unfound ?

答: This was a bug in the 1.3.0 release and is being fixed for 1.3.1 (which is due very soon). See the mailing list for more details.</p>

ContentLicense: CC BY-SA 3.0

Body:
By reading the documentation I understood that with Apache Flink 1.3 I should be able to use Elasticsearch 5.x.

However, in my pom.xml :

    <dependency>
        <groupId>org.apache.flink</groupId>
        <artifactId>flink-connector-elasticsearch5_2.10</artifactId>
        <version>1.3.0</version>
    </dependency>

I got this :

Dependency
  "org.apache.flink:flink-connector-elasticsearch5_2.10:1.3.0" not found

Any idea why this dependency is unfound ?


问:
Convert date/time into timestamp
I want to convert following date and time, into a timestamp 13 digits. Note I use strict mode.

Date:

Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)

Time:
03:00

I tried to use Date.parse() but it was not working. What is the best way to do this?

答:
Try below code

console.log(new Date().getTime());```

Title: Convert date/time into timestamp


问:
DisplayMembers in ListBox - Not displaying anything
In Form1, why isn't myListBox displaying my name property inside of class Student

Form1

```<code>private static List<Student> studentListHome = new List<Student>();

...

public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                studentListBox.DisplayMember = "name";
            }
        }

    private void refreshButton_Click(object sender, EventArgs e)
            {
                BindData();
            }
</code>```

Student

```<code>    private string name;

    public string Name
            {
                get
                {
                    return name;
                }
            }
...

public Student(string _name, int _id, string _bday)
        {
            name = _name;
            id = _id;
            bday = _bday;
        }
</code>```

答:
Because 'name' is a private string.

Try using 'Name' which is your property.

```<code>studentListBox.DisplayMember = "Name";
</code>```

Body:
In Form1, why isn't myListBox displaying my name property inside of class Student

Form1

private static List<Student> studentListHome = new List<Student>();

...

public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                studentListBox.DisplayMember = "name";
            }
        }

    private void refreshButton_Click(object sender, EventArgs e)
            {
                BindData();
            }

Student

    private string name;

    public string Name
            {
                get
                {
                    return name;
                }
            }
...

public Student(string _name, int _id, string _bday)
        {
            name = _name;
            id = _id;
            bday = _bday;
        }

Body:
Because 'name' is a private string.

Try using 'Name' which is your property.

studentListBox.DisplayMember = "Name";


问:
Do I need to open my source code if I use OpenJDK as JVM?
With the current developments regarding Oracle announcing its intention to charge for a pro (or whatever you call it) version of JVM, and IBM announcing its intention to support OpenJDK, things are getting quite complicated for a large set of Java developers.
We have a large piece of work in Java, and we did not have any issues in choosing our licensing terms up until now. It appears that we'll have to switch to OpenJDK where IBM will be putting their support. But OpenJDK is GPL V2, and as far as I know, any code linking to GPL V2 must be GPL V2.
We also have some JNI code, which is going to get even larger. Given these facts, does it mean that if we use OpenJDK to run our software, we'll have to switch to GPL for our licensing?
Needless to say, this would blow away our whole licensing & business model setup. </p>

答:
Please read the lines at the beginning of the classpath exception. The classpath exception doesn't seem to apply to the entire library.

Certain source files distributed by Sun Microsystems, Inc.  are subject to the following clarification and special exception to the GPL, but only where Sun has expressly included in the particular source file's header the words "Sun designates this particular file as subject to the "Classpath" exception as provided by Sun in the LICENSE file that accompanied this code."

ContentLicense: CC BY-SA 2.5


问:
Why we extends WCMUsePojo class while working with AEM?
Why we extends WCMUsepojo abstract class in our program while working with AEM?

What is the advantage of using this class?

答:
While the previous answer gives a pretty good explanation, I will write my own - brief one:

You can use simple Pojo (do not extend any Adobe's class) with java-use-api. But in this case, you will not be able to easily access resources/services.

You can extend WCMUsePojo to get the ability to use resources/services.

Also, you can go with Sling Models way which will give you more flexibility.


问:
How to unBlur square portion of Blurry image on touch android
What I want to do:

On mouse hover of Blurry image, it shows unblur same image in square shape like following image. (image is completely blur, on mouse hover unblur image shown in square shape)

What I have done:

I set blur image using following code (link) using PorterDuff.Mode.  On touch of screen mouse pointer converted into square and image shows unblur.

Edit:

Problem:

Now picture is unblur but i cant find proper blur effect on blurry image and unblur image is also not clear, on touch is not working properly.

My Code:

using custom view and following methods i'm able to blur and unblur  image but still there's not completely satisfied with output.

```<code>@Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(mTutorialColor);
        if (mCx >= 0 && mCy >= 0) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;
            // canvas.drawCircle(mCx, mCy, RADIUS, mBackgroundPaint);
            canvas.drawRect(mCx, mCy, mCx + width, mCy + 250, mBackgroundPaint);
        }

    }

private void init() {
        setWillNotDraw(false);
        setLayerType(LAYER_TYPE_HARDWARE, null);
        mBackgroundPaint = new Paint();
        mBackgroundPaint.setColor(getResources().getColor(android.R.color.transparent));
        mBackgroundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }
</code>```

Is there any other way to achieve this?

答:
You need to implement it differently.

You need two images (instead of one):

Blurred one. Which will be always drawn as background (or in a view underneath). Read here how to blur the image.

Normal one. This one should be drawn on top of blurred one using the square mask. Check this answer.

MORE DETAILS:

It can be done in the same way, how I explained in this answer, but with Mode.DST_IN Xfermode instead of PorterDuff.Mode.CLEAR.

Hope this will help you.

Body:
What I want to do:

On mouse hover of Blurry image, it shows unblur same image in square shape like following image. (image is completely blur, on mouse hover unblur image shown in square shape)

What I have done:

I set blur image using following code (link) using PorterDuff.Mode.  On touch of screen mouse pointer converted into square and image shows unblur.

Edit:

Problem:

Now picture is unblur but i cant find proper blur effect on blurry image and unblur image is also not clear, on touch is not working properly.

My Code:

using custom view and following methods i'm able to blur and unblur  image but still there's not completely satisfied with output.

@Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(mTutorialColor);
        if (mCx >= 0 && mCy >= 0) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;
            // canvas.drawCircle(mCx, mCy, RADIUS, mBackgroundPaint);
            canvas.drawRect(mCx, mCy, mCx + width, mCy + 250, mBackgroundPaint);
        }

    }

private void init() {
        setWillNotDraw(false);
        setLayerType(LAYER_TYPE_HARDWARE, null);
        mBackgroundPaint = new Paint();
        mBackgroundPaint.setColor(getResources().getColor(android.R.color.transparent));
        mBackgroundPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    }

Is there any other way to achieve this?


问:
To subtract two dates without Using DateAdd Function or DateDiff Function
How i got this output, can you please explain the reason behind it?

```<code>declare @a datetime = '2017-06-08 16:02:22.467',
        @b datetime = '2017-10-23 00:00:00.000'

select DAY(@a - @b)

select @a - @b
</code>```

Output:

```<code>17
1899-08-17 16:02:22.467
</code>```

答:
Disclaimer: The information in this answer is relevant only to the DateTime data type. It doesn't apply to the newer data types (DateTime2 , Date and Time).

Well, dates in sql server are stored as the number of days since 1900-01-01.

You can see it if you run this query:

```<code>SELECT CAST(0 as datetime)
</code>```

You'll get 1900-01-01 00:00:00 as the result.

Time is stored as the number of ticks since midnight.

There are 300 ticks per second.

Since the date in @a is before the date in @b, you get a negative result for the date (-137), and that number is then added to 01-01-1900 to give you 1899-08-17. The time in @a is after the time in @b, and since the time in @b is midnight, you get the time of @a in the result.

Body:
How i got this output, can you please explain the reason behind it?

declare @a datetime = '2017-06-08 16:02:22.467',
        @b datetime = '2017-10-23 00:00:00.000'

select DAY(@a - @b)

select @a - @b

Output:

17
1899-08-17 16:02:22.467

Body:
Disclaimer: The information in this answer is relevant only to the DateTime data type. It doesn't apply to the newer data types (DateTime2 , Date and Time).

Well, dates in sql server are stored as the number of days since 1900-01-01.

You can see it if you run this query:

SELECT CAST(0 as datetime)

You'll get 1900-01-01 00:00:00 as the result.

Time is stored as the number of ticks since midnight.

There are 300 ticks per second.

Since the date in @a is before the date in @b, you get a negative result for the date (-137), and that number is then added to 01-01-1900 to give you 1899-08-17. The time in @a is after the time in @b, and since the time in @b is midnight, you get the time of @a in the result.

ContentLicense: CC BY-SA 4.0


问:
Insert angular2 components in Svg
I recently started web dev. and angular2 in particular.
I must say that this framework is fantastic!

But I have one challenge that I cant figure out how to solve in the best way:

I want to build my web app with angular2 (datamodels, common services etc.).
But for the "main area screens" templates, I want to design in svg, drawing the static lines and circles etc with wysiwyg.
Then I want to embed all my different angular components to these "main area screens" svg pages. This is because our layout is not typical grid style, and the different components need to be placed on "pixel precision" over the staic svg background.

I have searched the web for different approaches, but nothing seems to solve my challenge.

Is it possible to embed angular2 components inside svg, and then add the svg to an angular template?

答:
Yes it is possible to add the svg as angular 2 components :

you can try this.

defining your circle component

```<code>@Component({
    selector: 'g[circle]',
    templateUrl: './circle.component.html',
    styleUrls: ['./circle.component.scss']
})
</code>```

circle.component.hmtl :

```<code><svg:circle
            [attr.cx]="circle?.x"
            [attr.cy]="circle?.y"
            [attr.r]="radius"

            [attr.fill]="circle?.fill"
             />
</code>```

and your root html will be like

```<code><svg>
<g circle *ngFor="let circle of circles"
                    [attr.fill-opacity]="opacity"
                    [attr.transform]="scale"
                    [circle]="circle"
                     />
</svg>
</code>```

similarly you can use all the other svg shapes by creating similar components with selector as defied above.

You can use this library which provides all the svg elements

https://www.npmjs.com/package/angular-svg

Title: Insert angular2 components in Svg

Body:
Yes it is possible to add the svg as angular 2 components :

you can try this.

defining your circle component

@Component({
    selector: 'g[circle]',
    templateUrl: './circle.component.html',
    styleUrls: ['./circle.component.scss']
})

circle.component.hmtl :

<svg:circle
            [attr.cx]="circle?.x"
            [attr.cy]="circle?.y"
            [attr.r]="radius"

            [attr.fill]="circle?.fill"
             />

and your root html will be like

<svg>
<g circle *ngFor="let circle of circles"
                    [attr.fill-opacity]="opacity"
                    [attr.transform]="scale"
                    [circle]="circle"
                     />
</svg>

similarly you can use all the other svg shapes by creating similar components with selector as defied above.

You can use this library which provides all the svg elements

https://www.npmjs.com/package/angular-svg


问:
What is the equivalent of the C# 'var' keyword in Java?
One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?

答:
If you add Lombok to your project you can use its val keyword.

http://projectlombok.org/features/val.html


答:
You can use the getTime function:

console.log(new Date('Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)').getTime());```

Title: Convert date/time into timestamp

Body:
I want to convert following date and time, into a timestamp 13 digits. Note I use strict mode.

Date:

Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)

Time:
03:00

I tried to use Date.parse() but it was not working. What is the best way to do this?


问:
Unable to perform click on the "PrestaShop" link in an IFrame like picture shown below
Am having an issue where I need to perform a click using Selenium Java on the link "PrestaShop" shown below. It's in an IFrame and my code is also below the picture.

Link to be clicked

When inspect the link using FireBug, it shows like below

Inspect using FireBug

And below is my code

```<code>try {
                List<WebElement> frames = getAllFrames();
                for (int i = 0; i < frames.size(); i++) {

                    WebElement frame = frames.get(i);
                    driver.switchTo().frame(frame);

                    if (driver.findElement(By.xpath(".//*[@classname='_1drp _5lv6']/a")).getSize() != null) {
                        driver.findElement(By.className(".//*[@classname='_1drp _5lv6']/a")).click();
                    } else {
                        driver.switchTo().defaultContent();
                    }

                }
            } catch (NoSuchElementException ex) {
                System.out.println(ex.getMessage());
            }
</code>```

The code is getting all frames on the page and verify if the link "PrestaShop" is presence on the frame. If yes then it needs to fire a click on the link. Now, instead it returns error message - Unable to locate element: .//*[@classname='_1drp _5lv6']/a

Can please help to advise how can I fire the click successfully on the link?

答:
thanks for your comment. I realized its because of the FB link was loaded too slow and hence the code fails. It's able to click now with below code if I added a Thread.sleep(30000) there.

```<code>if (driver.findElements(By.xpath(".//*[@class='lfloat']/div/a")).size() > 0) {
                    System.out.println("Found elements.");
                    driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
                } else {
                    System.out.println("Element not found.");
                    driver.switchTo().defaultContent();
                }
</code>```

However, if I want a FluentWait, then below code will just stop if the condition was not met

```<code>if (wait.ignoring(StaleElementReferenceException.class).ignoring(TimeoutException.class)
                        .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@class='lfloat']/div/a")))
                        .isDisplayed()) {
                    System.out.println("Found elements.");
                    driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
                } else {
                    System.out.println("Element not found.");
                    driver.switchTo().defaultContent();
                }
</code>```

It just return message Expected condition failed: waiting for visibility of element located by By.xpath: .//*[@class='lfloat']/div/a (tried for 30 second(s) with 500 MILLISECONDS interval) and then not continue the loop. Can I know what's the way to make the code to continue even if the condition was not met?

Body:
Am having an issue where I need to perform a click using Selenium Java on the link "PrestaShop" shown below. It's in an IFrame and my code is also below the picture.

Link to be clicked

When inspect the link using FireBug, it shows like below

Inspect using FireBug

And below is my code

try {
                List<WebElement> frames = getAllFrames();
                for (int i = 0; i < frames.size(); i++) {

                    WebElement frame = frames.get(i);
                    driver.switchTo().frame(frame);

                    if (driver.findElement(By.xpath(".//*[@classname='_1drp _5lv6']/a")).getSize() != null) {
                        driver.findElement(By.className(".//*[@classname='_1drp _5lv6']/a")).click();
                    } else {
                        driver.switchTo().defaultContent();
                    }

                }
            } catch (NoSuchElementException ex) {
                System.out.println(ex.getMessage());
            }

The code is getting all frames on the page and verify if the link "PrestaShop" is presence on the frame. If yes then it needs to fire a click on the link. Now, instead it returns error message - Unable to locate element: .//*[@classname='_1drp _5lv6']/a

Can please help to advise how can I fire the click successfully on the link?

Body:
thanks for your comment. I realized its because of the FB link was loaded too slow and hence the code fails. It's able to click now with below code if I added a Thread.sleep(30000) there.

if (driver.findElements(By.xpath(".//*[@class='lfloat']/div/a")).size() > 0) {
                    System.out.println("Found elements.");
                    driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
                } else {
                    System.out.println("Element not found.");
                    driver.switchTo().defaultContent();
                }

However, if I want a FluentWait, then below code will just stop if the condition was not met

if (wait.ignoring(StaleElementReferenceException.class).ignoring(TimeoutException.class)
                        .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@class='lfloat']/div/a")))
                        .isDisplayed()) {
                    System.out.println("Found elements.");
                    driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
                } else {
                    System.out.println("Element not found.");
                    driver.switchTo().defaultContent();
                }

It just return message Expected condition failed: waiting for visibility of element located by By.xpath: .//*[@class='lfloat']/div/a (tried for 30 second(s) with 500 MILLISECONDS interval) and then not continue the loop. Can I know what's the way to make the code to continue even if the condition was not met?


问:
Capitalise the first letter of every word as user types unless user insists on lower case
I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W"  from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<textarea></textarea></code>```

答:
Please check this.

jsfiddle.net/madhudvmask007/p4srb3mq

Problem here is, If i am using cursor pointer the delete first letter. After i delete the first letter cursor is pointing at the end of the string. I want pointer to be placed at the start if start.
Need solution for this.

Thank you!!

Body:
I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W"  from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();

<textarea></textarea>


问:
Javascript - how to animate scrollIntoView
I was only able to get a div on click into view with the scrollIntoView function, and it works as it should, just the way I want it, but I wonder is there a way to somehow animate it, and make it a bit slower?

I have tried with a suggestion from here:

```<code>function scroll(element, parent){
      $(parent)[0].scrollIntoView(false);
      $(parent).animate({
         scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top,
         duration: 500,
         easing: 'swing'
       });
    }
</code>```

But it pushes the element to far up, it is not pushing it as it is on just:

```<code>$('#drawer')[0].scrollIntoView(false);
</code>```

答:
```<code>scroll = function(element, parent, time) {
   $(parent).animate({
       scrollTop: $(element)[0].offsetTop - $(parent)[0].offsetTop,
   }, time, "swing");
}
</code>```

You might want to add scrollIntoView, i don't know what that is for.
This works in jQuery 3.1.1 .

Body:
I was only able to get a div on click into view with the scrollIntoView function, and it works as it should, just the way I want it, but I wonder is there a way to somehow animate it, and make it a bit slower?

I have tried with a suggestion from here:

function scroll(element, parent){
      $(parent)[0].scrollIntoView(false);
      $(parent).animate({
         scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top,
         duration: 500,
         easing: 'swing'
       });
    }

But it pushes the element to far up, it is not pushing it as it is on just:

$('#drawer')[0].scrollIntoView(false);

Body:
scroll = function(element, parent, time) {
   $(parent).animate({
       scrollTop: $(element)[0].offsetTop - $(parent)[0].offsetTop,
   }, time, "swing");
}

You might want to add scrollIntoView, i don't know what that is for.
This works in jQuery 3.1.1 .


问:
Slowness when chaining LINQ queries
I am doing chaining LINQ queries as show below. I am trying to find out the cause for the slowness of query.ToList();. The SQL queries are fast (milliseconds), but the code takes a minute. The reason for chaining is to reuse the repository function.

Is there any obvious reasons for slowness here?

How could I optimize this ?

How can I check the actual SQL query executed when
running query.ToList();?

```<code>//Client
var query = _service.GetResultsByStatus(status, bType, tType);
var result = query.ToList(); //takes a long time to execute

//Service function
 public IEnumerable<CustomResult> GetResultsByStatus(string status, string bType, string tType) {
    IEnumerable<CustomResult> result = null;
    result = repo.GetResults(bType).Where(item => item.tStatus == status && (tType == null || item.tType == tType))
        .Select(item => new CustomResult {
           A = item.A,
           B = item.B,
        });
    return result;
}

// Repository Function (reused in many places)
public IEnumerable<my_model> GetResults(string bType) {
     return from p in dbContext.my_model()
         where p.bType.Equals(bType)
         select p;
}
</code>```

答:
Your .Where(item => item.tStatus == status && (tType == null || item.tType == tType)) and the .Select are being done "locally" on your PC... Tons of useless rows and columns are being returned by the SQL to be then "filtered" on your PC.

```<code>public IEnumerable<my_model> GetResults(string bType) {
     return from p in dbContext.my_model()
         where p.bType.Equals(bType)
         select p;
}
</code>```

Change it to

```<code>public IQueryable<my_model> GetResults(string bType) {
</code>```

Normally IEnumerable<> means "downstream LINQ will be executed locally", IQueryable<> means "downstream LINQ will be executed on a server". In this case the Where and the Select are "downstream" from the transformation of the query in a IEnumerable<>. Note that while it is possible (and easy) to convert an IQueryable<> to an IEnumerable<>, the opposite normally isn't possible. The AsQueryable<> creates a "fake" IQueryable<> that is executed locally and is mainly useful in unit tests.

Title: Slowness when chaining LINQ queries

Body:
I am doing chaining LINQ queries as show below. I am trying to find out the cause for the slowness of query.ToList();. The SQL queries are fast (milliseconds), but the code takes a minute. The reason for chaining is to reuse the repository function.

Is there any obvious reasons for slowness here?

How could I optimize this ?

How can I check the actual SQL query executed when
running query.ToList();?

//Client
var query = _service.GetResultsByStatus(status, bType, tType);
var result = query.ToList(); //takes a long time to execute

//Service function
 public IEnumerable<CustomResult> GetResultsByStatus(string status, string bType, string tType) {
    IEnumerable<CustomResult> result = null;
    result = repo.GetResults(bType).Where(item => item.tStatus == status && (tType == null || item.tType == tType))
        .Select(item => new CustomResult {
           A = item.A,
           B = item.B,
        });
    return result;
}

// Repository Function (reused in many places)
public IEnumerable<my_model> GetResults(string bType) {
     return from p in dbContext.my_model()
         where p.bType.Equals(bType)
         select p;
}

Body:
Your .Where(item => item.tStatus == status && (tType == null || item.tType == tType)) and the .Select are being done "locally" on your PC... Tons of useless rows and columns are being returned by the SQL to be then "filtered" on your PC.

public IEnumerable<my_model> GetResults(string bType) {
     return from p in dbContext.my_model()
         where p.bType.Equals(bType)
         select p;
}

Change it to

public IQueryable<my_model> GetResults(string bType) {

Normally IEnumerable<> means "downstream LINQ will be executed locally", IQueryable<> means "downstream LINQ will be executed on a server". In this case the Where and the Select are "downstream" from the transformation of the query in a IEnumerable<>. Note that while it is possible (and easy) to convert an IQueryable<> to an IEnumerable<>, the opposite normally isn't possible. The AsQueryable<> creates a "fake" IQueryable<> that is executed locally and is mainly useful in unit tests.


问:
Android Emulator is not working in Android Studio 2.3.2
I am trying run my emulator in Android Studio 2.3.2. It's just coming like this

and then closing the window. But not launching the emulator.

Here are the details of AVD.

Name: 5.4_FWVGA_API_22
  CPU/ABI: Google APIs Intel Atom (x86)
  Path: C:\Users\vinod.android\avd\5.4_FWVGA_API_22.avd

Target: google_apis [Google APIs] (API level 22)

Skin: 480x854

SD Card: 100M

hw.dPad: no

runtime.network.speed: full

hw.accelerometer: yes

hw.device.name: 5.4in FWVGA

vm.heapSize: 48

skin.dynamic: yes

hw.device.manufacturer: Generic

hw.gps: yes

hw.initialOrientation: Portrait

skin.path.backup: _no_skin

image.androidVersion.api: 22

hw.audioInput: yes

image.sysdir.1: system-images\android-22\google_apis\x86\

tag.id: google_apis

showDeviceFrame: no

hw.camera.back: emulated

hw.mainKeys: yes

AvdId: 5.4_FWVGA_API_22

hw.camera.front: emulated

hw.lcd.density: 160

avd.ini.displayname: 5.4  FWVGA API 22

hw.gpu.mode: auto

hw.device.hash2: MD5:fbd5143f5b48ba972391c87c302c0c69

hw.ramSize: 512

hw.trackBall: no

PlayStore.enabled: false

hw.battery: yes

hw.cpu.ncore: 2

hw.sdCard: yes

tag.display: Google APIs

runtime.network.latency: none

hw.keyboard: yes

hw.sensors.proximity: yes

disk.dataPartition.size: 800M

hw.sensors.orientation: yes

avd.ini.encoding: UTF-8

hw.gpu.enabled: yes

Here is my sdk tools details:

答:
If using Linux, create a symlink for it:

ln -sf /usr/lib/libstdc++.so.6  /$HOME/Android/Sdk/emulator/lib64/libstdc++/libstdc++.so.6


问:
Div tag get down while hover it
While I hover Div tag, Another Div tag will appear in front of the prev Div. When i didn't put any words, it works. but when i put h3 tag, the div goes down.

here is the HTML

```<code><div id="content">
    <h1 class="head-content">Biscuits</h1>
    <div class="line"></div>
    <a href="#">
        <div class="list-content">
            <div class="detail-content">
                <h3>Biscuits 1</h3>
                <p>Price: IDR 12000</p>
            </div>
        </div>
    </a>
    <a href="#">
        <div class="list-content">
            <div class="detail-content">

            </div>
        </div>
    </a>
    <a href="#">
        <div class="list-content">
            <div class="detail-content">

            </div>
        </div>
    </a>
</div>
</code>```

here is CSS

```<code>#content{
        width:50%;
    }
    .line{
        border-top: 5px solid black;
    }
    .list-content{
        display:inline-block;
        width:25%;
        height:200px;
        background-color: black;
        margin-top: 10px;
    }
    .detail-content{
        display: none;
    }
    .list-content:hover .detail-content{
        display: block;
        width:100%;
        height:75%;
        background-color: rgba(255,255,255,0.6);
    }
</code>```

thank you before

答:
@James Please find following code. I hope you are expecting the same. Just replaced "display:inline-block;" with "float:left;" and took class "list-content" in anchor tag itself.

#content{
        width:50%;
    }
    .line{
        border-top: 5px solid black;
    }
    .list-content{
        float:left;
        width:25%;
        height:200px;
        background-color: black;
        margin-top: 10px;
        margin-right:10px;
    }
    .detail-content{
        display: none;
    }
    .list-content:hover .detail-content{
        display: block;
        width:100%;
        height:75%;
        background-color: rgba(255,255,255,0.6);
    }
   .clearfix{
   clear:both;
   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
    <h1 class="head-content">Biscuits</h1>
    <div class="line"></div>
  <div class="clearfix">

        <div class="detail-content">
                <h3>Biscuits 1</h3>
                <p>Price: IDR 12000</p>
            </div>

        <div class="detail-content">

            </div>

            <div class="detail-content">

            </div>

   </div>
</div></code>```

Title: Div tag get down while hover it

Body:
While I hover Div tag, Another Div tag will appear in front of the prev Div. When i didn't put any words, it works. but when i put h3 tag, the div goes down.

here is the HTML

Biscuits

Biscuits 1

Price: IDR 12000

here is CSS

#content{
        width:50%;
    }
    .line{
        border-top: 5px solid black;
    }
    .list-content{
        display:inline-block;
        width:25%;
        height:200px;
        background-color: black;
        margin-top: 10px;
    }
    .detail-content{
        display: none;
    }
    .list-content:hover .detail-content{
        display: block;
        width:100%;
        height:75%;
        background-color: rgba(255,255,255,0.6);
    }

thank you before

Body:
@James Please find following code. I hope you are expecting the same. Just replaced "display:inline-block;" with "float:left;" and took class "list-content" in anchor tag itself.

#content{
        width:50%;
    }
    .line{
        border-top: 5px solid black;
    }
    .list-content{
        float:left;
        width:25%;
        height:200px;
        background-color: black;
        margin-top: 10px;
        margin-right:10px;
    }
    .detail-content{
        display: none;
    }
    .list-content:hover .detail-content{
        display: block;
        width:100%;
        height:75%;
        background-color: rgba(255,255,255,0.6);
    }
   .clearfix{
   clear:both;
   }

<div id="content">
    <h1 class="head-content">Biscuits</h1>
    <div class="line"></div>
  <div class="clearfix">
    <a href="#" class="list-content">
        <div class="detail-content">
                <h3>Biscuits 1</h3>
                <p>Price: IDR 12000</p>
            </div>
    </a>
    <a href="#" class="list-content">
        <div class="detail-content">

            </div>
    </a>
    <a href="#" class="list-content">

            <div class="detail-content">

            </div>

    </a>
   </div>
</div>


问:
Python requests library using TLSv1 or TLSv1.1 despite upgrading to Python 2.7
I wanted to make sure that when using requests library to post to an HTTP server, it would refuse to communicate using TLSv1 or TLSv1.1.  To do this, I configured my https server to force the SSL protocol to use either TLSv1 or TLSv1.1. I expected these versions to be rejected.

My python program is running on CentOs machine:

```<code>cat /etc/centos-release
CentOS release 6.7 (Final)
</code>```

The default Python version is 2.6.6:

```<code>which python
/usr/bin/python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
</code>```

I installed python 2.7:

```<code>which python2.7
/usr/local/bin/python2.7
Python 2.7.6 (default, Jun  2 2017, 11:37:31)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.1e-fips 11 Feb 2013'

openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013
</code>```

Using pip2.7, I installed the libraries required get requests to run.  I did not make any changes to the openssl.

I sent two test alerts and it seems that my program negotiated down to TLSv1.  I was under the impression that TLSv1 is deprecated.  The program is executing using python 2.7 and not the system default of python 2.6.

At the top of the python program I embedded:
    #!/usr/local/bin/python2.7

Below are the 2 post alerts that shows TLSv1.1 and TLSv1 going through:

```<code>"POST /testpost HTTP/1.1" 200 43 TLSv1.1/ECDHE-RSA-AES256-SHA "-" "python-requests/2.5.1 CPython/2.6.6 Linux/2.6.32-573.22.1.el6.x86_64" 0.006 <"{for: test purposes}"

"POST /testpost HTTP/1.1" 200 43 TLSv1/ECDHE-RSA-AES256-SHA "-" "python-requests/2.5.1 CPython/2.6.6 Linux/2.6.32-573.22.1.el6.x86_64" 0.006 <"{for: test purposes}"
</code>```

Any thoughts?

答:
The documentation of the ssl module has a table which shows which protocol settings work together. Usually if a client and a server both using PROTOCOL_TLS (which is the same as PROTOCOL_SSLv23) connect they use the highest shared protocol version. If there is no compatible version (e.g. the server only speaks 1.1, the client only 1.0) then you'll get an error.

The requests documentation shows how you can force a client to use a specific tls version, e.g. to force TLS 1.2 you could use (slightly modified example):

```<code>import ssl

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager

class Tls12Adapter(HTTPAdapter):
    """"Transport adapter that forces TLSv1.2"""

    def init_poolmanager(self, *pool_args, **pool_kwargs):
        self.poolmanager = PoolManager(
            *pool_args,
            ssl_version=ssl.PROTOCOL_TLSv1_2,
            **pool_kwargs)
</code>```

Recent versions of urllib3 (which requests uses for connections) allow to pass a SSLContext instead, which allows for more flexible configurations, e.g. blocking specific versions while allowing any newer version:

```<code>import ssl
import requests

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests.packages.urllib3.util import ssl_

class TlsAdapter(HTTPAdapter):

    def __init__(self, ssl_options=0, **kwargs):
        self.ssl_options = ssl_options
        super(TlsAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, *pool_args, **pool_kwargs):
        ctx = ssl_.create_urllib3_context(ssl.PROTOCOL_TLS)
        # extend the default context options, which is to disable ssl2, ssl3
        # and ssl compression, see:
        # https://github.com/shazow/urllib3/blob/6a6cfe9/urllib3/util/ssl_.py#L241
        ctx.options |= self.ssl_options
        self.poolmanager = PoolManager(*pool_args,
                                       ssl_context=ctx,
                                       **pool_kwargs)

session = requests.session()
# disallow tls1.0 and tls1.1, allow only tls1.2 (and newer if suported by
# the used openssl version)
adapter = TlsAdapter(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
session.mount("https://", adapter)
</code>```

Body:
I wanted to make sure that when using requests library to post to an HTTP server, it would refuse to communicate using TLSv1 or TLSv1.1.  To do this, I configured my https server to force the SSL protocol to use either TLSv1 or TLSv1.1. I expected these versions to be rejected.

My python program is running on CentOs machine:

cat /etc/centos-release
CentOS release 6.7 (Final)

The default Python version is 2.6.6:

which python
/usr/bin/python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2

I installed python 2.7:

which python2.7
/usr/local/bin/python2.7
Python 2.7.6 (default, Jun  2 2017, 11:37:31)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2
>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.1e-fips 11 Feb 2013'

openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

Using pip2.7, I installed the libraries required get requests to run.  I did not make any changes to the openssl.

I sent two test alerts and it seems that my program negotiated down to TLSv1.  I was under the impression that TLSv1 is deprecated.  The program is executing using python 2.7 and not the system default of python 2.6.

At the top of the python program I embedded:
    #!/usr/local/bin/python2.7

Below are the 2 post alerts that shows TLSv1.1 and TLSv1 going through:

"POST /testpost HTTP/1.1" 200 43 TLSv1.1/ECDHE-RSA-AES256-SHA "-" "python-requests/2.5.1 CPython/2.6.6 Linux/2.6.32-573.22.1.el6.x86_64" 0.006 <"{for: test purposes}"

"POST /testpost HTTP/1.1" 200 43 TLSv1/ECDHE-RSA-AES256-SHA "-" "python-requests/2.5.1 CPython/2.6.6 Linux/2.6.32-573.22.1.el6.x86_64" 0.006 <"{for: test purposes}"

Any thoughts?

Body:
The documentation of the ssl module has a table which shows which protocol settings work together. Usually if a client and a server both using PROTOCOL_TLS (which is the same as PROTOCOL_SSLv23) connect they use the highest shared protocol version. If there is no compatible version (e.g. the server only speaks 1.1, the client only 1.0) then you'll get an error.

The requests documentation shows how you can force a client to use a specific tls version, e.g. to force TLS 1.2 you could use (slightly modified example):

import ssl

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager

class Tls12Adapter(HTTPAdapter):
    """"Transport adapter that forces TLSv1.2"""

    def init_poolmanager(self, *pool_args, **pool_kwargs):
        self.poolmanager = PoolManager(
            *pool_args,
            ssl_version=ssl.PROTOCOL_TLSv1_2,
            **pool_kwargs)

Recent versions of urllib3 (which requests uses for connections) allow to pass a SSLContext instead, which allows for more flexible configurations, e.g. blocking specific versions while allowing any newer version:

import ssl
import requests

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests.packages.urllib3.util import ssl_

class TlsAdapter(HTTPAdapter):

    def __init__(self, ssl_options=0, **kwargs):
        self.ssl_options = ssl_options
        super(TlsAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, *pool_args, **pool_kwargs):
        ctx = ssl_.create_urllib3_context(ssl.PROTOCOL_TLS)
        # extend the default context options, which is to disable ssl2, ssl3
        # and ssl compression, see:
        # https://github.com/shazow/urllib3/blob/6a6cfe9/urllib3/util/ssl_.py#L241
        ctx.options |= self.ssl_options
        self.poolmanager = PoolManager(*pool_args,
                                       ssl_context=ctx,
                                       **pool_kwargs)

session = requests.session()
# disallow tls1.0 and tls1.1, allow only tls1.2 (and newer if suported by
# the used openssl version)
adapter = TlsAdapter(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
session.mount("https://", adapter)


问:
Protractor Javascript not executing in sequence
I have the below function for login, which would console "successful" on success and "Failed" for files ones.

```<code>function login() {

return new Promise(function (resolve, reject) {
    var username = element(by.name('txtLogin'));
    var password = element(by.id('txtPassword'));
    var signInButton = element(by.id('btnSignIn'));

    for (var i = 0; i < testData.length; i++) {
        if (testData[i].env === appConfig) {
            username.sendKeys(testData[i].user);
            password.sendKeys(testData[i].pass);
            signInButton.click();
            console.log("Successfully Clicked on the Sign In Button!");
            break;
        }
    }
    browser.getTitle().then(function (title) {
        if (title == "Page Title") {
            resolve("Successfull");
        } else {
            reject("Failed");
        }
    });
});
};
</code>```

And the following test

```<code>describe('Login Scenarios', function () {

beforeEach(function () {
    login();
});

it('Valid Credentials, Should login successfully from util class', function () {
    console.log('Successfully logged in!');
});
});
</code>```

I am seeing very strange behavior here. This line executes and consoles output even before the page is fully loaded.

```<code>console.log("Successfully Clicked on the Sign In Button!");
</code>```

and the below code never gets executed.

```<code>browser.getTitle().then(function (title) {
        if (title == "Page Title") {
            resolve("Successfull");
        } else {
            reject("Failed");
        }
    });
</code>```

And in the end i see the following error.

```<code>failed: error while waiting for protractor to sync with the page: "cannot re ad property '$$testability' of undefined"
</code>```

I am pretty sure, i have messed up something here. But unable to figure out what's wrong that am doing here.

答:
login returns a promise, but you're not signalling to Jasmine/Protractor that it needs to wait for it to finish. You can do this using the done callback:

```<code>beforeEach(function (done) {
    login().then(function () {
       done();
    });
});
</code>```

See the Jasmine documentation (which seems to have been inexplicibly hidden away in their new website layout...) for more info.

Body:
I have the below function for login, which would console "successful" on success and "Failed" for files ones.

function login() {

return new Promise(function (resolve, reject) {
    var username = element(by.name('txtLogin'));
    var password = element(by.id('txtPassword'));
    var signInButton = element(by.id('btnSignIn'));

    for (var i = 0; i < testData.length; i++) {
        if (testData[i].env === appConfig) {
            username.sendKeys(testData[i].user);
            password.sendKeys(testData[i].pass);
            signInButton.click();
            console.log("Successfully Clicked on the Sign In Button!");
            break;
        }
    }
    browser.getTitle().then(function (title) {
        if (title == "Page Title") {
            resolve("Successfull");
        } else {
            reject("Failed");
        }
    });
});
};

And the following test

describe('Login Scenarios', function () {

beforeEach(function () {
    login();
});

it('Valid Credentials, Should login successfully from util class', function () {
    console.log('Successfully logged in!');
});
});

I am seeing very strange behavior here. This line executes and consoles output even before the page is fully loaded.

console.log("Successfully Clicked on the Sign In Button!");

and the below code never gets executed.

browser.getTitle().then(function (title) {
        if (title == "Page Title") {
            resolve("Successfull");
        } else {
            reject("Failed");
        }
    });

And in the end i see the following error.

failed: error while waiting for protractor to sync with the page: "cannot re ad property '$$testability' of undefined"

I am pretty sure, i have messed up something here. But unable to figure out what's wrong that am doing here.

Body:
login returns a promise, but you're not signalling to Jasmine/Protractor that it needs to wait for it to finish. You can do this using the done callback:

beforeEach(function (done) {
    login().then(function () {
       done();
    });
});

See the Jasmine documentation (which seems to have been inexplicibly hidden away in their new website layout...) for more info.


问:
Is it possible to have overlapping views with auto layout?
I'm trying to have to views overlap as shown in the picture below, but I couldn't figure out how would I go about doing it with auto layout.

I tried doing the bottom view programmatically, and it worked fine except for the button which I had laid out using interface builder.

If it's possible to have views overlap what are the constraints needed, and is there a way to let the button show on top of the view in the bottom without doing programmatically?

答:
In the interface builder, using a constraint, hook the top of the bottom view to the bottom of the top view, and then edit the constant in the Size Inspector to move it like you want.

It should look something like this:


问:
How do I set text-overflow to ellipsis in CSS grid layout?
I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header>
    <div>Left</div>
    <div class="long">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
    <div>Right</div>
  </header>
  <content>
  </content>
</div></code>```

答:
change .long css to below

```<code>.long {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
</code>```

the reason why you need to add white-space and overflow is below:

you need white-space: nowrap to tell browsers to not wrap when text length exceed containing block width, white-space properties default value is normal, which indicates it can wrap, so it won't exist the situation where text overflow;

overflow default value is visible, when text exceeds containing block, it just display, so there is no need to overflow text to display, only if you set overflow to hidden. Then, when text can not fully displayed, it will use text-overflow property.

Body:
I have a grid layout like the one in header below. There is a text in the div whose width is 1fr. I want the text inside that div to be truncated when it is too long. Adding text-overflow as ellpsis is not working. Any idea how to do it?

It has to be grid and there is no way I can change that.

html,
body {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

body {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;
}

content {
  flex: 1;
  background-color: red;
}

header {
  background-color: limegreen;
  display: grid;
  grid-template-columns: 0fr 1fr 0fr;
}

header div {
  border: 1px solid orange;
}

.long {
  text-overflow: ellipsis;
}

Left

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Right

  <content>
  </content>

Body:
change .long css to below

.long {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

the reason why you need to add white-space and overflow is below:

you need white-space: nowrap to tell browsers to not wrap when text length exceed containing block width, white-space properties default value is normal, which indicates it can wrap, so it won't exist the situation where text overflow;

overflow default value is visible, when text exceeds containing block, it just display, so there is no need to overflow text to display, only if you set overflow to hidden. Then, when text can not fully displayed, it will use text-overflow property.


问:
Android: Check if service is running via. bindService
What would be the best way to check if an Android Service is running? I am aware of the ActivityManager API, but it seems like the use of the API is not advised for the scenarios similar to mine (source). I am also aware of the possibility of using global/persistent variables to maintain the state of a service.

I have tried to use bindService with flags set to 0, but I got the same problems as the person on the source link (the only exception was, I was trying the bindService with a local service).

The following call

```<code>getApplicationContext().bindService(new Intent(getApplicationContext(),
        MyService.class), mServiceConnection, 0);
</code>```

always returns true, but does not get connected. Is this the expected behaviour? It seems to me bindService should return false if the service is not already running (it is not, I have checked that) or if the BIND_AUTO_CREATE flag is not set (again, it is not).

答:
I had the same need and found that running .bindService with something else already bound, that it would cause errors. I did this right before running .bindService</p>

```<code>try{
    context.unbindService(fetch_connection);
} catch (IllegalArgumentException e){
    System.out.println("Unbinding didn't work. little surprise");
}
</code>```

Body:
What would be the best way to check if an Android Service is running? I am aware of the ActivityManager API, but it seems like the use of the API is not advised for the scenarios similar to mine (source). I am also aware of the possibility of using global/persistent variables to maintain the state of a service.

I have tried to use bindService with flags set to 0, but I got the same problems as the person on the source link (the only exception was, I was trying the bindService with a local service).

The following call

getApplicationContext().bindService(new Intent(getApplicationContext(),
        MyService.class), mServiceConnection, 0);

always returns true, but does not get connected. Is this the expected behaviour? It seems to me bindService should return false if the service is not already running (it is not, I have checked that) or if the BIND_AUTO_CREATE flag is not set (again, it is not).

Body:
I had the same need and found that running .bindService with something else already bound, that it would cause errors. I did this right before running .bindService

try{
    context.unbindService(fetch_connection);
} catch (IllegalArgumentException e){
    System.out.println("Unbinding didn't work. little surprise");
}


问:
After update to Sonarqube 6.4 java script coverage exclusion does not work
After updating Sonarqube from 6.3 to 6.4 java script coverage exclusion does not work like before. We use JavaScript plugin in version 3.0.0.4962, sona-gradle-plugin 2.4 and we exclude our js-tests with "sonar.coverage.exclusions","**/*-test.js" from the coverage analysis.
After the update the *-test.js" are counted again for the coverage.
Is this a bug or do we have to do something differently? </p>

答:
This is in fact a comment, but I don't have the rating to comment.

I've tried and failed to reproduce your issue (with SonarQube 6.4 and SonarJS 3.0.0.4962). Do you perhaps have quotes around your path? Anyway, here is my working sonar-project.properties :

```<code>sonar.projectKey=test-coverage
sonar.projectName=Test Coverage
sonar.projectVersion=1.0

sonar.sources=.

sonar.javascript.lcov.reportPaths=coverage.lcov

sonar.coverage.exclusions=**/*-test.js
</code>```

Body:
This is in fact a comment, but I don't have the rating to comment.

I've tried and failed to reproduce your issue (with SonarQube 6.4 and SonarJS 3.0.0.4962). Do you perhaps have quotes around your path? Anyway, here is my working sonar-project.properties :

sonar.projectKey=test-coverage
sonar.projectName=Test Coverage
sonar.projectVersion=1.0

sonar.sources=.

sonar.javascript.lcov.reportPaths=coverage.lcov

sonar.coverage.exclusions=**/*-test.js


问:
How to get cURL information
I have a cURL script that makes connection to a page:

```<code><?php
// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);
?>
</code>```

And that page gives an output like:

```<code>{
  "status" : "fail",
  "data" : {
    "error_message" : "Destination address 37428963298746238 is invalid for Network=BTC."
  }
}
</code>```

How do I get "error_message" to $error_message with PHP?

答:
```<code>    // create curl resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_URL, "example.com");

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // $output contains the output string
    $output = curl_exec($ch);

    if(curl_error($ch))
    {
        echo 'error:' . curl_error($ch);
    }

    // close curl resource to free up system resources
    curl_close($ch);
</code>```

Title: How to get cURL information

Body:
I have a cURL script that makes connection to a page:

<?php
// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);
?>

And that page gives an output like:

{
  "status" : "fail",
  "data" : {
    "error_message" : "Destination address 37428963298746238 is invalid for Network=BTC."
  }
}

How do I get "error_message" to $error_message with PHP?


问:
How to enable multiple check an enable unCheck in radio button?
I have enable mutilple check for radio button. But how to enable unCheck

```<code><div id ="box"></div>
<script type="text/babel">

    class Radio extends React.Component{
    constructor(props) {
    super(props);
    this.state = {option: 'a'};
    }
     setRadio(e){
        this.setState({option: e.target.value});
     }
      render(){
         return(<div>
          <div onChange={this.setRadio.bind(this)}  >
          <b>Select :</b> <br />
          <input type="radio" value="a" name="a"/>a
          <input type="radio" value="b" name="b"/>b
          <input type="radio" value="c" name="c"/>c
          <input type="radio" value="d" name="d"/>d
          <input type="radio" value="e" name="e"/>e
      </div>
      </div>);
      }
    }

    ReactDOM.render(<Radio /> , document.getElementById('box'));
</script>
</code>```

I wasn't able to add unCheck option. I just need what should I add to the method setRadio(e) to enable uncheck.
Thanks for help

答:
From what I can understand, you want to check multiple radio buttons, In that case you should make use of checkboxes rather than radio buttons and have an onChange on each checkbox rather than the div

class Checkbox extends React.Component{
constructor(props) {
super(props);
this.state = {option: {
    'a': false,
    'b': false,
    'c': false,
    'd': false,
    'e': false
}};
}
 setCheckbox(val){
   var option = {...this.state.option}
   option[val]= !option[val]
    this.setState({option});
 }
  render(){
     return(

      Select :

      <input type="checkbox" onChange={()=> this.setCheckbox('a')} value="a" name="a" checked={this.state.option['a']}/>a
      <input type="checkbox" onChange={()=> this.setCheckbox('b')} value="b" name="b" checked={this.state.option['b']}/>b
      <input type="checkbox" onChange={()=> this.setCheckbox('c')} value="c" name="c" checked={this.state.option['c']}/>c
      <input type="checkbox" onChange={()=> this.setCheckbox('d')} value="d" name="d" checked={this.state.option['d']}/>d
      <input type="checkbox" onChange={()=> this.setCheckbox('e')} value="e" name="e" checked={this.state.option['e']}/>e

);
  }
}

ReactDOM.render(<Checkbox /> , document.getElementById('box'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id ="box"></div></code>```

Body:
I have enable mutilple check for radio button. But how to enable unCheck

I wasn't able to add unCheck option. I just need what should I add to the method setRadio(e) to enable uncheck.
Thanks for help

Body:
From what I can understand, you want to check multiple radio buttons, In that case you should make use of checkboxes rather than radio buttons and have an onChange on each checkbox rather than the div

class Checkbox extends React.Component{
constructor(props) {
super(props);
this.state = {option: {
    'a': false,
    'b': false,
    'c': false,
    'd': false,
    'e': false
}};
}
 setCheckbox(val){
   var option = {...this.state.option}
   option[val]= !option[val]
    this.setState({option});
 }
  render(){
     return(<div>
      <div  >
      <b>Select :</b> <br />
      <input type="checkbox" onChange={()=> this.setCheckbox('a')} value="a" name="a" checked={this.state.option['a']}/>a
      <input type="checkbox" onChange={()=> this.setCheckbox('b')} value="b" name="b" checked={this.state.option['b']}/>b
      <input type="checkbox" onChange={()=> this.setCheckbox('c')} value="c" name="c" checked={this.state.option['c']}/>c
      <input type="checkbox" onChange={()=> this.setCheckbox('d')} value="d" name="d" checked={this.state.option['d']}/>d
      <input type="checkbox" onChange={()=> this.setCheckbox('e')} value="e" name="e" checked={this.state.option['e']}/>e
  </div>
  </div>);
  }
}

ReactDOM.render(<Checkbox /> , document.getElementById('box'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id ="box"></div>


问:
Unable to make MySQL Trigger to work
I've written a simple trigger, but it raises errors I don't get. Heres my trigger:

```<code>    CREATE TRIGGER logSlette After DELETE on ansatte
for each row
begin
insert into slettede_ansatte set AnsattID=old.AnsattID,slettet=now()
end;
</code>```

The create table statement for the table is:

```<code>    CREATE TABLE slettede_Ansatte
 (
 AnsattID Integer(4) NOT NULL,
 slettet TIME NOT NULL,
 CONSTRAINT Ansatte_PK Primary Key(AnsattID)
 ) ENGINE=INNODB;
</code>```

答:
(revised)

The correct syntax is

```<code>CREATE TRIGGER logSlette AFTER DELETE ON ansatte
  FOR EACH ROW
  BEGIN
    INSERT INTO slettede_ansatte
       SET AnsattID = OLD.AnsattID,
           slettet=now();
  END;
</code>```

Maybe it is the missing semicolon?

Title: Unable to make MySQL Trigger to work

Body:
I've written a simple trigger, but it raises errors I don't get. Heres my trigger:

    CREATE TRIGGER logSlette After DELETE on ansatte
for each row
begin
insert into slettede_ansatte set AnsattID=old.AnsattID,slettet=now()
end;

The create table statement for the table is:

    CREATE TABLE slettede_Ansatte
 (
 AnsattID Integer(4) NOT NULL,
 slettet TIME NOT NULL,
 CONSTRAINT Ansatte_PK Primary Key(AnsattID)
 ) ENGINE=INNODB;

Body:
(revised)

The correct syntax is

CREATE TRIGGER logSlette AFTER DELETE ON ansatte
  FOR EACH ROW
  BEGIN
    INSERT INTO slettede_ansatte
       SET AnsattID = OLD.AnsattID,
           slettet=now();
  END;

Maybe it is the missing semicolon?


问:
How do I Store an Array Variable Inside of Another Array Variable using while loop and for each?
How do I Store an Array Variable Inside of Another Array Variable using while loop and for each?

Like this(array inside array)

答:
please chec Foreach for arrays inside of an array

```<code>foreach($resultArray as $row => $innerArray){
  foreach($innerArray as $innerRow => $value){
    echo $value . "<br/>";
  }
}
</code>```

also check this link : Foreach for arrays inside of an array

Body:
please chec Foreach for arrays inside of an array

foreach($resultArray as $row => $innerArray){
  foreach($innerArray as $innerRow => $value){
    echo $value . "<br/>";
  }
}

also check this link : Foreach for arrays inside of an array


问:
How to upload file in Angular2
I have to submit a form along with image. i have tried this code (with multiple ways) but did't work for me. is there anyone having working demo of file uploading using angular2 please help me out.

component.html

```<code>    <form class="form-horizontal" role="form" >

        <div class="form-group">
            <label class="control-label col-sm-4" for="myname" style="">Name<span class="asterisk">*</span></label>
            <div class="col-sm-7">
                <div>
                    <input type="text" class="form-control" id="myname"
                    [(ngModel)]="myfile.name">
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-sm-4" for="myimage">Image</label>
            <div class="col-sm-7">
                <div>
                    <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
                </div>
            </div>
        </div>

        <div class="form-group">
        <div class="text-center">
            <button type="button" (click)="upload()">Upload</button>
        </div>
        </div>
  </form>
</code>```

component.ts

```<code>     myfile={
                "name":"Mubashshir",
                "image":''
     }

     fileChangeEvent(fileInput: any){
        this.myfile.image = fileInput.target.files;
     }

     upload(){
          this.base_path_service.PostRequest('http://128.199.190.109/api/school/schoolDetail/',this.myfile)
            .subscribe(
                data => {
                            console.log("data submitted");
                        },
                err => console.log(err),
                () =>{
                     console.log('Authentication Complete');

                }
            );
      }
</code>```

答:
Here is the Angular 2 version

We needed to implement drag drop file input feature in one of our Angular 2 app.

We selected ng-file-upload for this.

We tried to follow the help page. As suggested, implemented drag-upload-input.html & drag-upload-input.component.ts like the following:

drag-upload-input.html

```<code><!-- we only need single file upload -->
<input type="file" ng2FileSelect [uploader]="uploader" />
</code>```

drag-upload-input.component.ts

```<code>import { Component } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';

// const URL = '/api/';
const URL = 'https://evening-anchorage-3159.herokuapp.com/api/';

@Component({
  moduleId: module.id,
  selector: 'drag-upload-input',
  templateUrl: './drag-upload-input.html'
})
export class DragUploadInput {
  public uploader: FileUploader = new FileUploader({ url: URL });
  public hasBaseDropZoneOver: boolean = false;
  public hasAnotherDropZoneOver: boolean = false;

  public fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }

  public fileOverAnother(e: any): void {
    this.hasAnotherDropZoneOver = e;
  }
}
</code>```

The app.module.ts has got FileUploadModule like this:

```<code>// File upload modules
import { FileUploadModule } from 'ng2-file-upload';
import { DragUploadInput } from './file-upload/drag-upload-input.component';

//other imports

@NgModule({
  imports: [ ... other imports
FileUploadModule
],
  declarations: [  ... other declarations
DragUploadInput],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

And the systemjs.config.js looks like this:

```<code>(function (global) {
  System.config({
    // map tells the System loader where to look for things
    map: {
      // other libraries
      'ng2-file-upload': 'node_modules/ng2-file-upload',
    },
    packages: {
      // other packages
      ng2-file-upload': {
        main: 'ng2-file-upload.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

source

Title: How to upload file in Angular2

Body:
I have to submit a form along with image. i have tried this code (with multiple ways) but did't work for me. is there anyone having working demo of file uploading using angular2 please help me out.

component.html

    <form class="form-horizontal" role="form" >

            Name*

                    <input type="text" class="form-control" id="myname"
                    [(ngModel)]="myfile.name">

            Image

                    <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />

            <button type="button" (click)="upload()">Upload</button>

  </form>

component.ts

     myfile={
                "name":"Mubashshir",
                "image":''
     }

     fileChangeEvent(fileInput: any){
        this.myfile.image = fileInput.target.files;
     }

     upload(){
          this.base_path_service.PostRequest('http://128.199.190.109/api/school/schoolDetail/',this.myfile)
            .subscribe(
                data => {
                            console.log("data submitted");
                        },
                err => console.log(err),
                () =>{
                     console.log('Authentication Complete');

                }
            );
      }

Body:
Here is the Angular 2 version

We needed to implement drag drop file input feature in one of our Angular 2 app.

We selected ng-file-upload for this.

We tried to follow the help page. As suggested, implemented drag-upload-input.html & drag-upload-input.component.ts like the following:

drag-upload-input.html

<!-- we only need single file upload -->
<input type="file" ng2FileSelect [uploader]="uploader" />

drag-upload-input.component.ts

import { Component } from '@angular/core';
import { FileUploader } from 'ng2-file-upload';

// const URL = '/api/';
const URL = 'https://evening-anchorage-3159.herokuapp.com/api/';

@Component({
  moduleId: module.id,
  selector: 'drag-upload-input',
  templateUrl: './drag-upload-input.html'
})
export class DragUploadInput {
  public uploader: FileUploader = new FileUploader({ url: URL });
  public hasBaseDropZoneOver: boolean = false;
  public hasAnotherDropZoneOver: boolean = false;

  public fileOverBase(e: any): void {
    this.hasBaseDropZoneOver = e;
  }

  public fileOverAnother(e: any): void {
    this.hasAnotherDropZoneOver = e;
  }
}

The app.module.ts has got FileUploadModule like this:

// File upload modules
import { FileUploadModule } from 'ng2-file-upload';
import { DragUploadInput } from './file-upload/drag-upload-input.component';

//other imports

@NgModule({
  imports: [ ... other imports
FileUploadModule
],
  declarations: [  ... other declarations
DragUploadInput],
  bootstrap: [AppComponent]
})
export class AppModule { }

And the systemjs.config.js looks like this:

(function (global) {
  System.config({
    // map tells the System loader where to look for things
    map: {
      // other libraries
      'ng2-file-upload': 'node_modules/ng2-file-upload',
    },
    packages: {
      // other packages
      ng2-file-upload': {
        main: 'ng2-file-upload.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

source


问:
Accessing root html tag from an Angular 2 component
So the question is, is it possible to use the Renderer to tweak tags that are outside the main Angular 2 app component, like the  tag? If yes, what is the best way to do this?

Let me give a bit of background. I'm trying to build a multilanguage site with Angular 2 and I came across a problem I could not find solution for. The thing is I am using the lang attribute in the html tag to define what language the site has at each moment, for example:

```<code><html lang="en"> // When we have English locale active
</code>```

So when the user clicks on a different language I update the site language using ng2-translate, which works perfect. The problem is that I need to update the  property accordingly but I can't find the correct way of doing this in Angular 2 (if it's even possible).
For now, I am directly touching the DOM but this won't work for me because I need to be abstracted from it (I'm using Universal too, so I need server side rendering to work).

For now, the styling of the app relays on this property (we support Arabic and this means changing the direction of the text if lang="ar"). I guess I could use a class on my main component or something like that, but using the lang property seems the correct approach to me. Any ideas?

Thanks

答:
You can use the DOCUMENT DI Token from Angular to perform Dom operations:</p>

```<code>import { Inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DOCUMENT } from '@angular/common';

export class AppComponent {

    constructor(private translate: TranslateService, @Inject(DOCUMENT) private _document: any) {
        translate.onLangChange.map(x => x.lang)
            .subscribe(lang => this._document.documentElement.lang = lang);
    }
}
</code>```

Body:
So the question is, is it possible to use the Renderer to tweak tags that are outside the main Angular 2 app component, like the  tag? If yes, what is the best way to do this?

Let me give a bit of background. I'm trying to build a multilanguage site with Angular 2 and I came across a problem I could not find solution for. The thing is I am using the lang attribute in the html tag to define what language the site has at each moment, for example:

 // When we have English locale active

So when the user clicks on a different language I update the site language using ng2-translate, which works perfect. The problem is that I need to update the  property accordingly but I can't find the correct way of doing this in Angular 2 (if it's even possible).
For now, I am directly touching the DOM but this won't work for me because I need to be abstracted from it (I'm using Universal too, so I need server side rendering to work).

For now, the styling of the app relays on this property (we support Arabic and this means changing the direction of the text if lang="ar"). I guess I could use a class on my main component or something like that, but using the lang property seems the correct approach to me. Any ideas?

Thanks

Body:
You can use the DOCUMENT DI Token from Angular to perform Dom operations:

import { Inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DOCUMENT } from '@angular/common';

export class AppComponent {

    constructor(private translate: TranslateService, @Inject(DOCUMENT) private _document: any) {
        translate.onLangChange.map(x => x.lang)
            .subscribe(lang => this._document.documentElement.lang = lang);
    }
}


问:
On logout invalidate flask-JWT
I have generated Flask-JWT token for user authentication, but on logout i want to invalidate token. Now it's allowing to access route after logout.</p>

```<code>@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
    user = current_user
    user.authenticated = False
    db.session.commit()
    logout_user()
    return jsonify({'success': True})
</code>```

答:
JWT token system works in a way that you put USER identity (or related) data and token expiry param in generated token itself which is signed with a non-shared (secret) key.If you want to invalidate the token you need to blacklist the token in a table & check on views/routes or delete the token from client so that client needs to regenerate the token again.

NOTE: putting any constraints in the payloads itself is not a good idea, if you don't want the blacklisting method, use other token generating schemes like Hawk where the generated token is saved in DB/other storage solutions & on invalidate/logout it is deleted.

if you want to log out a user from all devices

   1. keep a user-specific secret key in DB and use the secret key to create JWT token

   2. Assign a new secret key for the user, which will in effect invalidate all JWT tokens send to user/clients.

   3. This can be useful when the user changed his/her password

Title: On logout invalidate flask-JWT

Body:
I have generated Flask-JWT token for user authentication, but on logout i want to invalidate token. Now it's allowing to access route after logout.

@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
    user = current_user
    user.authenticated = False
    db.session.commit()
    logout_user()
    return jsonify({'success': True})


问:
self controller 0 key/value pairs
I have a working controller, however when I debug it and try to see the values of the variables, self is empty like this. I tryed to clean project,
restarted XCODE but nothing worked, any idea?

答:
initialize you variable in viewDidLoad.

for ex.
if you have declared NSMutableArray in properties and haven't intialized them in viewDidLoad.
like this i.e.NSMutableArray a=[NSMutableArray alloc]init];

It may cause this problem.

Title: self controller 0 key/value pairs


问:
Regex IF condition
I'm looking for a way to filter new IP-Addresses in my host file.
I created a script which updates my host file every time when I call it with data from the matrix enterprise manager. It works fine. But I have to find a solution that only 10.XX.XX.XX or 172.XX.XX.XX addresses are allowed to update.</p>

```<code>Param(
  $newHost = $args[0],
  $newIP = $args[1]
)

$SourceFile = "hosts"
$Match = "$newHost"

(Get-Content $SourceFile) | % {if ($_ -notmatch $Match) {$_}} | Set-Content $SourceFile

Start-Sleep -Seconds 1

$tab = [char]9
$enter = $newIP + $tab + $newHost

if ($newIP XXXX)  #--> here should be a regex if condition... no clue how it works..

$enter | Add-Content -Path hosts
</code>```

答:
Your code is unnecessarily convoluted and doesn't make proper use of the features PowerShell provides.

Don't assign $args[...] to parameters. That's not how parameter handling in PowerShell works. Make the parameters mandatory instead.

% {if ($_ -notmatch $Match) {$_}} is better phrased as Where-Object {$_ -notmatch $Match}.

If $Match is an FQDN the dots might cause false positives (because they match any character, not just literal dots). Either escape $Match ([regex]::Escape($Match)) or use the -notlike operator instead.

PowerShell has an escape sequence for tabs (`t). No need to define a variable with a value of [char]9.

Putting variables in a double-quoted string ("$var1$var2") is often more readable than string concatenation ($var1 + $var2).

Change your code to something like this:

```<code>[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true)]
  [string]$Hostname,
  [Parameter(Mandatory=$true)]
  [string]$IPAddress
)

$SourceFile = 'hosts'

(Get-Content $SourceFile) |
  Where-Object { $_ -notlike "*$Hostname*" } |
  Set-Content $SourceFile

Start-Sleep -Seconds 1

if ($IPAddress -match '^(10|172)\.') {
  "$IPAddress`t$Hostname" | Add-Content $SourceFile
}
</code>```

If you want to avoid writing the output file multiple times, you could collect the data read in a variable, and then write that variable and the new record in one go:

```<code>$hosts = @(Get-Content $SourceFile) | Where-Object { $_ -notlike "*$Hostname*" })

if ($IPAddress -match '^(10|172)\.') {
  $hosts += "$IPAddress`t$Hostname"
}

$hosts | Set-Content $SourceFile
</code>```

You could further optimize your script by doing the check via parameter validation, so you don't need an if condition in the function body in the first place, e.g. like this:

```<code>Param(
  [Parameter(Mandatory=$true)]
  [string]$Hostname,
  [Parameter(Mandatory=$true)]
  [ValidatePattern('^(10|172)\.')]
  [string]$IPAddress
)
</code>```

or like this:

```<code>Param(
  [Parameter(Mandatory=$true)]
  [string]$Hostname,
  [Parameter(Mandatory=$true)]
  [ValidateScript({$_ -match '^(10|172)\.' -and [bool][ipaddress]$_})]
  [string]$IPAddress
)
</code>```

Title: Regex IF condition

Body:
I'm looking for a way to filter new IP-Addresses in my host file.
I created a script which updates my host file every time when I call it with data from the matrix enterprise manager. It works fine. But I have to find a solution that only 10.XX.XX.XX or 172.XX.XX.XX addresses are allowed to update.

Param(
  $newHost = $args[0],
  $newIP = $args[1]
)

$SourceFile = "hosts"
$Match = "$newHost"

(Get-Content $SourceFile) | % {if ($_ -notmatch $Match) {$_}} | Set-Content $SourceFile

Start-Sleep -Seconds 1

$tab = [char]9
$enter = $newIP + $tab + $newHost

if ($newIP XXXX)  #--> here should be a regex if condition... no clue how it works..

$enter | Add-Content -Path hosts

Body:
Your code is unnecessarily convoluted and doesn't make proper use of the features PowerShell provides.

Don't assign $args[...] to parameters. That's not how parameter handling in PowerShell works. Make the parameters mandatory instead.

% {if ($_ -notmatch $Match) {$_}} is better phrased as Where-Object {$_ -notmatch $Match}.

If $Match is an FQDN the dots might cause false positives (because they match any character, not just literal dots). Either escape $Match ([regex]::Escape($Match)) or use the -notlike operator instead.

PowerShell has an escape sequence for tabs (`t). No need to define a variable with a value of [char]9.

Putting variables in a double-quoted string ("$var1$var2") is often more readable than string concatenation ($var1 + $var2).

Change your code to something like this:

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true)]
  [string]$Hostname,
  [Parameter(Mandatory=$true)]
  [string]$IPAddress
)

$SourceFile = 'hosts'

(Get-Content $SourceFile) |
  Where-Object { $_ -notlike "*$Hostname*" } |
  Set-Content $SourceFile

Start-Sleep -Seconds 1

if ($IPAddress -match '^(10|172)\.') {
  "$IPAddress`t$Hostname" | Add-Content $SourceFile
}

If you want to avoid writing the output file multiple times, you could collect the data read in a variable, and then write that variable and the new record in one go:

$hosts = @(Get-Content $SourceFile) | Where-Object { $_ -notlike "*$Hostname*" })

if ($IPAddress -match '^(10|172)\.') {
  $hosts += "$IPAddress`t$Hostname"
}

$hosts | Set-Content $SourceFile

You could further optimize your script by doing the check via parameter validation, so you don't need an if condition in the function body in the first place, e.g. like this:

Param(
  [Parameter(Mandatory=$true)]
  [string]$Hostname,
  [Parameter(Mandatory=$true)]
  [ValidatePattern('^(10|172)\.')]
  [string]$IPAddress
)

or like this:

Param(
  [Parameter(Mandatory=$true)]
  [string]$Hostname,
  [Parameter(Mandatory=$true)]
  [ValidateScript({$_ -match '^(10|172)\.' -and [bool][ipaddress]$_})]
  [string]$IPAddress
)


问:
DisplayMembers in ListBox - Not displaying anything
In Form1, why isn't myListBox displaying my name property inside of class Student

Form1

```<code>private static List<Student> studentListHome = new List<Student>();

...

public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                studentListBox.DisplayMember = "name";
            }
        }

    private void refreshButton_Click(object sender, EventArgs e)
            {
                BindData();
            }
</code>```

Student

```<code>    private string name;

    public string Name
            {
                get
                {
                    return name;
                }
            }
...

public Student(string _name, int _id, string _bday)
        {
            name = _name;
            id = _id;
            bday = _bday;
        }
</code>```

答:
This fixed it

Changing

```<code>studentListBox.DisplayMember = "Name";
</code>```

To

```<code>foreach(Student s in studentListHome){
    studentListBox.DisplayMember = "Name";
}
</code>```

Body:
In Form1, why isn't myListBox displaying my name property inside of class Student

Form1

private static List<Student> studentListHome = new List<Student>();

...

public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                studentListBox.DisplayMember = "name";
            }
        }

    private void refreshButton_Click(object sender, EventArgs e)
            {
                BindData();
            }

Student

    private string name;

    public string Name
            {
                get
                {
                    return name;
                }
            }
...

public Student(string _name, int _id, string _bday)
        {
            name = _name;
            id = _id;
            bday = _bday;
        }

Body:
This fixed it

Changing

studentListBox.DisplayMember = "Name";

To

foreach(Student s in studentListHome){
    studentListBox.DisplayMember = "Name";
}


问:
How to minimize the costs for allocating and initializing an NSDateFormatter?
I noticed that using an NSDateFormatter can be quite costly. I figured out that allocating and initializing the object already consumes a lot of time.

Further, it seems that using an NSDateFormatter in multiple threads increases the costs. Can there be a blocking where the threads have to wait for each other?

I created a small test application to illustrate the problem. Please check it out.

http://github.com/johnjohndoe/TestNSDateFormatter

git://github.com/johnjohndoe/TestNSDateFormatter.git

What is the reason for such costs and how can I improve the usage?

17.12. - To update my observation: I do not understand why the threads run longer when processed parallel compared to when the run in serial order. The time difference only occurs when NSDateFormatter is used.

答:
Using -initWithDateFormat:allowNaturalLanguage: instead of -init followed by -setDateFormat: should be much faster (probably ~2x).

In general though, what bbum said: cache your date formatters for hot code.

(Edit: this is no longer true in iOS 6/OSX 10.8, they should all be equally fast now)


问:
Formatting Date and Time with a function in C#
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.

This is my function code:

```<code>private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}
</code>```

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?

答:
You only needed to make sure your format matched your input, which none of your provided input formats did.

See how the custom dateformat specifiers and literal characters line-up with your input.

```<code>         Your input: 20161216000000.000000-000
  format specifiers: yyyyMMddhhmmss.ffffff-000
</code>```

Bringing that format to your method you'll get this:

```<code>// takes an object, returns a DateTime or null in case of failure
DateTime FormatDateTime(object ObjInstallDate)
{
    DateTime dtm;
    if (!DateTime.TryParseExact(
        (string) ObjInstallDate, // notice that we don't hassle with the input here,
                                 // only cast to a string
                                 // we simply rely on the parser of DateTimer.TryParseExact
        "yyyyMMddhhmmss.ffffff-000",  // this matches the format
                                      // if the -000 represents a timezone
                                      // you can use z00 or zz0
                                      // don't use zzz as that expects -0:00
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None,
        out dtm))
    {
        // an invalid date was supplied, maybe throw, at least log
        Console.WriteLine("{0} is not valid", ObjInstallDate);
    }
    // we either return here null or a valid date
    return dtm; // !! No ToString() here
}
</code>```

I cherry picked the needed custom format value from Custom Date and Time Format Strings.

Notice that I simply return the DateTime instance that was created. You'll see next why I do that.

As you want to display the DateTime on a  Winform (I assume in a textbox, but an label will work as well) you can now simply Databind the DateTime instance to the textbox and let the databinding plumbing do the formatting. Here is a code example that can be run in LinqPad:

```<code>// take a string and make a date of it
var str = "20161216000000.000000-000";
DateTime dtm = FormatDateTime(str);

// show it on a Databind TextBox
var f = new Form();
var txt = new TextBox();
txt.Width = 200;
// bind the Text property
txt.DataBindings.Add(
    "Text",  // property on the textbox
    dtm, // our DateTime object
    null, // use the DateTime instance, not a property
    true, // use formatting
    DataSourceUpdateMode.OnValidation,
    null, // value to indicate null
    "yyyy-MM-dd"); // our format
f.Controls.Add(txt);
f.Show();
</code>```

I'm using the overload of Add on the DataBindingsCollection that takes an Format string. I can then use the same custom format specifier options to represent that DateTime instance however I want. From here it would be easy to add another TextBox which uses the same DateTime instance but shows the month in text for example.

When all of this comes together this will be your result:

Body:
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.

This is my function code:

private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?

Body:
You only needed to make sure your format matched your input, which none of your provided input formats did.

See how the custom dateformat specifiers and literal characters line-up with your input.

         Your input: 20161216000000.000000-000
  format specifiers: yyyyMMddhhmmss.ffffff-000

Bringing that format to your method you'll get this:

// takes an object, returns a DateTime or null in case of failure
DateTime FormatDateTime(object ObjInstallDate)
{
    DateTime dtm;
    if (!DateTime.TryParseExact(
        (string) ObjInstallDate, // notice that we don't hassle with the input here,
                                 // only cast to a string
                                 // we simply rely on the parser of DateTimer.TryParseExact
        "yyyyMMddhhmmss.ffffff-000",  // this matches the format
                                      // if the -000 represents a timezone
                                      // you can use z00 or zz0
                                      // don't use zzz as that expects -0:00
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None,
        out dtm))
    {
        // an invalid date was supplied, maybe throw, at least log
        Console.WriteLine("{0} is not valid", ObjInstallDate);
    }
    // we either return here null or a valid date
    return dtm; // !! No ToString() here
}

I cherry picked the needed custom format value from Custom Date and Time Format Strings.

Notice that I simply return the DateTime instance that was created. You'll see next why I do that.

As you want to display the DateTime on a  Winform (I assume in a textbox, but an label will work as well) you can now simply Databind the DateTime instance to the textbox and let the databinding plumbing do the formatting. Here is a code example that can be run in LinqPad:

// take a string and make a date of it
var str = "20161216000000.000000-000";
DateTime dtm = FormatDateTime(str);

// show it on a Databind TextBox
var f = new Form();
var txt = new TextBox();
txt.Width = 200;
// bind the Text property
txt.DataBindings.Add(
    "Text",  // property on the textbox
    dtm, // our DateTime object
    null, // use the DateTime instance, not a property
    true, // use formatting
    DataSourceUpdateMode.OnValidation,
    null, // value to indicate null
    "yyyy-MM-dd"); // our format
f.Controls.Add(txt);
f.Show();

I'm using the overload of Add on the DataBindingsCollection that takes an Format string. I can then use the same custom format specifier options to represent that DateTime instance however I want. From here it would be easy to add another TextBox which uses the same DateTime instance but shows the month in text for example.

When all of this comes together this will be your result: