问:
CSS-Only Scrollable Table with fixed headers
I have a solution by which I can create scrollable tables w/fixed header/footer using minor jQuery and CSS - but I am looking for a way to make this a CSS-only solution that is cross-browser compliant.

To be clear, what I am seeking to do is use only a table tag (and it's valid sub-tags, colgroup, col, thead, tbody, tfoot, tr, th, td), but adopt a set of CSS rules which will meet the following conditions:

Must maintain column alignment between header / footer / content rows

Must allow the header/footer to remain fixed while the content scrolls vertically

Must not require any jQuery or other JavaScript in order to provide the functionality

Must only use the tags provided above

This code example: http://jsfiddle.net/TroyAlford/SNKfd/ shows my current approach. Most of the JS is just to populate the table with random values, but the last portion is what drives the left/right scrollability.

```<code>$tbody.bind('scroll', function(ev) {
    var $css = { 'left': -ev.target.scrollLeft };
    $thead.css($css);
    $tfoot.css($css);
});
</code>```

NOTE: The example provided does not render properly in IE, and requires jQuery to provide the horizontal scrolling. I don't care about horizontal scrolling anyway, so it's fine if a solution doesn't do that.

答:
Only with CSS :

CSS:

```<code>tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}
</code>```

Bootply : http://www.bootply.com/AgI8LpDugl

Body:
I have a solution by which I can create scrollable tables w/fixed header/footer using minor jQuery and CSS - but I am looking for a way to make this a CSS-only solution that is cross-browser compliant.

To be clear, what I am seeking to do is use only a table tag (and it's valid sub-tags, colgroup, col, thead, tbody, tfoot, tr, th, td), but adopt a set of CSS rules which will meet the following conditions:

Must maintain column alignment between header / footer / content rows

Must allow the header/footer to remain fixed while the content scrolls vertically

Must not require any jQuery or other JavaScript in order to provide the functionality

Must only use the tags provided above

This code example: http://jsfiddle.net/TroyAlford/SNKfd/ shows my current approach. Most of the JS is just to populate the table with random values, but the last portion is what drives the left/right scrollability.

$tbody.bind('scroll', function(ev) {
    var $css = { 'left': -ev.target.scrollLeft };
    $thead.css($css);
    $tfoot.css($css);
});

NOTE: The example provided does not render properly in IE, and requires jQuery to provide the horizontal scrolling. I don't care about horizontal scrolling anyway, so it's fine if a solution doesn't do that.

Body:
Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl


来源: stackexchange

问:
Android keyboard "Go" button to "Search"
can any one tell how to get "Search" in place of "Go" or "Done" button in android keyboard. (not magnifying glass ) . </p>

答:
Add below two line in your EditText tag :

```<code> android:inputType="text"
 android:imeOptions="actionSearch"
</code>```

And Add the setOnEditorActionListener() method to editText as below:

```<code>  etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                     doSearch(); //Do whatever you intend to do when user click on search button in keyboard.
                   }

                    return true;
                }
                return false;
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Add below two line in your EditText tag :

 android:inputType="text"
 android:imeOptions="actionSearch"

And Add the setOnEditorActionListener() method to editText as below:

  etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                     doSearch(); //Do whatever you intend to do when user click on search button in keyboard.
                   }

                    return true;
                }
                return false;
            }
        });


问:
C# PDF Printing Library
Are there any free libraries that would "print" to a PDF without actually having to install a PDF printer on the system.  I want something that can be completely self contained in my application.  The reason I say I want it to "print" is that I've tried and tried to find a solution for directly converting from HTML with CSS to PDF, but it does't seem very possible.  So I want to use the System.Windows.Forms.WebBrowser control to render the page first and then output that rendering to PDF.  I just don't want the user to be required to install a PDFPrinter.</p>

答: http://itextsharp.sourceforge.net/ is really excellent. You can see how to use it in the repository at stochfit.sourceforge.net</p>

OwnerDisplayName: Adam Haile

ContentLicense: CC BY-SA 2.5

Title: C# PDF Printing Library

OwnerDisplayName: Steve


问:
I just started using methods. This is a template and I'm confused on how to do the methods. Can someone show me how to do what is being asked?
I'm not sure how to add the methods that is wanted as this is my first program not doing everything in a main. It's super confusing to me. I have no idea how to make a method and only vaguely what it entails or how to return. Could anyone help me out with this code?

Edit::
I did the code thanks to the provided tips. However, I can't seem to get the last two methods to work. I feel as though shift char is to be used withing String shift but i dont know how. What i have here compiles and runs but the last output is "String shifted by one letter is 'Nztizhzqtz'" when i input My Shy Gypsy which correctly shifts every letter forward 1 letter in the alphabet but takes the spaces away, why?

```<code>import java.util.Scanner;

public class StringMethods {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = input.nextLine();

        System.out.println("\nNumber of Spaces in the string = " + countSpaces(s) + "\n");
        System.out.println("Number of E's in the string = " + countChar(s, "E") + "\n");
        System.out.println("Number of Stars in the string = " + countChar(s, "*") + "\n");
        System.out.println("Does string contain vowels? " + anyVowels(s) + "\n");
        System.out.println("String reversed = " + reverse(s) + "\n");
        System.out.println("String shifted by one letter is " + shift(s)  + "\n");
    }

    // method to return the number of spaces in a String
    public static int countSpaces(String input) {
        int spaces = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == ' '){
                spaces++;
            }
        }
         return spaces;
    }

    // method to count the number of instances of
    // a particular character in a String
    // the method will return the total of upper and lower
    // case instances if it is a letter
    public static int countChar(String input,String findStr) {
        input = input.toLowerCase();
        findStr = findStr.toLowerCase();
        int num = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == findStr.charAt(0)){
                num++;
            }
        }
        return num;

    }

    // method to detect whether a String contains a vowel or not
    // must include call(s) to countChar
    // returns true or false
    public static boolean anyVowels(String input) {
        int num = 0;
        num = countChar(input, "a")+countChar(input, "e")+countChar(input, "i")+countChar(input, "o")+countChar(input, "u");
        if(num >  0) {
            return true;
        }
        return false;
    }

    // method to return the reverse of a String
    public static String reverse(String input) {
        String reverse = "";
        for (int i = 0;i<input.length();i++) {
            reverse = input.charAt(i) + reverse;
        }
        return reverse;
    }

    // method to return a character shifted one place in the alphaber
    // a becomes b, b become c etc. z becomes a
    // A becomes B, B becomes C etc. Z becomes A
    // all other characters are left unchanged
    public static char shift(char input) {

        char shiftedChar = 'a';
        shiftedChar++;
        //for (int i = 0; i < input.length();i++) {
        //    shiftedChar = input.charAt(i);
        //
        //}

        return shiftedChar;
    }

    // method to return a String with each letter shifted one place in the alphabet
    // method must include call(s) to previous method
    public static String shift(String input) {

        String shiftedString = "";
        for (int i = 0; i < input.length();i++) {
            char a = input.charAt(i);
            if (a != ' ') {
            a++;
            shiftedString = shiftedString + a;
            }
        }

        return shiftedString;
    }

}
</code>```

答:
I see the teacher has left you the skeleton of the methods so I will help you out with the first one.

```<code>public static ________ countSpaces(________) {

    }
</code>```

Here the first underlined part is what you want the method to return (i.e. do you want it to return text (String) or an integer (int)). Look up datatypes for Java. Hint: what it should return is in the comments above the method.

The second underlined part (in brackets) is what you wish to pass to the method when you want to use it. So if the method needs the number 10 in it to do some sort of calculation, and return some sort of text, one example would be:

```<code>public static String countSpaces(int 10) {
       //do whatever necessary here

    }
</code>```

Hope this helps.

Body:
I'm not sure how to add the methods that is wanted as this is my first program not doing everything in a main. It's super confusing to me. I have no idea how to make a method and only vaguely what it entails or how to return. Could anyone help me out with this code?

Edit::
I did the code thanks to the provided tips. However, I can't seem to get the last two methods to work. I feel as though shift char is to be used withing String shift but i dont know how. What i have here compiles and runs but the last output is "String shifted by one letter is 'Nztizhzqtz'" when i input My Shy Gypsy which correctly shifts every letter forward 1 letter in the alphabet but takes the spaces away, why?

import java.util.Scanner;

public class StringMethods {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String s = input.nextLine();

        System.out.println("\nNumber of Spaces in the string = " + countSpaces(s) + "\n");
        System.out.println("Number of E's in the string = " + countChar(s, "E") + "\n");
        System.out.println("Number of Stars in the string = " + countChar(s, "*") + "\n");
        System.out.println("Does string contain vowels? " + anyVowels(s) + "\n");
        System.out.println("String reversed = " + reverse(s) + "\n");
        System.out.println("String shifted by one letter is " + shift(s)  + "\n");
    }

    // method to return the number of spaces in a String
    public static int countSpaces(String input) {
        int spaces = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == ' '){
                spaces++;
            }
        }
         return spaces;
    }

    // method to count the number of instances of
    // a particular character in a String
    // the method will return the total of upper and lower
    // case instances if it is a letter
    public static int countChar(String input,String findStr) {
        input = input.toLowerCase();
        findStr = findStr.toLowerCase();
        int num = 0;
        int i;
        for (i = 0;i<input.length();i++){
            if(input.charAt(i) == findStr.charAt(0)){
                num++;
            }
        }
        return num;

    }

    // method to detect whether a String contains a vowel or not
    // must include call(s) to countChar
    // returns true or false
    public static boolean anyVowels(String input) {
        int num = 0;
        num = countChar(input, "a")+countChar(input, "e")+countChar(input, "i")+countChar(input, "o")+countChar(input, "u");
        if(num >  0) {
            return true;
        }
        return false;
    }

    // method to return the reverse of a String
    public static String reverse(String input) {
        String reverse = "";
        for (int i = 0;i<input.length();i++) {
            reverse = input.charAt(i) + reverse;
        }
        return reverse;
    }

    // method to return a character shifted one place in the alphaber
    // a becomes b, b become c etc. z becomes a
    // A becomes B, B becomes C etc. Z becomes A
    // all other characters are left unchanged
    public static char shift(char input) {

        char shiftedChar = 'a';
        shiftedChar++;
        //for (int i = 0; i < input.length();i++) {
        //    shiftedChar = input.charAt(i);
        //
        //}

        return shiftedChar;
    }

    // method to return a String with each letter shifted one place in the alphabet
    // method must include call(s) to previous method
    public static String shift(String input) {

        String shiftedString = "";
        for (int i = 0; i < input.length();i++) {
            char a = input.charAt(i);
            if (a != ' ') {
            a++;
            shiftedString = shiftedString + a;
            }
        }

        return shiftedString;
    }

}

Body:
I see the teacher has left you the skeleton of the methods so I will help you out with the first one.

public static ________ countSpaces(________) {

    }

Here the first underlined part is what you want the method to return (i.e. do you want it to return text (String) or an integer (int)). Look up datatypes for Java. Hint: what it should return is in the comments above the method.

The second underlined part (in brackets) is what you wish to pass to the method when you want to use it. So if the method needs the number 10 in it to do some sort of calculation, and return some sort of text, one example would be:

public static String countSpaces(int 10) {
       //do whatever necessary here

    }

Hope this helps.


问:
JS - for loop inside for loop
I'm writing a function to count number, first loop get all the values from table row, the console return:

```<code>apple is 0
banana is 1
orange is 2
watermelon is 3
</code>```

If there's a number (ex:2) passing to the function, inside for loop will rearrange the number, I wish console return:

```<code>apple is 0
banana is 1
watermelon is 2
</code>```

But console actually return:

```<code>apple is 0
apple is 1
apple is 2
apple is 3
apple is 4
banana is 0
banana is 1
banana is 2
banana is 3
banana is 4
watermelon is 0
watermelon is 1
watermelon is 2
watermelon is 3
watermelon is 4
</code>```

Don't know how to fix it, here's my code

HTML part:

```<code><tr>
<td id="row_00">apple</td>
<td><a href="javascript:del_list(0);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_01">banana</td>
<td><a href="javascript:del_list(1);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_02">orange</td>
<td><a href="javascript:del_list(2);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_03">watermelon</td>
<td><a href="javascript:del_list(3);"><img src="delete.gif"></a></td>
</tr>
<tr>
<td id="row_04"></td>
<td><a href="javascript:del_list(4);"><img src="delete.gif"></a></td>
</tr>
</code>```

JS part:

```<code>function del_list(number){
    //passing the number between 0 to 4
    for (i = 0; i < 5; i++) {
        var list = $("#id" + i).val(); //table row from HTML
        console.log(list + " is " +i)

        if(i != number && list != ""){
            for (s = 0; s < 5; s++) {
                console.log(list + " is " +s)
            }
        }
    }
}
</code>```

答:
You don't need a second for loop, use one loop and skip the {number} element:</p>

```<code>function del_list(number){
    //passing the number between 0 to 4
    for (var i = 0, index = 0; i < 5; i++) {
        if (i != number) {
            var list = $("#id" + i).val(); //table row from HTML
            console.log(list + " is " + index++);
        }
    }
}
</code>```

Title: JS - for loop inside for loop

Body:
I'm writing a function to count number, first loop get all the values from table row, the console return:

apple is 0
banana is 1
orange is 2
watermelon is 3

If there's a number (ex:2) passing to the function, inside for loop will rearrange the number, I wish console return:

apple is 0
banana is 1
watermelon is 2

But console actually return:

apple is 0
apple is 1
apple is 2
apple is 3
apple is 4
banana is 0
banana is 1
banana is 2
banana is 3
banana is 4
watermelon is 0
watermelon is 1
watermelon is 2
watermelon is 3
watermelon is 4

Don't know how to fix it, here's my code

HTML part:

apple

banana

orange

watermelon

JS part:

function del_list(number){
    //passing the number between 0 to 4
    for (i = 0; i < 5; i++) {
        var list = $("#id" + i).val(); //table row from HTML
        console.log(list + " is " +i)

        if(i != number && list != ""){
            for (s = 0; s < 5; s++) {
                console.log(list + " is " +s)
            }
        }
    }
}

Body:
You don't need a second for loop, use one loop and skip the {number} element:

function del_list(number){
    //passing the number between 0 to 4
    for (var i = 0, index = 0; i < 5; i++) {
        if (i != number) {
            var list = $("#id" + i).val(); //table row from HTML
            console.log(list + " is " + index++);
        }
    }
}


问:
Is there an official API to parse SQL LocalDB connection strings?
The standard .NET SqlConnectionStringBuilder is unaware of two "properties" that are specific to SQL LocalDB:

IsLocalDb

InstanceName

e.g. I want the following connection string (localdb)\MyInstance to resolve IsLocalDb = true, and InstanceName = MyInstance.

Is there an official/supported way to parse these SQL LocalDB-specific connection strings?

答:
There are no connection string keys with these names, where do you see that in use?

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx

You should be able to parse the "Data Source" value and get the same information, alternatively you can get the information from a open SqlConnection with the following SQL statements

```<code>SELECT SERVERPROPERTY('IsLocalDB')
</code>```

and

```<code>SELECT SERVERPROPERTY('InstanceName')
</code>```

Body:
There are no connection string keys with these names, where do you see that in use?

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx

You should be able to parse the "Data Source" value and get the same information, alternatively you can get the information from a open SqlConnection with the following SQL statements

SELECT SERVERPROPERTY('IsLocalDB')

and

SELECT SERVERPROPERTY('InstanceName')


问:
How to declare a C# Record Type?
I read on a blog that C# 7 will feature record types

```<code>class studentInfo(string StudentFName, string StudentMName, string StudentLName);
</code>```

However when I tried it, I get these errors

CS0116    A namespace cannot directly contain members such as fields or
  methods

  CS1022    Type or namespace definition, or end-of-file expected

  CS1514    { expected

How is this supposed to work?

Update: it's a feature of C# 9
 https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/

答:
[Rewritten to reflect the current state of things]

To add to the other answers, you can easily track when C# features are pencilled in to appear in C# these days. For example, the Champion "Records" issue shows the state of thinking around records. Records is now scheduled for C# 9. But that feature was previously touted for C# 6, C# 7 and C# 8 too, so it remains only an aspiration.

ContentLicense: CC BY-SA 4.0

Title: How to declare a C# Record Type?

Body:
I read on a blog that C# 7 will feature record types

class studentInfo(string StudentFName, string StudentMName, string StudentLName);

However when I tried it, I get these errors

CS0116    A namespace cannot directly contain members such as fields or
  methods

  CS1022    Type or namespace definition, or end-of-file expected

  CS1514    { expected

How is this supposed to work?

Update: it's a feature of C# 9
 https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/


问:
Process n objects each time by condition
I have next object struct:

```<code>{
1698452536:Object {url: "1", isProcessed: false}
1701673991:Object {url: "2", isProcessed: false}
1717724454:Object {url: "3", isProcessed: false}
1756233961:Object {url: "4", isProcessed: false}
1797093325:Object {url: "5", isProcessed: false}
1857721095:Object {url: "6", isProcessed: false}
2095153396:Object {url: "7", isProcessed: false}
2098466246:Object {url: "8", isProcessed: false}
2131427779:Object {url: "9", isProcessed: false}
89975:Object {url: "10", isProcessed: false}
21591836:Object {url: "11", isProcessed: false}
80794211:Object {url: "12", isProcessed: false}
116460496:Object {url: "13", isProcessed: false}
159798435:Object {url: "14", isProcessed: false}
223366448:Object {url: "15", isProcessed: false}
361352239:Object {url: "16", isProcessed: false}
498790092:Object {url: "17", isProcessed: false}
508072650:Object {url: "18", isProcessed: false}
514973525:Object {url: "19", isProcessed: false}
560440401:Object {url: "20", isProcessed: false}
}
</code>```

I need to process five inner objects each time and only after first five is completed take another five.
Is there is a way to do such implementation?

UPDATE:

I`d tried next code in order to transform object to chunked array, but how to call bulk by bulk async and only after full bulk is succeed take another?

```<code>chunkArray(Object.values(images),5).forEach((array)=>{});
function chunkArray(array, groupsize) {
var sets = [],
    chunks, i = 0;
chunks = array.length / groupsize;

while (i < chunks) {
    sets[i] = array.splice(0, groupsize);
    i++;
}
return sets;
</code>```

}

答:
Thanks to @Diego ZoracKy, he's answer provide me the basis to solve this issue.    </p>

```<code>let processImages = () => {
                    let itemToDo = Object.values(images).filter((item) => { return !item.isProcessed }).slice(0, 5);
                    if (itemToDo.length) {
                        async.map(itemToDo, (arrayItem, callback) => {
                                try {
                                    imagesize(arrayItem.url).then((result) => {
                                        return callback(null, result);
                                    }).catch(function(err) {
                                        return callback(err);

                                } catch (e) {
                                    return callback(err);
                                }
                            },
                            (errors, results) => {
                                results.forEach((result) => {
                                  ...
                                });
                                if (errors) {
               console.log('error', '!!!!!!!!!Exception was caught!!!!!! ');
                                }
                                processImages();
                            }
                        )
                    } else {
                        //CONTINUE TO NEXT URL
                        }
                }
                //Invoke process images function first time
            processImages();
</code>```

Body:
I have next object struct:

{
1698452536:Object {url: "1", isProcessed: false}
1701673991:Object {url: "2", isProcessed: false}
1717724454:Object {url: "3", isProcessed: false}
1756233961:Object {url: "4", isProcessed: false}
1797093325:Object {url: "5", isProcessed: false}
1857721095:Object {url: "6", isProcessed: false}
2095153396:Object {url: "7", isProcessed: false}
2098466246:Object {url: "8", isProcessed: false}
2131427779:Object {url: "9", isProcessed: false}
89975:Object {url: "10", isProcessed: false}
21591836:Object {url: "11", isProcessed: false}
80794211:Object {url: "12", isProcessed: false}
116460496:Object {url: "13", isProcessed: false}
159798435:Object {url: "14", isProcessed: false}
223366448:Object {url: "15", isProcessed: false}
361352239:Object {url: "16", isProcessed: false}
498790092:Object {url: "17", isProcessed: false}
508072650:Object {url: "18", isProcessed: false}
514973525:Object {url: "19", isProcessed: false}
560440401:Object {url: "20", isProcessed: false}
}

I need to process five inner objects each time and only after first five is completed take another five.
Is there is a way to do such implementation?

UPDATE:

I`d tried next code in order to transform object to chunked array, but how to call bulk by bulk async and only after full bulk is succeed take another?

chunkArray(Object.values(images),5).forEach((array)=>{});
function chunkArray(array, groupsize) {
var sets = [],
    chunks, i = 0;
chunks = array.length / groupsize;

while (i < chunks) {
    sets[i] = array.splice(0, groupsize);
    i++;
}
return sets;

}

Body:
Thanks to @Diego ZoracKy, he's answer provide me the basis to solve this issue.

let processImages = () => {
                    let itemToDo = Object.values(images).filter((item) => { return !item.isProcessed }).slice(0, 5);
                    if (itemToDo.length) {
                        async.map(itemToDo, (arrayItem, callback) => {
                                try {
                                    imagesize(arrayItem.url).then((result) => {
                                        return callback(null, result);
                                    }).catch(function(err) {
                                        return callback(err);

                                } catch (e) {
                                    return callback(err);
                                }
                            },
                            (errors, results) => {
                                results.forEach((result) => {
                                  ...
                                });
                                if (errors) {
               console.log('error', '!!!!!!!!!Exception was caught!!!!!! ');
                                }
                                processImages();
                            }
                        )
                    } else {
                        //CONTINUE TO NEXT URL
                        }
                }
                //Invoke process images function first time
            processImages();


问:
Android Listview new item at top
I have a Listview. I want to order it such that when new item added they add at top. I try

```<code>Collections.reverse(ListElementsArrayList);
</code>```

And it works. But after (second,third click,....) it mix all earlier item.Is this possible. If yes help me.

My MainActivity is

```<code>package com.pradeep.ap;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class AP extends AppCompatActivity {

EditText A, B, D, N, AN;
Button a, b, d, n, an, AP, GP, HP;
int Count = 0;
ListView LV;

String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ap);

    A = (EditText) findViewById(R.id.eta);
    B = (EditText) findViewById(R.id.etb);
    D = (EditText) findViewById(R.id.etd);
    N = (EditText) findViewById(R.id.etn);
    AN = (EditText) findViewById(R.id.etan);
    AP = (Button) findViewById(R.id.apap);
    GP = (Button) findViewById(R.id.apgp);
    HP = (Button) findViewById(R.id.aphp);

    a = (Button) findViewById(R.id.a);
    b = (Button) findViewById(R.id.b);
    d = (Button) findViewById(R.id.d);
    n = (Button) findViewById(R.id.n);
    an = (Button) findViewById(R.id.an);
    LV = (ListView) findViewById(R.id.lv);

    handler = new Handler();
    ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
    adapter = new ArrayAdapter<String>(AP.this,android.R.layout.simple_list_item_1,
            ListElementsArrayList);
    LV.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numb = 0;
            float numd = 0;
            float numleal=0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(B.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())) {
                return;
            }
            numb = Float.parseFloat(B.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            ListElementsArrayList.add("  First  term  of  AP  is  =  " + A.getText().toString());
            result = numb - numd;
            Count = LV.getAdapter().getCount() + 1;
            Result = (int) result;
            A.setText("" + Result);
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);
        }
    });

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numd = 0;
            float result = 0;
            int Result;
            Count = LV.getAdapter().getCount() + 1;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            result = numa + numd;
            Result = (int) result;
            B.setText("" + Result);
            ListElementsArrayList.add("  Second  term  of  AP  is  =  " + B.getText().toString());
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);

        }
    });

    d.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numb = 0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(B.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numb = Float.parseFloat(B.getText().toString());
            result = numb - numa;
            Result = (int) result;
            Count = LV.getAdapter().getCount() + 1;
            D.setText("" + Result);
            ListElementsArrayList.add("  Value  of  D  is  =  " + D.getText().toString());
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);
        }
    });
    n.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numd = 0;
            float numan = 0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())
                    || TextUtils.isEmpty(AN.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            numan = Float.parseFloat(AN.getText().toString());
            result = ((numan - numa) / numd) + 1;
            Result = (int) result;
            Count = LV.getAdapter().getCount() + 1;
            N.setText("" + Result);
            ListElementsArrayList.add("  Number  of  term/terms  in  this  AP  is  =  " + N.getText().toString());
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);
        }
    });

    an.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numd = 0;
            float numn = 0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())
                    || TextUtils.isEmpty(N.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            numn = Float.parseFloat(N.getText().toString());
            result = ((numn - 1) * numd) + numa;
            Result = (int) result;
            AN.setText("" + Result);
            Count = LV.getAdapter().getCount() + 1;
            ListElementsArrayList.add("  Term/Terms of this AP  is  =  " + AN.getText().toString());
            adapter.notifyDataSetChanged();
            adapter.getCount();
            Collections.reverse(ListElementsArrayList);
        }
    });
}
</code>```

}

答:
Just use

```<code>List.add(0, element)
</code>```

to add an element as first element of a list. As described in the documentation.

Title: Android Listview new item at top

Body:
I have a Listview. I want to order it such that when new item added they add at top. I try

Collections.reverse(ListElementsArrayList);

And it works. But after (second,third click,....) it mix all earlier item.Is this possible. If yes help me.

My MainActivity is

package com.pradeep.ap;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class AP extends AppCompatActivity {

EditText A, B, D, N, AN;
Button a, b, d, n, an, AP, GP, HP;
int Count = 0;
ListView LV;

String[] ListElements = new String[]{};
List<String> ListElementsArrayList;
ArrayAdapter<String> adapter;
Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ap);

    A = (EditText) findViewById(R.id.eta);
    B = (EditText) findViewById(R.id.etb);
    D = (EditText) findViewById(R.id.etd);
    N = (EditText) findViewById(R.id.etn);
    AN = (EditText) findViewById(R.id.etan);
    AP = (Button) findViewById(R.id.apap);
    GP = (Button) findViewById(R.id.apgp);
    HP = (Button) findViewById(R.id.aphp);

    a = (Button) findViewById(R.id.a);
    b = (Button) findViewById(R.id.b);
    d = (Button) findViewById(R.id.d);
    n = (Button) findViewById(R.id.n);
    an = (Button) findViewById(R.id.an);
    LV = (ListView) findViewById(R.id.lv);

    handler = new Handler();
    ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
    adapter = new ArrayAdapter<String>(AP.this,android.R.layout.simple_list_item_1,
            ListElementsArrayList);
    LV.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    a.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numb = 0;
            float numd = 0;
            float numleal=0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(B.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())) {
                return;
            }
            numb = Float.parseFloat(B.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            ListElementsArrayList.add("  First  term  of  AP  is  =  " + A.getText().toString());
            result = numb - numd;
            Count = LV.getAdapter().getCount() + 1;
            Result = (int) result;
            A.setText("" + Result);
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);
        }
    });

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numd = 0;
            float result = 0;
            int Result;
            Count = LV.getAdapter().getCount() + 1;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            result = numa + numd;
            Result = (int) result;
            B.setText("" + Result);
            ListElementsArrayList.add("  Second  term  of  AP  is  =  " + B.getText().toString());
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);

        }
    });

    d.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numb = 0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(B.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numb = Float.parseFloat(B.getText().toString());
            result = numb - numa;
            Result = (int) result;
            Count = LV.getAdapter().getCount() + 1;
            D.setText("" + Result);
            ListElementsArrayList.add("  Value  of  D  is  =  " + D.getText().toString());
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);
        }
    });
    n.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numd = 0;
            float numan = 0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())
                    || TextUtils.isEmpty(AN.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            numan = Float.parseFloat(AN.getText().toString());
            result = ((numan - numa) / numd) + 1;
            Result = (int) result;
            Count = LV.getAdapter().getCount() + 1;
            N.setText("" + Result);
            ListElementsArrayList.add("  Number  of  term/terms  in  this  AP  is  =  " + N.getText().toString());
            adapter.notifyDataSetChanged();
            Collections.reverse(ListElementsArrayList);
        }
    });

    an.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float numa = 0;
            float numd = 0;
            float numn = 0;
            float result = 0;
            int Result;
            if (TextUtils.isEmpty(A.getText().toString())
                    || TextUtils.isEmpty(D.getText().toString())
                    || TextUtils.isEmpty(N.getText().toString())) {
                return;
            }
            numa = Float.parseFloat(A.getText().toString());
            numd = Float.parseFloat(D.getText().toString());
            numn = Float.parseFloat(N.getText().toString());
            result = ((numn - 1) * numd) + numa;
            Result = (int) result;
            AN.setText("" + Result);
            Count = LV.getAdapter().getCount() + 1;
            ListElementsArrayList.add("  Term/Terms of this AP  is  =  " + AN.getText().toString());
            adapter.notifyDataSetChanged();
            adapter.getCount();
            Collections.reverse(ListElementsArrayList);
        }
    });
}

}

Body:
Just use

List.add(0, element)

to add an element as first element of a list. As described in the documentation.


问:
How do I add a link action inside a grid/column in MVC using Razor only
I am using Razor grid system to show a listing. I want to make a column as a link action. But my problem is it's showing the link in the font end as raw HTML file.
My code is

```<code>columns.Add(c => c.Title).Titled("Title").Filterable(true).RenderValueAs(c => Html.ActionLink(c.Title, "Details", new { id = c.Id }));
</code>```

There fore the output is

I have also used Format() in placement of RenderValueAs() However the result is same.
I have studied through from this links.Link1, Link1, Link1, Link1 But no probable solution is found.
And I don't want to solve this without any help of javascript or any scripting language. I am looking for only razor related solution. Thank you.

答:
Possibly I got a solution of my own question, I have checked it.

Instead of using
 columns.Add(c => c.Title).Titled("Title").Filterable(true).RenderValueAs(c=>Html.ActionLink(c.Title, "Details", new { id = c.Id }));

I have used

```<code>@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml(
        tableStyle: "webgrid-table",
        headerStyle: "webgrid-header",
        footerStyle: "webgrid-footer",
        alternatingRowStyle: "webgrid-alternating-row",
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
        mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
            grid.Column(columnName: "Student Name", header: "Name", format: @<text>@item.Name</text>),
            grid.Column(columnName: "SchoolName", header: "School Name", format: @<text>@item.SchoolName</text> ),
            grid.Column(columnName: "Address", header: "Address", format: @<text>@item.Address</text>),
            grid.Column(columnName: "City", header: "City", format: @<a>@item.City</a>),
            grid.Column(columnName: "State", header: "State", format: @<text>@item.State</text>)
           ))
</code>```

Here i have attached  on cities. So therefore I am quiet capable of customize the whole grid by myself as same. From reference link i obtained this strategy.

Body:
I am using Razor grid system to show a listing. I want to make a column as a link action. But my problem is it's showing the link in the font end as raw HTML file.
My code is

columns.Add(c => c.Title).Titled("Title").Filterable(true).RenderValueAs(c => Html.ActionLink(c.Title, "Details", new { id = c.Id }));

There fore the output is

I have also used Format() in placement of RenderValueAs() However the result is same.
I have studied through from this links.Link1, Link1, Link1, Link1 But no probable solution is found.
And I don't want to solve this without any help of javascript or any scripting language. I am looking for only razor related solution. Thank you.

Body:
Possibly I got a solution of my own question, I have checked it.

Instead of using
 columns.Add(c => c.Title).Titled("Title").Filterable(true).RenderValueAs(c=>Html.ActionLink(c.Title, "Details", new { id = c.Id }));

I have used

@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml(
        tableStyle: "webgrid-table",
        headerStyle: "webgrid-header",
        footerStyle: "webgrid-footer",
        alternatingRowStyle: "webgrid-alternating-row",
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
        mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
            grid.Column(columnName: "Student Name", header: "Name", format: @<text>@item.Name</text>),
            grid.Column(columnName: "SchoolName", header: "School Name", format: @<text>@item.SchoolName</text> ),
            grid.Column(columnName: "Address", header: "Address", format: @<text>@item.Address</text>),
            grid.Column(columnName: "City", header: "City", format: @<a>@item.City</a>),
            grid.Column(columnName: "State", header: "State", format: @<text>@item.State</text>)
           ))

Here i have attached <a> on cities. So therefore I am quiet capable of customize the whole grid by myself as same. From reference link i obtained this strategy.


问:
oauth2client.client.AccessTokenRefreshError: invalid_grant
I've a Python script on a server, which runs every day at morning, and syncing rows from several databases to a Google Spreadsheet. This script runs till May of 2016 on that server without any problem, and runs an another one too since older. The scripts are equals and use same JSON credentials files.
A few days ago, on that server I've got this error message:

```<code>File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 326, in authorize
  client.login()
File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 85, in login
  self.auth.refresh(http)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 516, in refresh
  self._refresh(http.request)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 653, in _refresh
  self._do_refresh_request(http_request)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 710, in _do_refresh_request
  raise AccessTokenRefreshError(error_msg)
oauth2client.client.AccessTokenRefreshError: invalid_grant
</code>```

But (as I wrote) the same script runs without problem on another server. The two scripts uses different spreadsheets, but all of them had permissions for the service user. There isn't any changes in documents shared, permissions, etc. Both server has same script and json credential file, but the mentioned server asserts this message. That scripts had worked about 3 months. No changes in code, nor permissions.

What would be the problem?

Thanks,
a.

答:
Your issue was most probably caused due to a wrong server time synchronizaton.

Next time, try to sync your server time to Network Time Servers by, for example, installing ntp.

That should solve the issue.

Body:
I've a Python script on a server, which runs every day at morning, and syncing rows from several databases to a Google Spreadsheet. This script runs till May of 2016 on that server without any problem, and runs an another one too since older. The scripts are equals and use same JSON credentials files.
A few days ago, on that server I've got this error message:

File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 326, in authorize
  client.login()
File "/usr/local/lib/python2.7/dist-packages/gspread/client.py", line 85, in login
  self.auth.refresh(http)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 516, in refresh
  self._refresh(http.request)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 653, in _refresh
  self._do_refresh_request(http_request)
File "/usr/lib/python2.7/dist-packages/oauth2client/client.py", line 710, in _do_refresh_request
  raise AccessTokenRefreshError(error_msg)
oauth2client.client.AccessTokenRefreshError: invalid_grant

But (as I wrote) the same script runs without problem on another server. The two scripts uses different spreadsheets, but all of them had permissions for the service user. There isn't any changes in documents shared, permissions, etc. Both server has same script and json credential file, but the mentioned server asserts this message. That scripts had worked about 3 months. No changes in code, nor permissions.

What would be the problem?

Thanks,
a.


问:
How to change state of nested formly form to readonly on click of a button
My problem is pretty straight forward.

Things that I have.

-- A form (formly) which I made using the data (JSON) received form the backend.

-- The form is going to be Multilevel Nested (currently its two level nested).

-- There is a repeater associated to every nested form element that will add another element to the form on click of a button.

-- There is going to be a button on the top of the page that will toggle the state of the form elements to readOnly.

Problem that I am facing

-- When I click the button, the state of the form elements change to readOnly, except the ones that are nested.

What I want

--When I click the button, every single element of my form should change its state to readOnly, nested or not.

Here is the controller...Followed by JS-Bin link.

app.controller('MainCtrl', function MainCtrl(formlyVersion) {
  var vm = this;

  vm.onSubmit = onSubmit;
  vm.exampleTitle = 'Nested Repeating Section';
  vm.options = {
    formState: {
      readOnly: true
    }
  };

  init();

  vm.originalFields = angular.copy(vm.fields);

  function onSubmit() {
    alert(JSON.stringify(vm.model), null, 2);
  }

  function init() {
    vm.fields = [{
      key: 'name',
      type: 'input',

      templateOptions: {
        label: 'Name',
        required: true,
        minlength: 5,
        maxlength: 25
      }
    }, {
      key: 'description',
      type: 'textarea',

      templateOptions: {
        label: 'Description',
        rows: 5,
        maxlength: 100
      }
    }, {
      wrapper: 'panel',
      templateOptions: {
        label: 'Cars'
      },
      fieldGroup: [{
        type: 'repeatSection',
        key: 'cars',
        templateOptions: {
          btnText: '+',
          fields: [{

            wrapper: 'panel',
            templateOptions: {
              label: 'New car'
            },
            fieldGroup: [{
              key: 'carname',
              type: 'input',
              templateOptions: {
                label: 'Name',
                required: true,
                maxlength: 25
              }
            }, {
              key: 'cardesc',
              type: 'input',
              templateOptions: {
                label: 'Description',
                maxlength: 50
              }
            }]
          }]
        }
      }]
    }];
  }
});```

http://jsbin.com/sunocaf/edit?html,js,output

Thanks in advance

P.S. - I took the example from the official angular formly website.

答:
I was able to find a work around to my problem. I am still controlling the disable function via a button, the only difference is that I am using a separate controller for the repeated section of my form.

That way I can provide a flag using a data service to the repeated section's controller in order to make it disabled along with the whole form.

To achieve this I had to tweak the repeated section's wrapper a bit, but the end result was just what I wanted.

Cheers.

Body:
My problem is pretty straight forward.

Things that I have.

-- A form (formly) which I made using the data (JSON) received form the backend.

-- The form is going to be Multilevel Nested (currently its two level nested).

-- There is a repeater associated to every nested form element that will add another element to the form on click of a button.

-- There is going to be a button on the top of the page that will toggle the state of the form elements to readOnly.

Problem that I am facing

-- When I click the button, the state of the form elements change to readOnly, except the ones that are nested.

What I want

--When I click the button, every single element of my form should change its state to readOnly, nested or not.

Here is the controller...Followed by JS-Bin link.

app.controller('MainCtrl', function MainCtrl(formlyVersion) {
  var vm = this;

  vm.onSubmit = onSubmit;
  vm.exampleTitle = 'Nested Repeating Section';
  vm.options = {
    formState: {
      readOnly: true
    }
  };

  init();

  vm.originalFields = angular.copy(vm.fields);

  function onSubmit() {
    alert(JSON.stringify(vm.model), null, 2);
  }

  function init() {
    vm.fields = [{
      key: 'name',
      type: 'input',

      templateOptions: {
        label: 'Name',
        required: true,
        minlength: 5,
        maxlength: 25
      }
    }, {
      key: 'description',
      type: 'textarea',

      templateOptions: {
        label: 'Description',
        rows: 5,
        maxlength: 100
      }
    }, {
      wrapper: 'panel',
      templateOptions: {
        label: 'Cars'
      },
      fieldGroup: [{
        type: 'repeatSection',
        key: 'cars',
        templateOptions: {
          btnText: '+',
          fields: [{

            wrapper: 'panel',
            templateOptions: {
              label: 'New car'
            },
            fieldGroup: [{
              key: 'carname',
              type: 'input',
              templateOptions: {
                label: 'Name',
                required: true,
                maxlength: 25
              }
            }, {
              key: 'cardesc',
              type: 'input',
              templateOptions: {
                label: 'Description',
                maxlength: 50
              }
            }]
          }]
        }
      }]
    }];
  }
});

http://jsbin.com/sunocaf/edit?html,js,output

Thanks in advance

P.S. - I took the example from the official angular formly website.


问:
PHP MySQL select all results with ASC references
Suppose I have the following table:

```<code>ID|Reference
1 |23
1 |27
1 |47
1 |48
2 |16
2 |17
2 |18
2 |33
3 |16
3 |19
3 |22
4 |2
5 |6
5 |8
5 |7
5 |12
</code>```

I want to select all the ID's that have at least 2 ASC references with a difference of 1. So for instance when I execute the query, I want a return of:

```<code>ID|Reference
1 |47
1 |48
2 |16
2 |17
2 |18
5 |6
5 |8
5 |7
</code>```

Ofcourse, I could use a query like:

```<code>SELECT ID, Reference FROM Table ORDER BY Reference ASC
</code>```

and loop through the results and check it manually. However, I am wondering whether MySQL could achieve this in a single query and pop back the right results, since this will optimize performance (I guess)

答:
It is strange a field called ID that is not unique, you probably have a good reason.

You can try with a query like

```<code>SELECT ID, Reference FROM Table WHERE EXISTS (SELECT * FROM Table T WHERE T.ID = Table.ID AND T.Reference = Table.Reference - 1) OR EXISTS (SELECT * FROM Table T WHERE T.ID = Table.ID AND T.Reference = Table.Reference + 1)
</code>```

That means "get elements that have another element with same ID and a Reference with distance 1 (lower or higer)". It will not return exactly the ID's (you can try with SELECT DISTINTC(ID)...) it will return a result like your example with ID, Reference pairs where IDs will be not unique.

I am not sure if this will be more efficient, it probably depends on how many records you have in your table and how many records will match your condition.

Good luck.

Body:
Suppose I have the following table:

ID|Reference
1 |23
1 |27
1 |47
1 |48
2 |16
2 |17
2 |18
2 |33
3 |16
3 |19
3 |22
4 |2
5 |6
5 |8
5 |7
5 |12

I want to select all the ID's that have at least 2 ASC references with a difference of 1. So for instance when I execute the query, I want a return of:

ID|Reference
1 |47
1 |48
2 |16
2 |17
2 |18
5 |6
5 |8
5 |7

Ofcourse, I could use a query like:

SELECT ID, Reference FROM Table ORDER BY Reference ASC

and loop through the results and check it manually. However, I am wondering whether MySQL could achieve this in a single query and pop back the right results, since this will optimize performance (I guess)

Body:
It is strange a field called ID that is not unique, you probably have a good reason.

You can try with a query like

SELECT ID, Reference FROM Table WHERE EXISTS (SELECT * FROM Table T WHERE T.ID = Table.ID AND T.Reference = Table.Reference - 1) OR EXISTS (SELECT * FROM Table T WHERE T.ID = Table.ID AND T.Reference = Table.Reference + 1)

That means "get elements that have another element with same ID and a Reference with distance 1 (lower or higer)". It will not return exactly the ID's (you can try with SELECT DISTINTC(ID)...) it will return a result like your example with ID, Reference pairs where IDs will be not unique.

I am not sure if this will be more efficient, it probably depends on how many records you have in your table and how many records will match your condition.

Good luck.


答:
Let's do the first one.

```<code>// method to return the number of spaces in a String
public static ________ countSpaces(________) {

}
</code>```

What needs to be added is this

```<code>// method to return the number of spaces in a String
public static int countSpaces(String input) {
   int spaces = 0;
   // Do the magic counting here
   return spaces;
}
</code>```

Now the method takes a String as input and returns an integer as output.

Title: I just started using methods. This is a template and I'm confused on how to do the methods. Can someone show me how to do what is being asked?

Body:
Let's do the first one.

// method to return the number of spaces in a String
public static ________ countSpaces(________) {

}

What needs to be added is this

// method to return the number of spaces in a String
public static int countSpaces(String input) {
   int spaces = 0;
   // Do the magic counting here
   return spaces;
}

Now the method takes a String as input and returns an integer as output.


问:
Disable the UTC timezone
I am trying to display the UTC Time zone in the hightchart but I do not know how to add the setOption in the Highchart to global{useUTC: false} in my HighChart? I want to disable the UTC Timezon.

https://jsfiddle.net/LLExL/7281/

Title: Disable the UTC timezone

Body:
Apply like this  useUTC

Highcharts.setOptions({
  global: {
    useUTC: false
  }
});

Highcharts.chart('container',

  {
    chart: {
      type: 'columnrange',
      inverted: true,
      height: 200,
      spacingLeft: 30
    },
    credits: {
      enabled: false
    },
    title: {
      text: null,
      style: {
        "fontSize": "10px"
      }
    },
    subTitle: {
      text: null
    },
    legend: {
      enabled: false,
    },
    plotOptions: {
      series: {
        pointWidth: 30
      }
    },
    xAxis: {
      min: 1,
      max: 1,
      categories: ['', ''],
      title: {
        text: null
      },
      labels: {
        rotation: 90
      },
      gridLineWidth: 0
    },
    yAxis: {
      type: 'datetime',
      title: {
        text: null
      },
      labels: {
        rotation: -45,
        style: {
          "fontSize": "10px"
        }
      },
      tickInterval: 1800000,
      gridLineWidth: 1
    },
    series: [{
      data: [
        [1, 1483337940000, 1483338000000],
        [1, 1483338300000, 1483339740000],
        [1, 1483340580000, 1483340640000],
        [1, 1483340640000, 1483340820000],
        [1, 1483340820000, 1483341000000],
        [1, 1483342800000, 1483342860000],
        [1, 1483342860000, 1483342920000],
        [1, 1483342920000, 1483342980000],
        [1, 1483346460000, 1483346520000],
        [1, 1483347120000, 1483347180000],
        [1, 1483347180000, 1483348440000],
        [1, 1483348440000, 1483348620000],
        [1, 1483348620000, 1483348740000],
        [1, 1483350180000, 1483350240000],
        [1, 1483350420000, 1483351380000],
        [1, 1483353300000, 1483353420000],
        [1, 1483355280000, 1483355340000],
        [1, 1483358580000, 1483359780000],
      ]
    }]
  }

);

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container">

</div>


问:
Zend Framework - 500 Internal Server Error
Today I create my first project with Zend Framework but when I try to connect to my project I see only "500 Internal Server Error". I add some new rows in httpd.conf file:

```<code>NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot C:\AppServ\www\data1\public
ServerName my_ip
</VirtualHost>

NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot C:\AppServ\www\data1\public
ServerName http://my_ip
</VirtualHost>
</code>```

And that is my htaccess file:

```<code>RewriteEngine On
#RewriteBase data1/public/
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|html|pps)$ index.php [NC,L]

order allow,deny
allow from all
</code>```

I read more topics for this problem but for now problem is not solved.

That is my error.log file(from server):

```<code>[Wed Aug 08 01:46:02 2012] [warn] NameVirtualHost *:80 has no VirtualHosts
PHP Warning:  PHP Startup: Unable to load dynamic library 'C:/AppServ\\php5        \\ext\\php_exif.dll' - \xd3\xea\xe0\xe7\xe0\xed\xe0\xf2\xe0 \xef\xf0\xee\xf6\xe5\xe4 \xf3\xf0\xe0 \xed\xe5 \xe5 \xed\xe0\xec\xe5\xf0\xe5\xed\xe0.\r\n in Unknown on line 0
[Wed Aug 08 01:46:02 2012] [notice] Apache/2.2.8 (Win32) PHP/5.2.6 configured -- resuming normal operations
[Wed Aug 08 01:46:02 2012] [notice] Server built: Jan 18 2008 00:37:19
[Wed Aug 08 01:46:02 2012] [notice] Parent: Created child process 2392
[Wed Aug 08 01:46:02 2012] [warn] NameVirtualHost *:80 has no VirtualHosts
[Wed Aug 08 01:46:02 2012] [warn] NameVirtualHost *:80 has no VirtualHosts
PHP Warning:  PHP Startup: Unable to load dynamic library 'C:/AppServ\\php5\\ext\\php_exif.dll' - \xd3\xea\xe0\xe7\xe0\xed\xe0\xf2\xe0 \xef\xf0\xee\xf6\xe5\xe4\xf3\xf0\xe0 \xed\xe5 \xe5 \xed\xe0\xec\xe5\xf0\xe5\xed\xe0.\r\n in Unknown on line 0
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Child process is running
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Acquired the start mutex.
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Starting 64 worker threads.
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Starting thread to listen on port 80.
[Wed Aug 08 01:46:15 2012] [alert] [client 46.40.124.225] C:/AppServ/www/data1/public/.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration
</code>```

答:
I just had the exact same problem and the solution by drew010 did fix it indeed!

However, it seems Apache config structure changed, so the method to enable the missing module is slightly different:

```<code>$ cd /etc/apache2/mods-enabled
$ sudo ln -s ../mods-available/rewrite.load ./rewrite.load
</code>```

This confirms you have the right stuff going:

```<code>$ cd /etc/apache2/mods-enabled
$ cat ./rewrite.load
LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so
</code>```

Cheers!

Body:
Today I create my first project with Zend Framework but when I try to connect to my project I see only "500 Internal Server Error". I add some new rows in httpd.conf file:

NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot C:\AppServ\www\data1\public
ServerName my_ip
</VirtualHost>

NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot C:\AppServ\www\data1\public
ServerName http://my_ip
</VirtualHost>

And that is my htaccess file:

RewriteEngine On
#RewriteBase data1/public/
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|html|pps)$ index.php [NC,L]

order allow,deny
allow from all

I read more topics for this problem but for now problem is not solved.

That is my error.log file(from server):

[Wed Aug 08 01:46:02 2012] [warn] NameVirtualHost *:80 has no VirtualHosts
PHP Warning:  PHP Startup: Unable to load dynamic library 'C:/AppServ\\php5        \\ext\\php_exif.dll' - \xd3\xea\xe0\xe7\xe0\xed\xe0\xf2\xe0 \xef\xf0\xee\xf6\xe5\xe4 \xf3\xf0\xe0 \xed\xe5 \xe5 \xed\xe0\xec\xe5\xf0\xe5\xed\xe0.\r\n in Unknown on line 0
[Wed Aug 08 01:46:02 2012] [notice] Apache/2.2.8 (Win32) PHP/5.2.6 configured -- resuming normal operations
[Wed Aug 08 01:46:02 2012] [notice] Server built: Jan 18 2008 00:37:19
[Wed Aug 08 01:46:02 2012] [notice] Parent: Created child process 2392
[Wed Aug 08 01:46:02 2012] [warn] NameVirtualHost *:80 has no VirtualHosts
[Wed Aug 08 01:46:02 2012] [warn] NameVirtualHost *:80 has no VirtualHosts
PHP Warning:  PHP Startup: Unable to load dynamic library 'C:/AppServ\\php5\\ext\\php_exif.dll' - \xd3\xea\xe0\xe7\xe0\xed\xe0\xf2\xe0 \xef\xf0\xee\xf6\xe5\xe4\xf3\xf0\xe0 \xed\xe5 \xe5 \xed\xe0\xec\xe5\xf0\xe5\xed\xe0.\r\n in Unknown on line 0
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Child process is running
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Acquired the start mutex.
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Starting 64 worker threads.
[Wed Aug 08 01:46:02 2012] [notice] Child 2392: Starting thread to listen on port 80.
[Wed Aug 08 01:46:15 2012] [alert] [client 46.40.124.225] C:/AppServ/www/data1/public/.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Body:
I just had the exact same problem and the solution by drew010 did fix it indeed!

However, it seems Apache config structure changed, so the method to enable the missing module is slightly different:

$ cd /etc/apache2/mods-enabled
$ sudo ln -s ../mods-available/rewrite.load ./rewrite.load

This confirms you have the right stuff going:

$ cd /etc/apache2/mods-enabled
$ cat ./rewrite.load
LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so

Cheers!


问:
print last '\n' char using print method in python
Imagine I have the following code in file test.py:

```<code>for x in range(1,11):
     print x
</code>```

This will print:

```<code>$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
</code>```

However, I want it to print:

```<code>$myuser: python test.py
1
2
3
4
5
6
7
8
9
10

$myuser:
</code>```

Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?

答:
That's why I love python3:

```<code>print(*range(5), sep='\n',end='\n\n')
</code>```

actually this is ugly:

```<code>for i in range(5)+['']:
    print i
</code>```

Body:
Imagine I have the following code in file test.py:

for x in range(1,11):
     print x

This will print:

$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:

However, I want it to print:

$myuser: python test.py
1
2
3
4
5
6
7
8
9
10

$myuser:

Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?

Body:
That's why I love python3:

print(*range(5), sep='\n',end='\n\n')

actually this is ugly:

for i in range(5)+['']:
    print i


问:
Drawing a right triangle (Python 3)
I'm having a bit of an issue. I'm trying to make this program output a right triangle based on the height and symbol that is specified by the user, but whenever I enter the symbol and height desired the program will output the correct shape, but upside-down. I've been having some difficulties getting a firm grasp of loops and through trial and error, this is the best I could come up with thus far. Could someone help a brother out, please. Thank yous in advance.

```<code>triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1
</code>```

This code will return this output when character is '*' and height is 5:

```<code>*****
****
***
**
*
</code>```

The expected output when those values are entered should be:

```<code>*
**
***
****
*****
</code>```

答:
Here it is as a script. I assumed that multiple input characters meant multiple output triangles. Also, that height:0 means zero lines in each triangle.

Tricky thing I learned today is that int("20.0") doesn't convert to 20; it raises an exception. The code works around that by converting to float first.

```<code>#!/usr/bin/python3

def triangles(characters, height):
    # We could call int(height) here except that int("20.0") for example raises
    # an error even though there is a pretty clear integer value. To get around
    # that, attempt to convert to float first.
    try:
        lines = float(height)
    except ValueError:
        # If we raise here, the error is like: cannot convert to float. That's
        # confusing, so we let it go.
        lines = height

    # If the value can't be converted to int, this raises an error like: cannot
    # convert to int. If it had already converted to float, this rounds down.
    lines = int(lines)

    for character in characters:
        # Loop will execute no times if lines==0, once if lines==1 and so on.
        for line in range(1, lines + 1):
            print(str(character) * line)
        print("")

if __name__ == '__main__':
    try:
        triangles(input("Enter characters: "), input("Enter height: "))
    except ValueError as error:
        print("Couldn't print triangles:", error)
</code>```

Edit: Added sample output.

```<code>$ ./triangles.py
Enter characters: jk
Enter height: 8
j
jj
jjj
jjjj
jjjjj
jjjjjj
jjjjjjj
jjjjjjjj

k
kk
kkk
kkkk
kkkkk
kkkkkk
kkkkkkk
kkkkkkkk

$ ./triangles.py
Enter characters: .
Enter height: 3.0
.
..
...

$ ./triangles.py
Enter characters: f
Enter height: 3.7
f
ff
fff

$ ./triangles.py
Enter characters: duff
Enter height: duff
Couldn't print triangles: invalid literal for int() with base 10: 'duff'
</code>```

Title: Drawing a right triangle (Python 3)

Body:
I'm having a bit of an issue. I'm trying to make this program output a right triangle based on the height and symbol that is specified by the user, but whenever I enter the symbol and height desired the program will output the correct shape, but upside-down. I've been having some difficulties getting a firm grasp of loops and through trial and error, this is the best I could come up with thus far. Could someone help a brother out, please. Thank yous in advance.

triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')

for i in range (len(triangle_char)):
    for j in range (triangle_height):
        print((triangle_char) * triangle_height )
        triangle_height -= 1

This code will return this output when character is '*' and height is 5:

*****
****
***
**
*

The expected output when those values are entered should be:

*
**
***
****
*****

Body:
Here it is as a script. I assumed that multiple input characters meant multiple output triangles. Also, that height:0 means zero lines in each triangle.

Tricky thing I learned today is that int("20.0") doesn't convert to 20; it raises an exception. The code works around that by converting to float first.

#!/usr/bin/python3

def triangles(characters, height):
    # We could call int(height) here except that int("20.0") for example raises
    # an error even though there is a pretty clear integer value. To get around
    # that, attempt to convert to float first.
    try:
        lines = float(height)
    except ValueError:
        # If we raise here, the error is like: cannot convert to float. That's
        # confusing, so we let it go.
        lines = height

    # If the value can't be converted to int, this raises an error like: cannot
    # convert to int. If it had already converted to float, this rounds down.
    lines = int(lines)

    for character in characters:
        # Loop will execute no times if lines==0, once if lines==1 and so on.
        for line in range(1, lines + 1):
            print(str(character) * line)
        print("")

if __name__ == '__main__':
    try:
        triangles(input("Enter characters: "), input("Enter height: "))
    except ValueError as error:
        print("Couldn't print triangles:", error)

Edit: Added sample output.

$ ./triangles.py
Enter characters: jk
Enter height: 8
j
jj
jjj
jjjj
jjjjj
jjjjjj
jjjjjjj
jjjjjjjj

k
kk
kkk
kkkk
kkkkk
kkkkkk
kkkkkkk
kkkkkkkk

$ ./triangles.py
Enter characters: .
Enter height: 3.0
.
..
...

$ ./triangles.py
Enter characters: f
Enter height: 3.7
f
ff
fff

$ ./triangles.py
Enter characters: duff
Enter height: duff
Couldn't print triangles: invalid literal for int() with base 10: 'duff'


问:
How to use replaceFirst() to get a series of sequential strings in my case?
My input string uid contains 6 characters, and there are 0~6 '?' at random position like "00??00", "0?00?0", "0??00?". For example, if the input is "00?0?0", I want to replace two '?' with 0~9. So the results should be "000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"

Well, my following code can only get "000000","001010","002020"..."009090", I got to know that replace() will replace all '?', and using replaceFirst() might solve it. So how to use replaceFirst() to get the results I want?

```<code>List<Get> gets = new ArrayList<>();

for (int i =0; i<10; i++){
    get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());

    // get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());

    gets.add(get);
}
</code>```

答:
You can use a String#format(), the advantage with that approach instead of replace() is that you can keep the 2 places by adding leading zeros to the string you generate...

see this example and optimize it removing the unnecessary creation of string objects...

```<code>String patt = "00??00";
for (int i = 0; i < 10; i++) {
    String numberWithLeadingZeros = String.format("%02d", i);
    String x = String.format(patt.replace("??", "%s"), numberWithLeadingZeros);
    System.out.println(x);
}
</code>```

our final result will be something as:

"000000","000100","000200"..."000900","001000","001100"..."001900"..."009900"

Body:
My input string uid contains 6 characters, and there are 0~6 '?' at random position like "00??00", "0?00?0", "0??00?". For example, if the input is "00?0?0", I want to replace two '?' with 0~9. So the results should be "000000","000010","000020"..."000090","001000","001010"..."001090"..."009090"

Well, my following code can only get "000000","001010","002020"..."009090", I got to know that replace() will replace all '?', and using replaceFirst() might solve it. So how to use replaceFirst() to get the results I want?

List<Get> gets = new ArrayList<>();

for (int i =0; i<10; i++){
    get = new Get((uid.replace(uid.charAt(2), (char) (i + '0'))).getBytes());

    // get = new Get((uid.replaceFirst("\\?", "0+i")).getBytes());

    gets.add(get);
}

Body:
You can use a String#format(), the advantage with that approach instead of replace() is that you can keep the 2 places by adding leading zeros to the string you generate...

see this example and optimize it removing the unnecessary creation of string objects...

String patt = "00??00";
for (int i = 0; i < 10; i++) {
    String numberWithLeadingZeros = String.format("%02d", i);
    String x = String.format(patt.replace("??", "%s"), numberWithLeadingZeros);
    System.out.println(x);
}

our final result will be something as:

"000000","000100","000200"..."000900","001000","001100"..."001900"..."009900"


问:
Updating One to many relation in laravel 5.3
I want to update a one to many relationship. For example  I have a model called Product

```<code>class Product extends Model
{
    protected $primaryKey = 'product_id';
    public $timestamps = FALSE;

    public function Size(){
        return $this->hasMany('App\Size');
    }

}
</code>```

and a model called Size

```<code>class Size extends Model
{
    public $timestamps = FALSE;
    protected $fillable = ['product_id','size'];

    public function Product(){
        return $this->belongsTo('App\Product');
    }
</code>```

here is my controller:

```<code>public function update(Request $request){
    for($i = 1; $i <= $sizeCounter; $i++){
        $selectedSize = "size_$i";

        if($request->$selectedSize){
            $array = ['size'=> $request->$selectedSize];
        }
    }

    $Size = Size::where('product_id' , $request->id)->update($array);
}
</code>```

But what it is doing updating all the records of size with the selectedd product id to the last enterder size. I want to update all the sizes with the slected diffrent sizes not the last selected sizes

How to update the sizes of a particular product. Like many to many relations' sync method is there any way to update the records.

答:
You override your $array in the loop. After the for loop, $array has possibly the last size.

In general, your query is correct, but it's about the place of execute. It should be like below:

```<code>if (isset($request->$selectedSize)) { // or is_int() ?
    $Size = Size::where('product_id', $request->id)->update(['size'=> $request->$selectedSize]);
}
</code>```

Body:
I want to update a one to many relationship. For example  I have a model called Product

class Product extends Model
{
    protected $primaryKey = 'product_id';
    public $timestamps = FALSE;

    public function Size(){
        return $this->hasMany('App\Size');
    }

}

and a model called Size

class Size extends Model
{
    public $timestamps = FALSE;
    protected $fillable = ['product_id','size'];

    public function Product(){
        return $this->belongsTo('App\Product');
    }

here is my controller:

public function update(Request $request){
    for($i = 1; $i <= $sizeCounter; $i++){
        $selectedSize = "size_$i";

        if($request->$selectedSize){
            $array = ['size'=> $request->$selectedSize];
        }
    }

    $Size = Size::where('product_id' , $request->id)->update($array);
}

But what it is doing updating all the records of size with the selectedd product id to the last enterder size. I want to update all the sizes with the slected diffrent sizes not the last selected sizes

How to update the sizes of a particular product. Like many to many relations' sync method is there any way to update the records.

Body:
You override your $array in the loop. After the for loop, $array has possibly the last size.

In general, your query is correct, but it's about the place of execute. It should be like below:

if (isset($request->$selectedSize)) { // or is_int() ?
    $Size = Size::where('product_id', $request->id)->update(['size'=> $request->$selectedSize]);
}


问:
Differences between a bought certificate and a dev certificate?
I Got a solution that contains a C# winform client and a server (Windows Service WCF service, IdentityServer4 and ElasticSearch). Certificate is required when running IdentityServer in production so this will be implemented on all of the services. It will probably only be a one way certificate(function certificate for services).

The production will run a bought certificate.

Is there any reason to buy an certificate for dev or will a dev certificate from a local Windows server be enouth to really test everything like as if it was in production?

答: A test certificate will work the same way as a bought certificate. Its however possible that you will need to override the check of the certificate on client and service to grant it even if the certificate is not installed in the required service. If you however are able to generate certificate specific for the computers that are running the software, then there will be no need to override the certificate check method.</p>


问:
Unit testing AngularJS Directives with Jest
I feel I am missing something crucial in this extremely simplified angular directive unit test:

```<code>import * as angular from 'angular'
import 'angular-mocks'

const app = angular.module('my-app', [])

app.directive('myDirective', () => ({
    template: 'this does not work either',
    link: (scope, element) => { // have also tried compile fn
        console.log('This does not log')
        element.html('Hi!')
    }
}))

describe('myDirective', () => {
    var element, scope

    beforeEach(app)

    beforeEach(inject(($rootScope, $compile) => {
        scope = $rootScope.$new()
        element = $compile('<my-directive />')(scope)
        scope.$digest()
    }))

    it('should actually do something', () => {
        expect(element.html()).toEqual('Hi!')
    })
})
</code>```

When jest runs it appears the directive has not been linked/compiled/whatever

```<code> FAIL  test/HtmlToPlaintextDirective.spec.js
  ● myDirective › should actually do something

    expect(received).toEqual(expected)

    Expected value to equal:
      "Hi!"
    Received:
      ""
</code>```

答:
Updated answer:

You're right things don't work as expected when importing everything in a single file.

Digging into things it looks like you're running into some magic that Babel/Jest does to support browser scripts that rely on globals (like AngularJS).

What's happening is that your module's angular variable is not the same as the global angular variable that is visible to angular-mocks.

You can check this by running this at the top of one of your tests:

```<code>import * as angular from 'angular'
import 'angular-mocks'

console.log(angular === window.angular); // `false` in Jest!

console.log(angular.mock); // undefined
console.log(window.angular.mock); // `{...}` defined
</code>```

To work around this you just need to use the global angular variable in your tests.

src/__test__/all-in-one.test.js:

```<code>import "angular";
import "angular-mocks";

/*
Work around Jest's window/global mock magic.

Use the global version of `angular` that has been augmented by angular-mocks.
*/
var angular = window.angular;

export var app = angular.module('app', []);

app.directive('myDirective', () => ({
    link: (scope, element) => {
        console.log('This does log');
        scope.content = 'Hi!';
    },
    template: 'content: {{content}}'
}));

describe('myDirective', function(){
    var element;
    var scope;

    beforeEach(function(){
        angular.mock.module(app.name);
    });

    it('should do something', function(){
        inject(function(
            $rootScope,
            $compile
        ){
            scope = $rootScope.$new();
            element = $compile('<my-directive></my-directive>')(scope);
            scope.$digest();
        });

        expect(element.html()).toEqual('content: Hi!');
    });
});
</code>```

Original answer: (This worked because I was accidentally using the global version of angular inside my test.)

The Angular module under test isn't being initialised correctly in your tests.

Your call to beforeEach(app) isn't correct.

Instead you need to use angular.mock.module("moduleName") to initialise your module.

```<code>describe('myDirective', () => {
    var element, scope

    // You need to pass the module name to `angular.mock.module()`
    beforeEach(function(){
        angular.mock.module(app.name);
    });

    // Then you can set up and run your tests as normal:
    beforeEach(inject(($rootScope, $compile) => {
        scope = $rootScope.$new()
        element = $compile('<my-directive></my-directive>')(scope)
        scope.$digest()
    }))

    it('should actually do something', () => {
        expect(element.html()).toEqual('Hi!')
    })
});
</code>```

And then your test works as expected for me:

```<code> PASS  src\__test__\app.test.js
  myDirective
    √ should do something (46ms)
</code>```

For reference, here is the full app and test:

src/app/app.module.js:

```<code>import * as angular from 'angular'

export var app = angular.module('app', []);

app.directive('myDirective', () => ({
    link: (scope, element) => {
        console.log('This does log');
        scope.content = 'Hi!';
    },
    template: 'content: {{content}}'
}))
</code>```

src/__test__/app.test.js:

```<code>import {app} from "../app/app.module";
import "angular-mocks";

describe('myDirective', function(){
    var element;
    var scope;

    beforeEach(function(){
        angular.mock.module(app.name);
    });

    beforeEach(inject(function(
        $rootScope,
        $compile
    ){
        scope = $rootScope.$new();
        element = $compile('<my-directive></my-directive>')(scope);
        scope.$digest();
    }));

    it('should do something', function(){
        expect(element.html()).toEqual('content: Hi!');
    });
});
</code>```

Body:
I feel I am missing something crucial in this extremely simplified angular directive unit test:

import * as angular from 'angular'
import 'angular-mocks'

const app = angular.module('my-app', [])

app.directive('myDirective', () => ({
    template: 'this does not work either',
    link: (scope, element) => { // have also tried compile fn
        console.log('This does not log')
        element.html('Hi!')
    }
}))

describe('myDirective', () => {
    var element, scope

    beforeEach(app)

    beforeEach(inject(($rootScope, $compile) => {
        scope = $rootScope.$new()
        element = $compile('<my-directive />')(scope)
        scope.$digest()
    }))

    it('should actually do something', () => {
        expect(element.html()).toEqual('Hi!')
    })
})

When jest runs it appears the directive has not been linked/compiled/whatever

 FAIL  test/HtmlToPlaintextDirective.spec.js
  ● myDirective › should actually do something

    expect(received).toEqual(expected)

    Expected value to equal:
      "Hi!"
    Received:
      ""

Body:
Updated answer:

You're right things don't work as expected when importing everything in a single file.

Digging into things it looks like you're running into some magic that Babel/Jest does to support browser scripts that rely on globals (like AngularJS).

What's happening is that your module's angular variable is not the same as the global angular variable that is visible to angular-mocks.

You can check this by running this at the top of one of your tests:

import * as angular from 'angular'
import 'angular-mocks'

console.log(angular === window.angular); // `false` in Jest!

console.log(angular.mock); // undefined
console.log(window.angular.mock); // `{...}` defined

To work around this you just need to use the global angular variable in your tests.

src/__test__/all-in-one.test.js:

import "angular";
import "angular-mocks";

/*
Work around Jest's window/global mock magic.

Use the global version of `angular` that has been augmented by angular-mocks.
*/
var angular = window.angular;

export var app = angular.module('app', []);

app.directive('myDirective', () => ({
    link: (scope, element) => {
        console.log('This does log');
        scope.content = 'Hi!';
    },
    template: 'content: {{content}}'
}));

describe('myDirective', function(){
    var element;
    var scope;

    beforeEach(function(){
        angular.mock.module(app.name);
    });

    it('should do something', function(){
        inject(function(
            $rootScope,
            $compile
        ){
            scope = $rootScope.$new();
            element = $compile('<my-directive></my-directive>')(scope);
            scope.$digest();
        });

        expect(element.html()).toEqual('content: Hi!');
    });
});

Original answer: (This worked because I was accidentally using the global version of angular inside my test.)

The Angular module under test isn't being initialised correctly in your tests.

Your call to beforeEach(app) isn't correct.

Instead you need to use angular.mock.module("moduleName") to initialise your module.

describe('myDirective', () => {
    var element, scope

    // You need to pass the module name to `angular.mock.module()`
    beforeEach(function(){
        angular.mock.module(app.name);
    });

    // Then you can set up and run your tests as normal:
    beforeEach(inject(($rootScope, $compile) => {
        scope = $rootScope.$new()
        element = $compile('<my-directive></my-directive>')(scope)
        scope.$digest()
    }))

    it('should actually do something', () => {
        expect(element.html()).toEqual('Hi!')
    })
});

And then your test works as expected for me:

 PASS  src\__test__\app.test.js
  myDirective
    √ should do something (46ms)

For reference, here is the full app and test:

src/app/app.module.js:

import * as angular from 'angular'

export var app = angular.module('app', []);

app.directive('myDirective', () => ({
    link: (scope, element) => {
        console.log('This does log');
        scope.content = 'Hi!';
    },
    template: 'content: {{content}}'
}))

src/__test__/app.test.js:

import {app} from "../app/app.module";
import "angular-mocks";

describe('myDirective', function(){
    var element;
    var scope;

    beforeEach(function(){
        angular.mock.module(app.name);
    });

    beforeEach(inject(function(
        $rootScope,
        $compile
    ){
        scope = $rootScope.$new();
        element = $compile('<my-directive></my-directive>')(scope);
        scope.$digest();
    }));

    it('should do something', function(){
        expect(element.html()).toEqual('content: Hi!');
    });
});


问:
windows 10 iot raspberry pi 3 wifi hotspot
I am trying to make my RPi 3 an AP using Windows 10 IoT core. RPi is connected with internet through Ethernet port and I want to make RPi 3 builtin WiFi to share internet with other devices. I have read documentation page but it is not working for me. I have tried with Windows IoT Onboarding and from PowerShell also. After selecting adapters from IoR Onboarding, clicked on start sharing service and a message appears which says "internet conncetion sharing has started" but I can't find network on other devices.</p>

答:
After selecting adapters from IoR Onboarding, clicked on start sharing
  service and a message appears which says "internet conncetion sharing
  has started" but I can't find network on other devices.

You could open Windows Device Portal and set your raspberry pi3 as the following instruction. Before doing this you would connect your raspberry pi3 with WLAN.

Select IoT Onboarding option on the left of the page. Then an Adapter configuration must be chosen. You could choose Access point adapter Microsoft Wi-Fi Direct Virtual Adapter #2 and choose Shared network adapter LAN9512/LAN9514 USB 2.0 to Ethernet 10/100 Adapter.

Then clicked on start sharing service. You could see the message appears which says "internet conncetion sharing has started".

At last make sure select enable in radio box and click on save button under the SoftAP settings. There is a message says reboot your raspberry pi3 for changes to take effect the SoftAP settings. Please click yes and your raspberry pi3 will be restarted.

After your raspberry pi3 is started you could connect your devices like PC or mobile phone on the SoftAP which is on raspberry pi3.


问:
How to get next non child element
I honestly tried to do search before posting but couldn't find something specific.
So my task is to show hidden content in the blog, when user clicks on the link.
HTML looks like this:

```<code><div class="entry">
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is all the hidden content</p></div>
</div>
</code>```

Now jQuery I'm doing the following but it's not working:

```<code>$(".hidden_post").hide();
$(".a-toggle).click(function() {
$(this).next(".hidden_post").slideDown("slow"); });
</code>```

So to get next element I need to go to a parent element first and then proceed search from there.
Now it gets more complicated for me, because I'll actually going to have several hidden
contents in one "entry". Like this:

```<code><div class="entry">
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is hidden content #1</p></div>
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is hidden content #2</p></div>
<p>Here is a visible content <a class="a-toggle"> Read More...</a></p>
<div class="hidden_post"><p>Here is hidden content #3</p></div>
</div>
</code>```

Now if I use $(this).parent().next(".hidden_post").slideDown("slow");
It will go up to "entry" div and then will find first "hidden_post" only. I guess
I still need another solution to go straight from class="a-toggle"> to
 that is next to it. Is there any solution?

答:
You could use parent():

```<code>$(".hidden_post").hide();
$(".a-toggle").click(function() {
   $(this).parent().next(".hidden_post").slideDown("slow");
});
</code>```

Title: How to get next non child element

Body:
I honestly tried to do search before posting but couldn't find something specific.
So my task is to show hidden content in the blog, when user clicks on the link.
HTML looks like this:

Here is a visible content  Read More...

Here is all the hidden content

Now jQuery I'm doing the following but it's not working:

$(".hidden_post").hide();
$(".a-toggle).click(function() {
$(this).next(".hidden_post").slideDown("slow"); });

So to get next element I need to go to a parent element first and then proceed search from there.
Now it gets more complicated for me, because I'll actually going to have several hidden
contents in one "entry". Like this:

Here is a visible content  Read More...

Here is hidden content #1

Here is a visible content  Read More...

Here is hidden content #2

Here is a visible content  Read More...

Here is hidden content #3

Now if I use $(this).parent().next(".hidden_post").slideDown("slow");
It will go up to "entry" div and then will find first "hidden_post" only. I guess
I still need another solution to go straight from  to
 that is next to it. Is there any solution?

Body:
You could use parent():

$(".hidden_post").hide();
$(".a-toggle").click(function() {
   $(this).parent().next(".hidden_post").slideDown("slow");
});