问:
Code Style Testing for Chef using Jenkins and GitHub organizations
Currently, we commit Chef cookbooks to individual repos within our GitHub organization.  We are configuring a Jenkins job per repo / cookbook which will execute cookstyle first when a commit occurs, and if cookstyle passes with no issues, it will execute Test Kitchen. We have a template Jenkins job we copy and configure for each cookbook we create.

Does anyone know if it's possible to have GitHub hooks in Jenkins to listen for commit events across the entire organization, and then execute cookstyle on a repo where a commit occurred that contain a Chef cookbook?  I'd like to have one central job handling the lint testing for our organization.

答: You can create github web hooks for your  github organization and configure your jenkins with the help of github plugin. Refer this documentation to see how to configure</p>


来源: stackexchange

问:
Import Oracle data dump and overwrite existing data
I have an oracle dmp file and I need to import data into a table.
The data in the dump contains new rows and few updated rows.
I am using import command and IGNORE=Y, so it imports all the new rows well. But it doesn't import/overwrite the existing rows (it shows a warning of unique key constraint violated).
Is there some option to make the import UPDATE the existing rows with new data?</p>

答:
You can import into temp table and then do record recon by joining with it.

Use impdp option REMAP_TABLE to load existing file into temp table.

```<code>impdp .... REMAP_TABLE=TMP_TABLE_NAME
</code>```

when load is done run MERGE statement on existing table from temp table.

ContentLicense: CC BY-SA 3.0

Body:
You can import into temp table and then do record recon by joining with it.

Use impdp option REMAP_TABLE to load existing file into temp table.

impdp .... REMAP_TABLE=TMP_TABLE_NAME

when load is done run MERGE statement on existing table from temp table.


问:
Split string every nth character from the right?
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

```<code>import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))
</code>```

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

```<code>'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])
</code>```

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

```<code>ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))
</code>```

答:
You can adapt the answer you linked, and use the beauty of mod to create a nice little one-liner:

```<code>>>> s = '1234567890'
>>> '/'.join([s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'1/234/567/890'
</code>```

and if you want this to auto-add the dot for the cases like your first example of:

```<code>s = '100243'
</code>```

then you can <s>just add a mini ternary</s> use or as suggested by @MosesKoledoye:

```<code>>>> '/'.join(([s[0:len(s)%3] or '.']) + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'./100/243'
</code>```

This method will also be faster than reversing the string before hand or reversing a list.

Body:
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))

Body:
You can adapt the answer you linked, and use the beauty of mod to create a nice little one-liner:

>>> s = '1234567890'
>>> '/'.join([s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'1/234/567/890'

and if you want this to auto-add the dot for the cases like your first example of:

s = '100243'

then you can <s>just add a mini ternary</s> use or as suggested by @MosesKoledoye:

>>> '/'.join(([s[0:len(s)%3] or '.']) + [s[i:i+3] for i in range(len(s)%3, len(s), 3)])
'./100/243'

This method will also be faster than reversing the string before hand or reversing a list.


问:
extending the c programming language with gcc
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

```<code>namespace TcpConnection {
    void* connect(char *addr)
}
</code>```

would translate to:

```<code>void* TcpConnection_connect(char *addr)
</code>```

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?

答:
For prototyping, maybe just go with a preprocessor written in the language of your choice (C, Perl, Python...) and then build it into your Makefile rules. Just to get an easy, low-cost way to try it all out...

Use a different file extension, and turn .foo into .c.

ContentLicense: CC BY-SA 2.5

Body:
I want to write my own programming language as an extension of the c programming language. The entire programming language that I am inventing are simply shorthands which translate to valid c code. For example:

namespace TcpConnection {
    void* connect(char *addr)
}

would translate to:

void* TcpConnection_connect(char *addr)

All that is done is a simple name replacement. This is only one example of an extension which I want to provide. Another simple extension would be function overloading (this would concatenate to the end of the function name the types of its arguments.

In any case, the result is perfectly valid C code. Is there any way to do this without going into gcc code?


问:
Custom URL schemes
How does one handle custom URL schemes to allow one app to be directed to another? e.g. instagram://user?username=someusername which directs a user straight to the users profile via username.  I need to create something similar.

I've checked out application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool and application(_ application: UIApplication, handleOpen url: URL) -> Bool but they seem to have a red line through when attempting to implement so I assume they are deprecated. Also, they don't seem to get called when I open my app via url from a browser.

答:
Using this url as an example: appName://?id=12345

You can do something in your app once launched using the url like so

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
    if let items = urlComponents?.queryItems as [NSURLQueryItem]?,
        (url.scheme == "appName") {
        if items.first?.name == "id",
            let id = items.first?.value {
            print(id) // prints 12345 to console
            // do something with the id, possibly present/push a controller for the user
        }
    }
    return false
}
</code>```

Title: Custom URL schemes

Body:
Using this url as an example: appName://?id=12345

You can do something in your app once launched using the url like so

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
    if let items = urlComponents?.queryItems as [NSURLQueryItem]?,
        (url.scheme == "appName") {
        if items.first?.name == "id",
            let id = items.first?.value {
            print(id) // prints 12345 to console
            // do something with the id, possibly present/push a controller for the user
        }
    }
    return false
}


问:
Exceptions handling patterns for .NET library - handle, leave unattended or rethrow?
I'm writing a C# library, whose DLL will be later used by code of other application(s).

When there is a statement in the library that could throw an exception such as System.IO.IOException, should I catch it then and there itself or should I leave it to be caught by the program of the application that uses it?

I ask this because, I have not caught the exception in my library. When debugging my application (that uses the library), Visual Studio shows it to me as an unhandled exception in the library. But when I > Continue, the program continues and the exception is caught by the application. It seems to be working fine.

Now, is it okay to do this - i.e., could there be any problems when the application is deployed? Or should it be absolutely caught in the library itself? Or does MSDN suggest somewhere, something better than this as a "best practice"?

答:
Writing a good library is an art and science. Assuming that you have already decided on functionality provided and exposed relevant APIs to consumers of the library it seems that one problem remained unresolved - exception handling.

In general exceptions which will be raised during library code execution could be divided into two groups:
1. Dependent on library implementation and functionality.
2. Dependent on consumer or system and out of area of interest for your library.

IMHO best practice would be to define all exceptions which are thrown by library code and derive them either from ApplicationException or better yet from relevant .NET exception with your lib specific prefix i.e.: <LibShortName>FormatException or <LibShortName>InvalidOperationException. Then if your library should throw exception to client code use library derived exceptions.

If there are exceptions raised outside of library and they are meaningful from your lib functionality perspective you can catch them and either throw new library exception containing as an internal exception already catched exception or use your <LibShortName>AggregateException to create chaining of exceptions before exposing them to clients.

The above scheme is used in many popular .NET libraries i.e. SharpSkia. There are other approaches to the problem, however, I find the above one most informative for library consumers - they get as much information on error as possible. Furthermore they can easily use type based patterns in catching and handling exceptions.

One of the most important aspects of writing good libraries is performance. To get best one for you library never use exception for control flow in you code. Exceptions should be used exclusively for error conditions. One of good examples of bad design violating the above pattern was ANTLR C# parser framewrok AFAIR v2. At some stage library was using exceptions for controlling parsing logic what was extremely inefficient. Later it was refactored to use exceptions only for error conditions improving performance by several orders of magnitude.

Finally one of the best books on designing .NET library APIs is:

Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries by Krzysztof Cwalina and Brad Adams.

What could be an interesting read these are discussions on API Reviews in closed and open issuess from .NET Core corefx repository and a bit old but still a classic one Krzysztof Cwalina blog posts tagged with General API Design


问:
Stack Overflow with recursion in Java
I'm trying to write an AI that never loses at Tic Tac Toe, and I want to use the minimax algorithm to do so. However, when I try to run the program, a stack overflow appears and I can't seem to find what is the error. Could you take a look and tell me what I'm doing wrong? It doesn't go as deep in the recursion I believe, since it should only go through all the possible game outcomes, which go up to 8 moves (since the player is first to play, not the AI). It is probably me doing something wrong, but I can't find anything.

EDIT: Here's the full code, the mechanics function is the main part:
EDIT2: Fixed the constructor

```<code>package Packet;
import java.util.*;
import java.util.Scanner;

public class Logic {

public static class TicTacToe{

    private int[] currentBoard = new int[9];
    private int[] availableSpots = new int [9];

    private int emptySpace = 0;
    private int playerAI = 1;
    private int playerHuman = 2;

    void TicTacToe(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }

    private int movesNumber(){
        int counter = 0;
        for (int i = 0; i < 9; i++){
            if (this.currentBoard[i] == this.emptySpace){
                counter++;
            }
        }
        return counter;
    }

    private boolean win(int[] board,int player){
        if (
        (board[0] == player && board[1] == player && board[2] == player) ||
        (board[3] == player && board[4] == player && board[5] == player) ||
        (board[6] == player && board[7] == player && board[8] == player) ||
        (board[0] == player && board[3] == player && board[6] == player) ||
        (board[1] == player && board[4] == player && board[7] == player) ||
        (board[2] == player && board[5] == player && board[8] == player) ||
        (board[0] == player && board[4] == player && board[8] == player) ||
        (board[2] == player && board[4] == player && board[6] == player) ){
            return true;
        }
        else{
            return false;
        }
    }

    private int mechanics(int[] newBoard, int player){
        if (win(newBoard,this.playerHuman)){
            return -10;
        }
        else if (win(newBoard, this.playerAI)){
            return +10;
        }
        else if (this.movesNumber() == 0){
            return 0;
        }

        ArrayList<Integer> moves = new ArrayList<Integer>();
        ArrayList<Integer> scores = new ArrayList<Integer>();

        for (int i = 0; i < this.movesNumber(); i++){
            int[] possibleBoard = new int[9];
            possibleBoard = newBoard;

            int availableSpotNumber = i;

            int j = i;

            while (this.availableSpots[j] == 9){
                availableSpotNumber++;
                j++;
            }

            possibleBoard[availableSpotNumber] = player;

            if (player == this.playerAI){
                scores.add(this.mechanics(possibleBoard, this.playerHuman));
            }
            else{
                scores.add(this.mechanics(possibleBoard, this.playerAI));
            }
            moves.add(availableSpotNumber);

            possibleBoard[availableSpotNumber] = this.emptySpace;
        }

        int bestMove = 0;

        if (player == this.playerAI){
            int bestScore = -10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) > bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        else {
            int bestScore = 10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) < bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        return moves.get(bestMove);
    }

    public void printTable(){
        System.out.println(this.currentBoard[0] + " | " + this.currentBoard[1] + " | " + this.currentBoard[2]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[3] + " | " + this.currentBoard[4] + " | " + this.currentBoard[5]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[6] + " | " + this.currentBoard[7] + " | " + this.currentBoard[8]);
        System.out.println();
    }

    private void fillTable(int position,int player){
        this.currentBoard[position] = player;
        this.availableSpots[position] = 9;
    }

    public void startGame(){
        while(true){
            this.printTable();
            Scanner ulaz = new Scanner(System.in);
            fillTable(ulaz.nextInt(), this.playerHuman);
            this.printTable();
            fillTable(this.mechanics(this.currentBoard, this.playerAI), this.playerAI);
            ulaz.close();
        }
    }

    public void resetGame(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }
}

public static void main(String[] args){
    TicTacToe game = new TicTacToe();
    game.startGame();
}
}
</code>```

Also, here's the exact errors I get:

```<code>Exception in thread "main" java.lang.StackOverflowError
    at Packet.Logic$TicTacToe.mechanics(Logic.java:54)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
</code>```

After this part, these parts appear a bunch of times (at least 50)

```<code>at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
</code>```

Line 54:

```<code>if (win(newBoard,this.playerHuman)){
</code>```

Line 84:

```<code>scores.add(this.mechanics(possibleBoard, this.playerHuman));
</code>```

Line 87:

```<code>scores.add(this.mechanics(possibleBoard, this.playerAI));
</code>```

答:
This might or might not be a code issue, as Java is not a fully functional language with it comes to recursion, you might want to see this answer: Does Java 8 have tail call optimization?

Basically, a language that allows for unlimited-depth recursion has to have tail recursion optimization. With tail call optimization, if the return value is the result of exactly the same function with different parameters, the stack will get replaced instead of the new call being added to the stack.

If a language does not have tail call optimization, then you're limited by stack size in how deep your recursion goes, even if the recursive calls have correct termination conditions (note: I haven't analyzed the code in depth, so obviously there might be a problem in the recursive logic itself). If you want to tweak the stack size, use the -Xss Java runtime parameter. Generally, increasing the stack size is a good heuristic (although not a fool-proof method) of checking whether the fault is with the language or with your algorithm.

Title: Stack Overflow with recursion in Java

Body:
I'm trying to write an AI that never loses at Tic Tac Toe, and I want to use the minimax algorithm to do so. However, when I try to run the program, a stack overflow appears and I can't seem to find what is the error. Could you take a look and tell me what I'm doing wrong? It doesn't go as deep in the recursion I believe, since it should only go through all the possible game outcomes, which go up to 8 moves (since the player is first to play, not the AI). It is probably me doing something wrong, but I can't find anything.

EDIT: Here's the full code, the mechanics function is the main part:
EDIT2: Fixed the constructor

package Packet;
import java.util.*;
import java.util.Scanner;

public class Logic {

public static class TicTacToe{

    private int[] currentBoard = new int[9];
    private int[] availableSpots = new int [9];

    private int emptySpace = 0;
    private int playerAI = 1;
    private int playerHuman = 2;

    void TicTacToe(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }

    private int movesNumber(){
        int counter = 0;
        for (int i = 0; i < 9; i++){
            if (this.currentBoard[i] == this.emptySpace){
                counter++;
            }
        }
        return counter;
    }

    private boolean win(int[] board,int player){
        if (
        (board[0] == player && board[1] == player && board[2] == player) ||
        (board[3] == player && board[4] == player && board[5] == player) ||
        (board[6] == player && board[7] == player && board[8] == player) ||
        (board[0] == player && board[3] == player && board[6] == player) ||
        (board[1] == player && board[4] == player && board[7] == player) ||
        (board[2] == player && board[5] == player && board[8] == player) ||
        (board[0] == player && board[4] == player && board[8] == player) ||
        (board[2] == player && board[4] == player && board[6] == player) ){
            return true;
        }
        else{
            return false;
        }
    }

    private int mechanics(int[] newBoard, int player){
        if (win(newBoard,this.playerHuman)){
            return -10;
        }
        else if (win(newBoard, this.playerAI)){
            return +10;
        }
        else if (this.movesNumber() == 0){
            return 0;
        }

        ArrayList<Integer> moves = new ArrayList<Integer>();
        ArrayList<Integer> scores = new ArrayList<Integer>();

        for (int i = 0; i < this.movesNumber(); i++){
            int[] possibleBoard = new int[9];
            possibleBoard = newBoard;

            int availableSpotNumber = i;

            int j = i;

            while (this.availableSpots[j] == 9){
                availableSpotNumber++;
                j++;
            }

            possibleBoard[availableSpotNumber] = player;

            if (player == this.playerAI){
                scores.add(this.mechanics(possibleBoard, this.playerHuman));
            }
            else{
                scores.add(this.mechanics(possibleBoard, this.playerAI));
            }
            moves.add(availableSpotNumber);

            possibleBoard[availableSpotNumber] = this.emptySpace;
        }

        int bestMove = 0;

        if (player == this.playerAI){
            int bestScore = -10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) > bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        else {
            int bestScore = 10000;
            for (int i = 0; i < moves.size(); i++){
                if (scores.get(i) < bestScore){
                    bestScore = scores.get(i);
                    bestMove = i;
                }
            }
        }
        return moves.get(bestMove);
    }

    public void printTable(){
        System.out.println(this.currentBoard[0] + " | " + this.currentBoard[1] + " | " + this.currentBoard[2]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[3] + " | " + this.currentBoard[4] + " | " + this.currentBoard[5]);
        System.out.println("-   -   -");
        System.out.println(this.currentBoard[6] + " | " + this.currentBoard[7] + " | " + this.currentBoard[8]);
        System.out.println();
    }

    private void fillTable(int position,int player){
        this.currentBoard[position] = player;
        this.availableSpots[position] = 9;
    }

    public void startGame(){
        while(true){
            this.printTable();
            Scanner ulaz = new Scanner(System.in);
            fillTable(ulaz.nextInt(), this.playerHuman);
            this.printTable();
            fillTable(this.mechanics(this.currentBoard, this.playerAI), this.playerAI);
            ulaz.close();
        }
    }

    public void resetGame(){
        for (int i = 0; i < 9; i++){
            this.currentBoard[i] = this.emptySpace;
        }
        for (int i = 0; i < 9; i++){
            this.availableSpots[i] = i;
        }
    }
}

public static void main(String[] args){
    TicTacToe game = new TicTacToe();
    game.startGame();
}
}

Also, here's the exact errors I get:

Exception in thread "main" java.lang.StackOverflowError
    at Packet.Logic$TicTacToe.mechanics(Logic.java:54)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
    at Packet.Logic$TicTacToe.mechanics(Logic.java:87)

After this part, these parts appear a bunch of times (at least 50)

at Packet.Logic$TicTacToe.mechanics(Logic.java:84)
at Packet.Logic$TicTacToe.mechanics(Logic.java:87)

Line 54:

if (win(newBoard,this.playerHuman)){

Line 84:

scores.add(this.mechanics(possibleBoard, this.playerHuman));

Line 87:

scores.add(this.mechanics(possibleBoard, this.playerAI));


问:
MongoJS: MongoError: failed to connect to server with correct credentials
I am using this plugin: https://github.com/mafintosh/mongojs .

I used to log in via Node.js without credential successfuly:

```<code>var db = mongojs("dbname", []);
</code>```

Later on I have shut down the Mongo and restarted it but this time it was with the command: mongod --auth.
I already had a user roled to the admin database.

Then I have tried to log in again via Node.js, but this time with the user credentials:

```<code>var db = mongojs("username:password@mydomain.com:8080/dbname", []);
</code>```

And I have also tried with a different syntax:

```<code>var db = mongojs("username:password@mydomain.com:271017/dbname", []);
</code>```

And I have also tried:

```<code>var db = mongojs("username:password@dbname", []);
</code>```

As you can see, I have tried lots of syntax methods but nothing did the trick.

I have to mention, that the credentials I used are just fine, I have just logged successfuly via Robo3T (Robomongo) and Mongo Compass with the same details.

I have also tried to revoke the user from admin and put it specifically on dbname but it did not work.

My question:

What is the correct way in order to login with credentials from Node.js?
Please provide a solution based on the library I used and provided above from GitHub.
(If you have a better and more efficient way I will be glad to hear in addition).

A semi question popped up:

I have noticed that when i oblige Mongo to ask for a user in order to continue work with the database, I receive an error in Terminal / SSH:

```<code>Error: not authorized on <dbname> to execute command { usersInfo: 1.0 } at src/mongo/shell/db.js:1363
</code>```

The above error appears when trying to do the same thing via Terminal on my own Mac and either via SSH on my remote VPS.

I put the details how correct as I can, I hope it is clear enough!

Thanks!

答:
Found it!

I have just needed this:

```<code>var db = mongojs("mongodb://MYUSERNAME:MYPASSWORD@localhost:27017/DBNAME", []);
</code>```

Just replace the capital letters with the credentials.

Really, I have searched for it for 3 hours or more.

Body:
I am using this plugin: https://github.com/mafintosh/mongojs .

I used to log in via Node.js without credential successfuly:

var db = mongojs("dbname", []);

Later on I have shut down the Mongo and restarted it but this time it was with the command: mongod --auth.
I already had a user roled to the admin database.

Then I have tried to log in again via Node.js, but this time with the user credentials:

var db = mongojs("username:password@mydomain.com:8080/dbname", []);

And I have also tried with a different syntax:

var db = mongojs("username:password@mydomain.com:271017/dbname", []);

And I have also tried:

var db = mongojs("username:password@dbname", []);

As you can see, I have tried lots of syntax methods but nothing did the trick.

I have to mention, that the credentials I used are just fine, I have just logged successfuly via Robo3T (Robomongo) and Mongo Compass with the same details.

I have also tried to revoke the user from admin and put it specifically on dbname but it did not work.

My question:

What is the correct way in order to login with credentials from Node.js?
Please provide a solution based on the library I used and provided above from GitHub.
(If you have a better and more efficient way I will be glad to hear in addition).

A semi question popped up:

I have noticed that when i oblige Mongo to ask for a user in order to continue work with the database, I receive an error in Terminal / SSH:

Error: not authorized on <dbname> to execute command { usersInfo: 1.0 } at src/mongo/shell/db.js:1363

The above error appears when trying to do the same thing via Terminal on my own Mac and either via SSH on my remote VPS.

I put the details how correct as I can, I hope it is clear enough!

Thanks!

Body:
Found it!

I have just needed this:

var db = mongojs("mongodb://MYUSERNAME:MYPASSWORD@localhost:27017/DBNAME", []);

Just replace the capital letters with the credentials.

Really, I have searched for it for 3 hours or more.


问:
I need some help here with SQL Sum function group by dates and group
I have a table called Table1

```
CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5
```

If I wanted to have a result like this

```
Year | Month |GroupHours| GroupHourTotal
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5
```

I tried this but I am getting incorrect results when the dates are not in the same month.
Any ideas?

```select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc
```

答:
You have a dependent field, Group, which needs to be broken into a separate table. Once you do that, it's a piece of cake:

SELECT Year, Month, GroupTitle,
  SUM(HoursAttended) As HoursAttended
  From Cases C JOIN Groups G ON
  C.GroupId = G.Id GROUP BY Year, Month,
  GroupTitle ORDER BY year desc

Replace "Group" with "GroupId", make it a foreign key to a Groups table, and Bob's your uncle.

Body:
I have a table called Table1

CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5

If I wanted to have a result like this

Year | Month |GroupHours| GroupHourTotal
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5

I tried this but I am getting incorrect results when the dates are not in the same month.
Any ideas?

select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc


问:
How to populate a class to a grid
I have a class InfoField containing members of various types.  I want to bind an ObservableCollection<InfoField> property to some sort of WPF controller.

The class members are listed horizontally and all collection elements are listed vertically.

Both columns and rows have headers.

I can apply different data templates for the various data types.

I can press the column headers (e.g. ShowRpm) to select all the checkboxes under it.

I've been testing with ListView, but I'm not sure that's the right way to go.  From what I can see, I'll have trouble getting points two and four to work using ListView.  Anybody got a good idea on which control to use for this?

```<code>          ShowRpm    ShowCurrent  ShowTemperature  Direction
Motor1   (checkbox)  (checkbox)   (checkbox)       (combobox)
Motor2   (checkbox)  (checkbox)   (checkbox)       (combobox)
Motor3   (checkbox)  (checkbox)   (checkbox)       (combobox)
 ...
MotorN   (checkbox)  (checkbox)   (checkbox)       (combobox)
</code>```

C#:

```<code>public class InfoField {
    public bool ShowRpm { get; set; }
    public bool ShowCurrent { get; set; }
    public bool ShowTemperature { get; set; }
    public Direction Direction { get; set; }
}

public enum Direction {
    Horizontal,
    Vertical
}
</code>```

答:
I would suggest you use a DataGrid. With some customization you should be able to statisy all your options. This is a starting point you can use

```<code>//Collection for the datagrid
public ObservableCollection<InfoField> infoFieldData;

public MainWindow()
{
    InitializeComponent();

    infoFieldData = new ObservableCollection<InfoField>();

    InfoField info1 = new InfoField();
    InfoField info2 = new InfoField();

    infoFieldData.Add(info1);
    infoFieldData.Add(info2);

    dataGrid.ItemsSource = infoFieldData;
    dataGrid.Items.Refresh();
}

public class InfoField
{
    public bool ShowRpm { get; set; }
    public bool ShowCurrent { get; set; }
    public bool ShowTemperature { get; set; }
    public Direction Direction { get; set; }
}

public enum Direction
{
    Horizontal,
    Vertical
}
</code>```

The DataGrid XAML

```<code><DataGrid x:Name="dataGrid" HorizontalAlignment="Left" VerticalAlignment="Top" CanUserAddRows="False"/>
</code>```

For point 2 of having row headers there's this question DataGrid Row Header WPF

For the point 4 there's this How do I capture “Click” events on a DataGrid column headers

Title: How to populate a class to a grid

Body:
I have a class InfoField containing members of various types.  I want to bind an ObservableCollection<InfoField> property to some sort of WPF controller.

The class members are listed horizontally and all collection elements are listed vertically.

Both columns and rows have headers.

I can apply different data templates for the various data types.

I can press the column headers (e.g. ShowRpm) to select all the checkboxes under it.

I've been testing with ListView, but I'm not sure that's the right way to go.  From what I can see, I'll have trouble getting points two and four to work using ListView.  Anybody got a good idea on which control to use for this?

          ShowRpm    ShowCurrent  ShowTemperature  Direction
Motor1   (checkbox)  (checkbox)   (checkbox)       (combobox)
Motor2   (checkbox)  (checkbox)   (checkbox)       (combobox)
Motor3   (checkbox)  (checkbox)   (checkbox)       (combobox)
 ...
MotorN   (checkbox)  (checkbox)   (checkbox)       (combobox)

C#:

public class InfoField {
    public bool ShowRpm { get; set; }
    public bool ShowCurrent { get; set; }
    public bool ShowTemperature { get; set; }
    public Direction Direction { get; set; }
}

public enum Direction {
    Horizontal,
    Vertical
}

Body:
I would suggest you use a DataGrid. With some customization you should be able to statisy all your options. This is a starting point you can use

//Collection for the datagrid
public ObservableCollection<InfoField> infoFieldData;

public MainWindow()
{
    InitializeComponent();

    infoFieldData = new ObservableCollection<InfoField>();

    InfoField info1 = new InfoField();
    InfoField info2 = new InfoField();

    infoFieldData.Add(info1);
    infoFieldData.Add(info2);

    dataGrid.ItemsSource = infoFieldData;
    dataGrid.Items.Refresh();
}

public class InfoField
{
    public bool ShowRpm { get; set; }
    public bool ShowCurrent { get; set; }
    public bool ShowTemperature { get; set; }
    public Direction Direction { get; set; }
}

public enum Direction
{
    Horizontal,
    Vertical
}

The DataGrid XAML

<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" VerticalAlignment="Top" CanUserAddRows="False"/>

For point 2 of having row headers there's this question DataGrid Row Header WPF

For the point 4 there's this How do I capture “Click” events on a DataGrid column headers


问:
How to give a password to a zip file on Mac OS X
How can I give a password to a zip file on Mac OS X without downloading any additional program?</p>

答:
I found the solution.

Go to Terminal and type

zip -er (zipfile's name).zip (File path)

Enter password: (your password)

Verify password: (type it again)

press enter. That's it. It will be saved to your main folder. You have a passworded zip file now.

ContentLicense: CC BY-SA 4.0


问:
How to process rows from SQL query with MRJob
I am having hard time figuring out how MRJob works. I am trying to make an sql query and yield its rows, and in the documentation there is no such thing explained in details.

My code so far:

```<code># To be able to give db file as option.
def configure_options(self):
    super(MyClassName, self).configure_options()
    self.add_file_option('--database')

def mapper_init(self):
    # Making sqlite3 database available to mapper.
    self.sqlite_conn = sqlite3.connect(self.options.database)
    self.command= '''
        SELECT id
        FROM names
        '''

def mapper(self,_,val):
    yield self.sqlite_conn.execute(self.command), 1
</code>```

And in console I write

```<code>python myfile.py text.txt --database=mydb.db
</code>```

Where text.txt is an empty dummy file so the script will not ask for std input.

I am expecting the output to be:

```<code>id1, 1
id2, 1
</code>```

But now there is no output. What am I missing?

答:
I found the solution myself, in case someone needs it later. In this example, the database path is given as an option in command line.

```<code>def configure_options(self):
    super(MyClassName, self).configure_options()
    self.add_file_option('--database')

def mapper_init(self):
    # make sqlite3 database available to mapper
    self.sqlite_conn = sqlite3.connect(self.options.database)
    self.command = '''
        SELECT id
        FROM table
        '''

def mapper(self,_,val):
    queryResult = self.sqlite_conn.execute(self.command)
    while 1:
        row = queryResult.fetchone()
        if row == None:
            break
        yield row[0], 1
</code>```

Executing from command line:

```<code>python myfilename.py dummy.txt --database=mydatabase.db
</code>```

Note that when you add a dummy text file, it should contain only one row, since the mapper will run as many times as many rows there are in the text file.

Body:
I am having hard time figuring out how MRJob works. I am trying to make an sql query and yield its rows, and in the documentation there is no such thing explained in details.

My code so far:

# To be able to give db file as option.
def configure_options(self):
    super(MyClassName, self).configure_options()
    self.add_file_option('--database')

def mapper_init(self):
    # Making sqlite3 database available to mapper.
    self.sqlite_conn = sqlite3.connect(self.options.database)
    self.command= '''
        SELECT id
        FROM names
        '''

def mapper(self,_,val):
    yield self.sqlite_conn.execute(self.command), 1

And in console I write

python myfile.py text.txt --database=mydb.db

Where text.txt is an empty dummy file so the script will not ask for std input.

I am expecting the output to be:

id1, 1
id2, 1

But now there is no output. What am I missing?

Body:
I found the solution myself, in case someone needs it later. In this example, the database path is given as an option in command line.

def configure_options(self):
    super(MyClassName, self).configure_options()
    self.add_file_option('--database')

def mapper_init(self):
    # make sqlite3 database available to mapper
    self.sqlite_conn = sqlite3.connect(self.options.database)
    self.command = '''
        SELECT id
        FROM table
        '''

def mapper(self,_,val):
    queryResult = self.sqlite_conn.execute(self.command)
    while 1:
        row = queryResult.fetchone()
        if row == None:
            break
        yield row[0], 1

Executing from command line:

python myfilename.py dummy.txt --database=mydatabase.db

Note that when you add a dummy text file, it should contain only one row, since the mapper will run as many times as many rows there are in the text file.


问:
Detect datatable date field and force date format in EPPlus export
I have a button on my page that when clicked exports data from a gridview to excel.

```<code>protected void btExport_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Charset = "";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=Output.xlsx");

    DataTable dt= gvOutput.DataSource as DataTable;

    ExcelPackage pck = new ExcelPackage();
    using(pck)
    {
      ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Sheet1");
      wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);
      wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();

      Response.BinaryWrite(pck.GetAsByteArray());

    }

    Response.Flush();
    Response.End();
}
</code>```

This is working fine using the above code, however date fields are formatted as integers. I understand specific cells can be forced to have a certain format, but my issue is that the date columns will change as the dataset for the gridview is dynamic.

I need a way to identify on the fly which column is a date and to force the format of that column to be a date time.

I imagine it will involve an IF statement like this but I haven't got a clue what to put in it or where to put it!

```<code>if (dt.Columns[x].DataType == typeof(DateTime))
{
    //do something
}
</code>```

Any ideas/help is greatly appreciated.

答:
Fully corrected (and tested) code:</p>

```<code>        int colNumber = 0;

        foreach (DataColumn col in DataToExport.Columns)
        {
            colNumber++;
            if (col.DataType == typeof(DateTime))
            {
                wsDt.Column(colNumber).Style.Numberformat.Format = "MM/dd/yyyy hh:mm:ss AM/PM";
            }
        }
</code>```

Body:
I have a button on my page that when clicked exports data from a gridview to excel.

protected void btExport_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Charset = "";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=Output.xlsx");

    DataTable dt= gvOutput.DataSource as DataTable;

    ExcelPackage pck = new ExcelPackage();
    using(pck)
    {
      ExcelWorksheet wsDt = pck.Workbook.Worksheets.Add("Sheet1");
      wsDt.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.None);
      wsDt.Cells[wsDt.Dimension.Address].AutoFitColumns();

      Response.BinaryWrite(pck.GetAsByteArray());

    }

    Response.Flush();
    Response.End();
}

This is working fine using the above code, however date fields are formatted as integers. I understand specific cells can be forced to have a certain format, but my issue is that the date columns will change as the dataset for the gridview is dynamic.

I need a way to identify on the fly which column is a date and to force the format of that column to be a date time.

I imagine it will involve an IF statement like this but I haven't got a clue what to put in it or where to put it!

if (dt.Columns[x].DataType == typeof(DateTime))
{
    //do something
}

Any ideas/help is greatly appreciated.

Body:
Fully corrected (and tested) code:

        int colNumber = 0;

        foreach (DataColumn col in DataToExport.Columns)
        {
            colNumber++;
            if (col.DataType == typeof(DateTime))
            {
                wsDt.Column(colNumber).Style.Numberformat.Format = "MM/dd/yyyy hh:mm:ss AM/PM";
            }
        }


问:
to apply word wrap for the long dynamic text
I am working on angularjs application with jsPDF API to export the content to the PDF file. I have a issue when the text is long to show in the PDF, when the text is long complete sentence is not shown in the generated PDF as seen in the demo link below. I want to apply word wrap so that all the content is displayed in the PDF file.

Check the online demo here : https://plnkr.co/edit/w7fZsdFbbRYctK5tWv5u?p=preview

Code demo:

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

 app.controller("myController", ["$scope",
   function($scope) {

   $scope.export = function() {

       // var pdf = new jsPDF('landscape');
       var pdf = new jsPDF('p','pt','a4');
        var pdfName = 'test.pdf';

        var options = {   pagesplit: true};

        var $divs = $('.myDivClass')
        var totalDiv = $divs.length -1;
        var currentRecursion=0;

        function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
            //Once we have done all the divs save the pdf
            if(currentRecursion==totalRecursions){
                pdf.save(pdfName);
            }else{
                currentRecursion++;
                pdf.addPage();
                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                });
            }
        }

        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
            recursiveAddHtmlAndSave(currentRecursion, totalDiv);
        });
    }
   }
 ]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html ng-app="app">

<head>
<link data-require="bootstrap-css@3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.33/vfs_fonts.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
</head>

<body>
  <div ng-controller="myController">
        <button ng-click="export()">Export</button>

   <div class="myDivClass" style="background-color:white">

The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly)

  </div></div>
</body>

</html></code>```

I have checked the API, and there is splitTextToSize(..) as shown here Word wrap in generated PDF (using jsPDF)? but confused to apply the same in my existing code, as if you see my js code shown above $scope.export i'm iterating the div's to get the dynamic data and then called  pdf.save(pdfName). Can anyone provide the solution, Online demo link is also shared.

PS:I may have text, images,and any other html tags in my div(myDivClass).

答:
Well I got a quick workaround for your solution , we can set a width of the page and then the long text gets printed inside the pdf and no content breaks out of the pdf , just update your options in the script.js to this :

```<code>var options = {   pagesplit: true,'width': 550}
</code>```

and this will do the work for you

Body:
I am working on angularjs application with jsPDF API to export the content to the PDF file. I have a issue when the text is long to show in the PDF, when the text is long complete sentence is not shown in the generated PDF as seen in the demo link below. I want to apply word wrap so that all the content is displayed in the PDF file.

Check the online demo here : https://plnkr.co/edit/w7fZsdFbbRYctK5tWv5u?p=preview

Code demo:

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

 app.controller("myController", ["$scope",
   function($scope) {

   $scope.export = function() {

       // var pdf = new jsPDF('landscape');
       var pdf = new jsPDF('p','pt','a4');
        var pdfName = 'test.pdf';

        var options = {   pagesplit: true};

        var $divs = $('.myDivClass')
        var totalDiv = $divs.length -1;
        var currentRecursion=0;

        function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
            //Once we have done all the divs save the pdf
            if(currentRecursion==totalRecursions){
                pdf.save(pdfName);
            }else{
                currentRecursion++;
                pdf.addPage();
                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                });
            }
        }

        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
            recursiveAddHtmlAndSave(currentRecursion, totalDiv);
        });
    }
   }
 ]);

<!doctype html>

<link data-require="bootstrap-css@3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />

        <button ng-click="export()">Export</button>

The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly)

I have checked the API, and there is splitTextToSize(..) as shown here Word wrap in generated PDF (using jsPDF)? but confused to apply the same in my existing code, as if you see my js code shown above $scope.export i'm iterating the div's to get the dynamic data and then called  pdf.save(pdfName). Can anyone provide the solution, Online demo link is also shared.

PS:I may have text, images,and any other html tags in my div(myDivClass).

Body:
Well I got a quick workaround for your solution , we can set a width of the page and then the long text gets printed inside the pdf and no content breaks out of the pdf , just update your options in the script.js to this :

var options = {   pagesplit: true,'width': 550}

and this will do the work for you


问:
VS Code not detecting Python3 interpreter on MacOS
I just upgrade python3 to 3.6 (using homebrew) and now VS Code doesn't seem to be aware of it. When I try to select my Python interpreter I see 2.7.9 and 2.7.10 (in /usr/bin and /usr/local/bin respectively) but I do not see 3.6.3 (/usr/local/bin/python3).

It's certainly in my path, and I'm aware that I can update settings.json manually, but I use both Python 2 and 3 for various projects and making them available via the interpreter switcher would be incredibly useful. Any ideas why Code isn't autodetecting python3? Or is there a way for me to force-add it to the list?

答:
Figured it out. Something I clearly installed had modified by .bash_profile to include the following:

```<code># Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH
</code>```

I commented that out, restarted Code, and now I can see all my Python interpreters listed (including 3.6.3).

Body:
Figured it out. Something I clearly installed had modified by .bash_profile to include the following:

# Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH

I commented that out, restarted Code, and now I can see all my Python interpreters listed (including 3.6.3).


问:
How to use a Foreach loop in PHP/Blade for Laravel?
Here is a quick question:
Is there any way to optimise this code with a foreach loop or something like this?

```<code>@if(isset($tags[0]))
    <span class="label label-primary">{{ $tags[0] }}</span>
@endif
@if(isset($tags[1]))
    <span class="label label-primary">{{ $tags[1] }}</span>
@endif
@if(isset($tags[2]))
    <span class="label label-primary">{{ $tags[2] }}</span>
@endif
@if(isset($tags[3]))
    <span class="label label-primary">{{ $tags[3] }}</span>
@endif
@if(isset($tags[4]))
    <span class="label label-primary">{{ $tags[4] }}</span>
@endif
@if(isset($tags[5]))
    <span class="label label-primary">{{ $tags[5] }}</span>
@endif
@if(isset($tags[6]))
    <span class="label label-primary">{{ $tags[6] }}</span>
@endif
@if(isset($tags[7]))
    <span class="label label-primary">{{ $tags[7] }}</span>
@endif
@if(isset($tags[8]))
    <span class="label label-primary">{{ $tags[8] }}</span>
@endif
@if(isset($tags[9]))
    <span class="label label-primary">{{ $tags[9] }}</span>
@endif
</code>```

Thank you and have a nice day/night !

答:
```<code>@foreach ($tags as $data)
<span class="label label-primary">{{$data->property }}</span>
@endforeach
</code>```

you can also use the for else in blade just see the laravel docs
https://laravel.com/docs/5.5/blade

Body:
Here is a quick question:
Is there any way to optimise this code with a foreach loop or something like this?

@if(isset($tags[0]))
    {{ $tags[0] }}
@endif
@if(isset($tags[1]))
    {{ $tags[1] }}
@endif
@if(isset($tags[2]))
    {{ $tags[2] }}
@endif
@if(isset($tags[3]))
    {{ $tags[3] }}
@endif
@if(isset($tags[4]))
    {{ $tags[4] }}
@endif
@if(isset($tags[5]))
    {{ $tags[5] }}
@endif
@if(isset($tags[6]))
    {{ $tags[6] }}
@endif
@if(isset($tags[7]))
    {{ $tags[7] }}
@endif
@if(isset($tags[8]))
    {{ $tags[8] }}
@endif
@if(isset($tags[9]))
    {{ $tags[9] }}
@endif

Thank you and have a nice day/night !

Body:
@foreach ($tags as $data)
<span class="label label-primary">{{$data->property }}</span>
@endforeach

you can also use the for else in blade just see the laravel docs
https://laravel.com/docs/5.5/blade


问:
How to retain cookies for xmlrpc.client in Python 3?
The default Python xmlrpc.client.Transport (can be used with xmlrpc.client.ServerProxy) does not retain cookies, which are sometimes needed for cookie based logins.

For example, the following proxy, when used with the TapaTalk API (for which the login method uses cookies for authentication), will give a permission error when trying to modify posts.

```<code>proxy = xmlrpc.client.ServerProxy(URL, xmlrpc.client.Transport())
</code>```

There are some solutions for Python 2 on the net, but they aren't compatible with Python 3.

How can I use a Transport that retains cookies?

答:
Existing answer from GermainZ works only for HTTP. After a lot of time fighting with it, there is HTTPS adaptation. Note the context option which is crucial.

```<code>class CookiesTransport(xmlrpc.client.SafeTransport):
    """A SafeTransport (HTTPS) subclass that retains cookies over its lifetime."""

    # Note context option - it's required for success
    def __init__(self, context=None):
        super().__init__(context=context)
        self._cookies = []

    def send_headers(self, connection, headers):
        if self._cookies:
            connection.putheader("Cookie", "; ".join(self._cookies))
        super().send_headers(connection, headers)

    def parse_response(self, response):
        # This check is required if in some responses we receive no cookies at all
        if response.msg.get_all("Set-Cookie"):
            for header in response.msg.get_all("Set-Cookie"):
                cookie = header.split(";", 1)[0]
                self._cookies.append(cookie)
        return super().parse_response(response)
</code>```

The reason for it is that ServerProxy doesn't respect context option related to transport, if transport is specified, so we need to use it directly in Transport constructor.

Usage:

```<code>import xmlrpc.client
import ssl

transport = CookiesTransport(context=ssl._create_unverified_context())
# Note the closing slash in address as well, very important
server = xmlrpc.client.ServerProxy("https://<api_link>/", transport=transport)

# do stuff with server
server.myApiFunc({'param1': 'x', 'param2': 'y'})
</code>```

Body:
The default Python xmlrpc.client.Transport (can be used with xmlrpc.client.ServerProxy) does not retain cookies, which are sometimes needed for cookie based logins.

For example, the following proxy, when used with the TapaTalk API (for which the login method uses cookies for authentication), will give a permission error when trying to modify posts.

proxy = xmlrpc.client.ServerProxy(URL, xmlrpc.client.Transport())

There are some solutions for Python 2 on the net, but they aren't compatible with Python 3.

How can I use a Transport that retains cookies?

Body:
Existing answer from GermainZ works only for HTTP. After a lot of time fighting with it, there is HTTPS adaptation. Note the context option which is crucial.

class CookiesTransport(xmlrpc.client.SafeTransport):
    """A SafeTransport (HTTPS) subclass that retains cookies over its lifetime."""

    # Note context option - it's required for success
    def __init__(self, context=None):
        super().__init__(context=context)
        self._cookies = []

    def send_headers(self, connection, headers):
        if self._cookies:
            connection.putheader("Cookie", "; ".join(self._cookies))
        super().send_headers(connection, headers)

    def parse_response(self, response):
        # This check is required if in some responses we receive no cookies at all
        if response.msg.get_all("Set-Cookie"):
            for header in response.msg.get_all("Set-Cookie"):
                cookie = header.split(";", 1)[0]
                self._cookies.append(cookie)
        return super().parse_response(response)

The reason for it is that ServerProxy doesn't respect context option related to transport, if transport is specified, so we need to use it directly in Transport constructor.

Usage:

import xmlrpc.client
import ssl

transport = CookiesTransport(context=ssl._create_unverified_context())
# Note the closing slash in address as well, very important
server = xmlrpc.client.ServerProxy("https://<api_link>/", transport=transport)

# do stuff with server
server.myApiFunc({'param1': 'x', 'param2': 'y'})


问:
Spring boot -- Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
Spring Boot

I was trying to running my spring Boot application in intelliJ but getting an Error:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.1.RELEASE)

2016-01-26 23:09:30.883  INFO 3960 --- [           main] com.example.he.ExampleApplication         : Starting ExampleApplication on user with PID 3960 (F:\WORK\Work_Project\Example_Application-master\Example_Application-master\build\classes\main started by user in F:\WORK\Work_Project\Example_Application-master\Example_Application-master)
2016-01-26 23:09:30.892  INFO 3960 --- [           main] com.example.he.ExampleApplication         : No active profile set, falling back to default profiles: default
2016-01-26 23:09:31.042  INFO 3960 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@73d4cc9e: startup date [Tue Jan 26 23:09:31 IST 2016]; root of context hierarchy
2016-01-26 23:09:31.242  WARN 3960 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
2016-01-26 23:09:31.453 ERROR 3960 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.example.he.ExampleApplication.main(ExampleApplication.java:15) [main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) [idea_rt.jar:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:185) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    ... 13 common frames omitted

2016-01-26 23:09:31.456  INFO 3960 ---

Process finished with exit code 1
</code>```

Iam using Gradle.This is my build.gradle file:

```<code>buildscript {
    ext {
        springBootVersion = '1.3.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'

war {
    baseName = 'Example-Application'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.apache.tomcat.embed:tomcat-embed-jasper:8.0.30')
        compile('javax.servlet:servlet-api:2.5')
    compile('javax.servlet:jstl:1.2')
    runtime('mysql:mysql-connector-java')
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.9'
}
</code>```

This is the configuration class:

```<code>package com.example.he.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/city").setViewName("city");
    registry.addViewController("/").setViewName("city");
    registry.addViewController("/userAdd").setViewName("user");
    registry.addViewController("/created").setViewName("created");
    registry.addViewController("/createblog").setViewName("blog");
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/home").setViewName("home");

  }

}
</code>```

And this is my Application class:

```<code>package com.example.he;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
public class ExampleApplication extends SpringBootServletInitializer{

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ExampleApplication.class, args);
    }

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(ExampleApplication.class);
  }

}
</code>```

and also i have tried these annotations as well.

```<code>@ComponentScan
@EnableAutoConfiguration
@Configuration
</code>```

I am new to spring and i don't really understand what these annotations do.I tried following some of these but couldn't fix the issue.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Spring Boot Testing: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

I tried building the application using console(gradle build), build is successful but running the war gives me an error: Unable to start embedded Tomcat . Could someone please help me ?

答:
Adding annotation on main boot application class worked for me.
@EnableAutoConfiguration
public class ExampleApplication{.....</p>

Body:
Spring Boot

I was trying to running my spring Boot application in intelliJ but getting an Error:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.1.RELEASE)

2016-01-26 23:09:30.883  INFO 3960 --- [           main] com.example.he.ExampleApplication         : Starting ExampleApplication on user with PID 3960 (F:\WORK\Work_Project\Example_Application-master\Example_Application-master\build\classes\main started by user in F:\WORK\Work_Project\Example_Application-master\Example_Application-master)
2016-01-26 23:09:30.892  INFO 3960 --- [           main] com.example.he.ExampleApplication         : No active profile set, falling back to default profiles: default
2016-01-26 23:09:31.042  INFO 3960 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@73d4cc9e: startup date [Tue Jan 26 23:09:31 IST 2016]; root of context hierarchy
2016-01-26 23:09:31.242  WARN 3960 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
2016-01-26 23:09:31.453 ERROR 3960 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:764) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:357) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:305) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1124) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1113) [spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at com.example.he.ExampleApplication.main(ExampleApplication.java:15) [main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) [idea_rt.jar:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:185) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:158) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) ~[spring-boot-1.3.1.RELEASE.jar:1.3.1.RELEASE]
    ... 13 common frames omitted

2016-01-26 23:09:31.456  INFO 3960 ---

Process finished with exit code 1

Iam using Gradle.This is my build.gradle file:

buildscript {
    ext {
        springBootVersion = '1.3.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
apply plugin: 'war'

war {
    baseName = 'Example-Application'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.apache.tomcat.embed:tomcat-embed-jasper:8.0.30')
        compile('javax.servlet:servlet-api:2.5')
    compile('javax.servlet:jstl:1.2')
    runtime('mysql:mysql-connector-java')
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.9'
}

This is the configuration class:

package com.example.he.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/city").setViewName("city");
    registry.addViewController("/").setViewName("city");
    registry.addViewController("/userAdd").setViewName("user");
    registry.addViewController("/created").setViewName("created");
    registry.addViewController("/createblog").setViewName("blog");
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/home").setViewName("home");

  }

}

And this is my Application class:

package com.example.he;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
public class ExampleApplication extends SpringBootServletInitializer{

    public static void main(String[] args) throws Exception {
        SpringApplication.run(ExampleApplication.class, args);
    }

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(ExampleApplication.class);
  }

}

and also i have tried these annotations as well.

@ComponentScan
@EnableAutoConfiguration
@Configuration

I am new to spring and i don't really understand what these annotations do.I tried following some of these but couldn't fix the issue.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

Spring Boot Testing: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

I tried building the application using console(gradle build), build is successful but running the war gives me an error: Unable to start embedded Tomcat . Could someone please help me ?


问:
Conditional wont be read in do while statement
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated. </p>

```<code>import java.io.*;
import java.util.*;
public class Prog213c
{
  public static void main(String[] args) {

        Scanner kbReader=new Scanner(System.in);

        do{
            System.out.println( "Enter student number");
            int studentNumber = kbReader.nextInt();
            System.out.println(" Enter credits ");
            int credits = kbReader.nextInt();

            switch (credits)
            {
            case 30:
                System.out.println("Grade Level code = 2");
                break;
            case 29:
                System.out.println("Grade Level code = 1");
                break;
            case 70:
                System.out.println("Grade Level code = 3");
                break;
            case 103:
                System.out.println("Grade Level code = 4");
                break;

            default: System.out.println("invalid number");
            }
            System.out.print("Do again(y/n)");
            String answer = kbReader.next();
        } while (answer == 'y'); // error received here
</code>```

答:
Problem 1:
since answer is a string object, this is not working (answer == 'y');

you can do "y".equals(answer) is you get the nextLine from the scanner

or if you need to work with chars

```<code>char x = kbReader.next().charAt(0);
while (x == 'y');
</code>```

Problem 2:

answer must be declared before the do-while loop...

your final code can look like

```<code>    Scanner kbReader = new Scanner(System.in);
    char answer = 'y';
    do {
        System.out.println("Enter student number");
        int studentNumber = kbReader.nextInt();
        System.out.println(" Enter credits ");
        int credits = kbReader.nextInt();

        switch (credits) {
        case 30:
            System.out.println("Grade Level code = 2");
            break;
        case 29:
            System.out.println("Grade Level code = 1");
            break;
        case 70:
            System.out.println("Grade Level code = 3");
            break;
        case 103:
            System.out.println("Grade Level code = 4");
            break;

        default:
            System.out.println("invalid number");
        }
        System.out.print("Do again(y/n)");
        answer = kbReader.next().charAt(0);
    } while (answer == 'y');
</code>```

Body:
For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.

import java.io.*;
import java.util.*;
public class Prog213c
{
  public static void main(String[] args) {

        Scanner kbReader=new Scanner(System.in);

        do{
            System.out.println( "Enter student number");
            int studentNumber = kbReader.nextInt();
            System.out.println(" Enter credits ");
            int credits = kbReader.nextInt();

            switch (credits)
            {
            case 30:
                System.out.println("Grade Level code = 2");
                break;
            case 29:
                System.out.println("Grade Level code = 1");
                break;
            case 70:
                System.out.println("Grade Level code = 3");
                break;
            case 103:
                System.out.println("Grade Level code = 4");
                break;

            default: System.out.println("invalid number");
            }
            System.out.print("Do again(y/n)");
            String answer = kbReader.next();
        } while (answer == 'y'); // error received here

Body:
Problem 1:
since answer is a string object, this is not working (answer == 'y');

you can do "y".equals(answer) is you get the nextLine from the scanner

or if you need to work with chars

char x = kbReader.next().charAt(0);
while (x == 'y');

Problem 2:

answer must be declared before the do-while loop...

your final code can look like

    Scanner kbReader = new Scanner(System.in);
    char answer = 'y';
    do {
        System.out.println("Enter student number");
        int studentNumber = kbReader.nextInt();
        System.out.println(" Enter credits ");
        int credits = kbReader.nextInt();

        switch (credits) {
        case 30:
            System.out.println("Grade Level code = 2");
            break;
        case 29:
            System.out.println("Grade Level code = 1");
            break;
        case 70:
            System.out.println("Grade Level code = 3");
            break;
        case 103:
            System.out.println("Grade Level code = 4");
            break;

        default:
            System.out.println("invalid number");
        }
        System.out.print("Do again(y/n)");
        answer = kbReader.next().charAt(0);
    } while (answer == 'y');


问:
How to create a custom drop-down using react-select (like stackoverflow)?
Instead of a simple string using label options:

```<code>var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two' }
];
</code>```

I want to use a custom component with complex data to populate each option. The selected tags could still be a value, label pair though.

A perfect example:

答:
Yes, react-select lets you pass in a custom menu component via the menuRenderer prop:

Renders a custom menu with options; accepts the following named parameters: menuRenderer({ focusedOption, focusOption, options, selectValue, valueArray })

More info in react-select's docs.

Body:
Instead of a simple string using label options:

var options = [
  { value: 'one', label: 'One' },
  { value: 'two', label: 'Two' }
];

I want to use a custom component with complex data to populate each option. The selected tags could still be a value, label pair though.

A perfect example:


答:
Single quotes are character literals in Java. So you can't compare a
String with a char directly.

Your answer variable has to be declared before the do-while loop.

you have to use the equals method to compare strings.
answer.equals("y")

Title: Conditional wont be read in do while statement


问:
Avro schema update with two schema in one avro file
I have one avro file with first schema then I updated the schema that appends to the same file. So now I have two schemas in one file. How does avro handle this scenario. Will I have any new fields add in the file or will I loose any data while reading this data. This is a real time streaming application where I am writing the data to hdfs. My upstream system might update the schema but the hdfs writer might be on old schema. So the hdfs avro file will have two schemas until I update the writer to handle the newer schema.

Note - I don't have schema registry and I am creating one avro file per day. So if a schema is updated in the middle of the day, I will have one avro file with two schemas.

答:
Unlike Thrift Avro doesn't save any meta information about the avro schema in the data.

Avro required avro schema to be present at both write and read time.

Assumption is the schema evolution is compatible and hence reading a older schema with a newer version will not lead to exceptions, but can have null values for new field.

Your evolving schema needs to be backward compatible. Avro provides utility to check for schema compatibility.

As your file may have two different version , but at read time you will provide a version hence the data will be de-serialized to the version you provide at read time.


问:
How do I call a custom function in a parent class when panResponder starts moving?
If I have an imported component called <Draggable /> in react-native,

How do I call a custom function in the parent component when onPanResponderGrant decides the gesture has started?

You'll see I'm passing an id of 'A' and 'B' into <Draggable />, and I'd like to be able to call them back out on touch, and display them in the infoBox at the bottom of the main View?

```<code>// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
        };
    }
    render(){
        return (
          <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                      <Text>Draggable Container</Text>
                      <Draggable id='A' />
                      <Draggable id='B' />
                </View>
                <View style={styles.infoBar}>{this.infoBarData()}</View>
          </View>
        );
    }
    infoBarData(){
        if (this.state.dID) {
            return(
                <Text>{this.state.dID}</Text>
            )

        }
    }
}
</code>```

and

```<code>// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated, } from 'react-native';
import styles from './styles';

class Draggable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan : new Animated.ValueXY(),
        };
        this.panResponder = PanResponder.create({
            onStartShouldSetPanResponder    : () => true,
            onPanResponderMove              : Animated.event([null,{
                dx  : this.state.pan.x,
                dy  : this.state.pan.y,
            }]),
            onPanResponderRelease           : () => {
              Animated.spring(this.state.pan,{toValue:{x:0, y:0}}).start();
            }
        });
    }
    render() {
        return (
            <Animated.View
                {...this.panResponder.panHandlers}
                style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
                <Text style={styles.textAlt}>Drag me!</Text>
                <Text style={styles.textNum}>{this.props.id}</Text>
            </Animated.View>
        )
    }
}
export default Draggable;
</code>```

EDIT

I've added the following to the parent class

```<code>// Object
<Draggable
  onPanResponderMove={this.onStopMove}
  onPanResponderRelease={this.onMove}
  id='A' />

// Methods
onMove = (dID) => {
  this.setState({ dID });
}

onStopMove = () => {
  this.setState({ dID: null });
}
</code>```

And I added the following to the Draggable class.

```<code>// Methods
_handleOnPanResponderMove(evt, gestureState) {
    Animated.event([null,{
        // These animate movement on the X/Y axis
        dx  : this.state.pan.x,
        dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
}
</code>```

But when I move the animated event out of the PanResponder.create({})

by doing the following, it loses it's ability to be dragged. I assume this is something to do with

```<code>PanResponder.create({
    ...,
    onPanResponder : this._handleOnPanResponder.bind(this),
    ...,
})
</code>```

Not being returned a value?

EDIT 2

I also tried to add the following, but again, didn't work.

```<code>PanResponder.create({
    ...,
    onPanResponder : (evt ,gesture) => {
        Animated.event([null,{
            // These animate movement on the X/Y axis
            dx  : this.state.pan.x,
            dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
    }
    ...,
})
</code>```

答:
Ok,

So here is the code that works for anybody who may come across this question.

```<code>// App
import React, { Component } from 'react';
import {
    View,
    Text,
} from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
        };
    }
    render(){
        return (
          <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                      <Text>Draggable Container</Text>
                      <Draggable
                        onPanResponderGrant={this.onMove}
                        onPanResponderRelease={this.onStopMove}
                        id='A' />
                      <Draggable
                        onPanResponderGrant={this.onMove}
                        onPanResponderRelease={this.onStopMove}
                        id='B' />
                </View>
                <View style={styles.infoBar}>{this.printInfo()}</View>
          </View>
        );
    }
    onMove = (dID) => {
      this.setState({ dID });
    }

    onStopMove = () => {
      this.setState({ dID: null });
    }
    printInfo(){
      if (this.state.dID) {
        return(
          <Text>{this.state.dID}</Text>
        );
      }
    }
}

// Draggable
import React, { Component } from 'react';
import {
    Text,
    PanResponder,
    Animated,
} from 'react-native';
import styles from './styles';

class Draggable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan                 : new Animated.ValueXY(),
        };
    this.panResponder = PanResponder.create({
        onStartShouldSetPanResponder    : () => true,
        onPanResponderGrant : () => {
          this.props.onPanResponderGrant(this.props.id)
        },
        onPanResponderMove              : Animated.event([null,{
            dx  : this.state.pan.x,
            dy  : this.state.pan.y,
        }]),
        onPanResponderRelease           : () => {
                  Animated.spring(
                    this.state.pan,
                    {toValue:{x:0, y:0}}
                  ).start();
                  this.props.onPanResponderRelease();
              },
    });
    }
    render() {
        return (
            <Animated.View
                {...this.panResponder.panHandlers}
                style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
                <Text style={styles.textAlt}>Drag me!</Text>
                <Text style={styles.textNum}>{this.props.id}</Text>
            </Animated.View>
        )
    }
}
export default Draggable;
</code>```

Body:
If I have an imported component called <Draggable /> in react-native,

How do I call a custom function in the parent component when onPanResponderGrant decides the gesture has started?

You'll see I'm passing an id of 'A' and 'B' into <Draggable />, and I'd like to be able to call them back out on touch, and display them in the infoBox at the bottom of the main View?

// App

import React, { Component } from 'react';
import { View, Text, } from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
        };
    }
    render(){
        return (
          <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                      <Text>Draggable Container</Text>
                      <Draggable id='A' />
                      <Draggable id='B' />
                </View>
                <View style={styles.infoBar}>{this.infoBarData()}</View>
          </View>
        );
    }
    infoBarData(){
        if (this.state.dID) {
            return(
                <Text>{this.state.dID}</Text>
            )

        }
    }
}

and

// Draggable

import React, { Component } from 'react';
import { Text, PanResponder, Animated, } from 'react-native';
import styles from './styles';

class Draggable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan : new Animated.ValueXY(),
        };
        this.panResponder = PanResponder.create({
            onStartShouldSetPanResponder    : () => true,
            onPanResponderMove              : Animated.event([null,{
                dx  : this.state.pan.x,
                dy  : this.state.pan.y,
            }]),
            onPanResponderRelease           : () => {
              Animated.spring(this.state.pan,{toValue:{x:0, y:0}}).start();
            }
        });
    }
    render() {
        return (
            <Animated.View
                {...this.panResponder.panHandlers}
                style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
                <Text style={styles.textAlt}>Drag me!</Text>
                <Text style={styles.textNum}>{this.props.id}</Text>
            </Animated.View>
        )
    }
}
export default Draggable;

EDIT

I've added the following to the parent class

// Object
<Draggable
  onPanResponderMove={this.onStopMove}
  onPanResponderRelease={this.onMove}
  id='A' />

// Methods
onMove = (dID) => {
  this.setState({ dID });
}

onStopMove = () => {
  this.setState({ dID: null });
}

And I added the following to the Draggable class.

// Methods
_handleOnPanResponderMove(evt, gestureState) {
    Animated.event([null,{
        // These animate movement on the X/Y axis
        dx  : this.state.pan.x,
        dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
}

But when I move the animated event out of the PanResponder.create({})

by doing the following, it loses it's ability to be dragged. I assume this is something to do with

PanResponder.create({
    ...,
    onPanResponder : this._handleOnPanResponder.bind(this),
    ...,
})

Not being returned a value?

EDIT 2

I also tried to add the following, but again, didn't work.

PanResponder.create({
    ...,
    onPanResponder : (evt ,gesture) => {
        Animated.event([null,{
            // These animate movement on the X/Y axis
            dx  : this.state.pan.x,
            dy  : this.state.pan.y,
    }]);
    this.props.onPanResponderRelease(this.props.id);
    }
    ...,
})

Body:
Ok,

So here is the code that works for anybody who may come across this question.

// App
import React, { Component } from 'react';
import {
    View,
    Text,
} from 'react-native';
import styles from './cust/styles';
import Draggable from './cust/draggable';

export default class Viewport extends Component {
    constructor(props){
        super(props);
        this.state = {
            dID  : null,
        };
    }
    render(){
        return (
          <View style={styles.mainContainer}>
                <View style={styles.draggableContainer}>
                      <Text>Draggable Container</Text>
                      <Draggable
                        onPanResponderGrant={this.onMove}
                        onPanResponderRelease={this.onStopMove}
                        id='A' />
                      <Draggable
                        onPanResponderGrant={this.onMove}
                        onPanResponderRelease={this.onStopMove}
                        id='B' />
                </View>
                <View style={styles.infoBar}>{this.printInfo()}</View>
          </View>
        );
    }
    onMove = (dID) => {
      this.setState({ dID });
    }

    onStopMove = () => {
      this.setState({ dID: null });
    }
    printInfo(){
      if (this.state.dID) {
        return(
          <Text>{this.state.dID}</Text>
        );
      }
    }
}

// Draggable
import React, { Component } from 'react';
import {
    Text,
    PanResponder,
    Animated,
} from 'react-native';
import styles from './styles';

class Draggable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan                 : new Animated.ValueXY(),
        };
    this.panResponder = PanResponder.create({
        onStartShouldSetPanResponder    : () => true,
        onPanResponderGrant : () => {
          this.props.onPanResponderGrant(this.props.id)
        },
        onPanResponderMove              : Animated.event([null,{
            dx  : this.state.pan.x,
            dy  : this.state.pan.y,
        }]),
        onPanResponderRelease           : () => {
                  Animated.spring(
                    this.state.pan,
                    {toValue:{x:0, y:0}}
                  ).start();
                  this.props.onPanResponderRelease();
              },
    });
    }
    render() {
        return (
            <Animated.View
                {...this.panResponder.panHandlers}
                style={[this.state.pan.getLayout(), styles.circleAlt, styles.position]}>
                <Text style={styles.textAlt}>Drag me!</Text>
                <Text style={styles.textNum}>{this.props.id}</Text>
            </Animated.View>
        )
    }
}
export default Draggable;