问:
Parser in Haskell for Triples
I am currently doing an assignment about Parsing in Haskell, but I am struggling with some of the basics.

Assignment :
I am supposed to create a function which parses a string into a list of Triples.
So that:
A, B, C
  ,E ,D

would result in

```<code>Triples [("A","B","C"), ("A","E","D")]
</code>```

The input string is going to include ;\n as an indication for the beginng of a new Triple. The string is going to end with a dot.
The elements of the Triples can be letters or digits or combination,
e.g. abc, a, 1, abc121.

Therefore,

```<code>"a,b,c;\n d,e;\n f,g;\n h,i."
</code>```

would result in:

```<code>Triples [("a","b","c"),("a","d","e"),("a","f","g"),("a","h","i")]
</code>```

My current solution:

```<code>parseTriplesD :: Parser Triples
parseTriplesD = parseTriples
            >>= \rs -> return (Triples rs)
</code>```

This function is pretty simple and correct. Takes the string and returns a object of the newtype Triples with the List of Triples created by parseTriples.

```<code>parseTriples :: Parser [Triple]
parseTriples = parseTriple
            >>= \r -> ((string ";\n" >> parseTriples >>= \rs -> return (r:rs))
            P.<|>(return[r]))
</code>```

This function needs some work. My idea is that I use another function which creates a Triple with tree Elements of the input string, ignores the /n and recursivly calls it self while adding the created triples to a return list. When this does not work because it can only create one Triple, it returns a list with the Triple.
I somehow need to create the first Triple, and then use first element of this triple as the first element of the other ones.

Question 1
How do I create the first Triple and use the first Elements of the Triple for the other Triples?

```<code>parseTriple :: Parser Triple
parseTriple = P.many (letter<|>digit) >>= \a -> P.char ','
            >> P.many (letter<|>digit)>>= \b -> P.char ','
            >> P.many (letter<|>digit)>>= \c -> return ((a,b,c))
</code>```

This function is pretty simple but I am not sure if its correct.
My idea is that it takes the first couple of characters of the string which are either a letter or a digit, up until the comma  "," , and saves these charcters in a.
It is repeated 3 times, and the creates and returns a Triple with the three elements.

Question 2
How do I take only a few characters (which are either a letter or a digit EDIT: Or A SPACE Character) of the string up until the comma?
Is P.many (letter<|>digit) correct?

What we are given:

The Triples data structue:

```<code>newtype Triples = Triples [Triple] deriving (Show,Eq)
type Triple = (String, String, String)
</code>```

Imports:

```<code>import Test.HUnit (runTestTT,Test(TestLabel,TestList),(~?=))
import qualified Text.Parsec as P (char,runP,noneOf,many,(<|>),eof)
import Text.ParserCombinators.Parsec
import Text.Parsec.String
import Text.Parsec.Char
import Data.Maybe
</code>```

Test cases

```<code>runParsec :: Parser a -> String -> Maybe a
runParsec parser input = case P.runP parser () "" input of
    Left  _ -> Nothing
    Right a -> Just a

-- | Tests the implementations of 'parseScore'.
main :: IO ()
main = do
    testresults <- runTestTT tests
    print testresults

-- | List of tests for 'parseScore'.
tests :: Test
tests = TestLabel "parseScoreTest" (TestList [
    runParsec parseTriplesD "0,1,2;\n2,3."   ~?= Just (Triples [("0","1","2"),("0","2","3")]),
    runParsec parseTriplesD "a,bcde ,23." ~?= Just (Triples [("a","bcde ","23")]),
    runParsec parseTriplesD "a,b,c;\n d,e;\n f,g;\n h,i." ~?= Just (Triples [("a","b","c"),("a","d","e"),("a","f","g"),("a","h","i")]),
    runParsec parseTriplesD "a,bcde23." ~?= Nothing,
    runParsec parseTriplesD "a,b,c;d,e;f,g;h,i." ~?= Nothing,
    runParsec parseTriplesD "a,b,c;\nd;\nf,g;\nh,i." ~?= Nothing
    ])
</code>```

答:
What you could do is:

Parse the first character

Parse a list of pairs

Add the first character to each of the pairs to create triples

Using do notation will make your code more readable.

You can use alphaNum as a shorthand for letter <|> digit.

```<code>parseTriplesD :: Parser Triples
parseTriplesD = Triples <$> parseTriples

parseTriples :: Parser [Triple]
parseTriples = do
    a <- parseString
    char ','
    pairs <- parsePair `sepBy1` string ";\n"
    char '.'
    eof
    return (map (\(b, c) -> (a, b, c)) pairs)

parsePair :: Parser (String, String)
parsePair = do
    first <- parseString
    char ','
    second <- parseString
    return (first, second)

parseString :: Parser String
parseString = many (char ' ') >> many (alphaNum <|> char ' ')
</code>```

Title: Parser in Haskell for Triples

Body:
I am currently doing an assignment about Parsing in Haskell, but I am struggling with some of the basics.

Assignment :
I am supposed to create a function which parses a string into a list of Triples.
So that:
A, B, C
  ,E ,D

would result in

Triples [("A","B","C"), ("A","E","D")]

The input string is going to include ;\n as an indication for the beginng of a new Triple. The string is going to end with a dot.
The elements of the Triples can be letters or digits or combination,
e.g. abc, a, 1, abc121.

Therefore,

"a,b,c;\n d,e;\n f,g;\n h,i."

would result in:

Triples [("a","b","c"),("a","d","e"),("a","f","g"),("a","h","i")]

My current solution:

parseTriplesD :: Parser Triples
parseTriplesD = parseTriples
            >>= \rs -> return (Triples rs)

This function is pretty simple and correct. Takes the string and returns a object of the newtype Triples with the List of Triples created by parseTriples.

parseTriples :: Parser [Triple]
parseTriples = parseTriple
            >>= \r -> ((string ";\n" >> parseTriples >>= \rs -> return (r:rs))
            P.<|>(return[r]))

This function needs some work. My idea is that I use another function which creates a Triple with tree Elements of the input string, ignores the /n and recursivly calls it self while adding the created triples to a return list. When this does not work because it can only create one Triple, it returns a list with the Triple.
I somehow need to create the first Triple, and then use first element of this triple as the first element of the other ones.

Question 1
How do I create the first Triple and use the first Elements of the Triple for the other Triples?

parseTriple :: Parser Triple
parseTriple = P.many (letter<|>digit) >>= \a -> P.char ','
            >> P.many (letter<|>digit)>>= \b -> P.char ','
            >> P.many (letter<|>digit)>>= \c -> return ((a,b,c))

This function is pretty simple but I am not sure if its correct.
My idea is that it takes the first couple of characters of the string which are either a letter or a digit, up until the comma  "," , and saves these charcters in a.
It is repeated 3 times, and the creates and returns a Triple with the three elements.

Question 2
How do I take only a few characters (which are either a letter or a digit EDIT: Or A SPACE Character) of the string up until the comma?
Is P.many (letter<|>digit) correct?

What we are given:

The Triples data structue:

newtype Triples = Triples [Triple] deriving (Show,Eq)
type Triple = (String, String, String)

Imports:

import Test.HUnit (runTestTT,Test(TestLabel,TestList),(~?=))
import qualified Text.Parsec as P (char,runP,noneOf,many,(<|>),eof)
import Text.ParserCombinators.Parsec
import Text.Parsec.String
import Text.Parsec.Char
import Data.Maybe

Test cases

runParsec :: Parser a -> String -> Maybe a
runParsec parser input = case P.runP parser () "" input of
    Left  _ -> Nothing
    Right a -> Just a

-- | Tests the implementations of 'parseScore'.
main :: IO ()
main = do
    testresults <- runTestTT tests
    print testresults

-- | List of tests for 'parseScore'.
tests :: Test
tests = TestLabel "parseScoreTest" (TestList [
    runParsec parseTriplesD "0,1,2;\n2,3."   ~?= Just (Triples [("0","1","2"),("0","2","3")]),
    runParsec parseTriplesD "a,bcde ,23." ~?= Just (Triples [("a","bcde ","23")]),
    runParsec parseTriplesD "a,b,c;\n d,e;\n f,g;\n h,i." ~?= Just (Triples [("a","b","c"),("a","d","e"),("a","f","g"),("a","h","i")]),
    runParsec parseTriplesD "a,bcde23." ~?= Nothing,
    runParsec parseTriplesD "a,b,c;d,e;f,g;h,i." ~?= Nothing,
    runParsec parseTriplesD "a,b,c;\nd;\nf,g;\nh,i." ~?= Nothing
    ])

Body:
What you could do is:

Parse the first character

Parse a list of pairs

Add the first character to each of the pairs to create triples

Using do notation will make your code more readable.

You can use alphaNum as a shorthand for letter <|> digit.

parseTriplesD :: Parser Triples
parseTriplesD = Triples <$> parseTriples

parseTriples :: Parser [Triple]
parseTriples = do
    a <- parseString
    char ','
    pairs <- parsePair `sepBy1` string ";\n"
    char '.'
    eof
    return (map (\(b, c) -> (a, b, c)) pairs)

parsePair :: Parser (String, String)
parsePair = do
    first <- parseString
    char ','
    second <- parseString
    return (first, second)

parseString :: Parser String
parseString = many (char ' ') >> many (alphaNum <|> char ' ')


来源: stackexchange

问:
for loop iterates strange
Good Morning,
I have a problem with for loop, I tried to make multiply progressbars on page and I try to triger them in one action:

```<code>function startProgressbaring(){

var progressArray = [
    progress1 = document.querySelector('.progressbar-1'),
    progress2 = document.querySelector('.progressbar-2'),
    progress3 = document.querySelector('.progressbar-3'),
    progress4 = document.querySelector('.progressbar-4'),
    progress5 = document.querySelector('.progressbar-5'),
    progress6 = document.querySelector('.progressbar-6')
];
var durationArray = [
     progress1_Duration = 90,
     progress2_Duration = 65,
     progress3_Duration = 70,
     progress4_Duration = 55,
     progress5_Duration = 95,
     progress6_Duration = 90
];

var id = setInterval(frame,30);
var width = 1;

        function frame(){
        for(var z=0; z<durationArray.length; z++){

            if(width>durationArray[z]){
                clearInterval(id);
                console.log(durationArray[z]);
            }else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }

        };
</code>```

Console Log with durationArray returns only 55, for example
six progressbars have values between 56 and 60 not the values from durationArray,
no idea whats going wrong, thanks for any advices

答:
The problem is, that you do

```<code>clearInterval(id);
</code>```

if one of the frames reaches its width. That automatically stops the others too. May just stop if all have ended:

```<code>function frame(){
 var running=false;
 for(var z=0; z<durationArray.length; z++){
        if(width>durationArray[z]){
            console.log(durationArray[z]);
        }else {
            running=true;
            width++;
            progressArray[z].style.width = width + '%';
       }
  }
  if(!running) clearInterval(id);
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: for loop iterates strange

Body:
Good Morning,
I have a problem with for loop, I tried to make multiply progressbars on page and I try to triger them in one action:

function startProgressbaring(){

var progressArray = [
    progress1 = document.querySelector('.progressbar-1'),
    progress2 = document.querySelector('.progressbar-2'),
    progress3 = document.querySelector('.progressbar-3'),
    progress4 = document.querySelector('.progressbar-4'),
    progress5 = document.querySelector('.progressbar-5'),
    progress6 = document.querySelector('.progressbar-6')
];
var durationArray = [
     progress1_Duration = 90,
     progress2_Duration = 65,
     progress3_Duration = 70,
     progress4_Duration = 55,
     progress5_Duration = 95,
     progress6_Duration = 90
];

var id = setInterval(frame,30);
var width = 1;

        function frame(){
        for(var z=0; z<durationArray.length; z++){

            if(width>durationArray[z]){
                clearInterval(id);
                console.log(durationArray[z]);
            }else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }

        };

Console Log with durationArray returns only 55, for example
six progressbars have values between 56 and 60 not the values from durationArray,
no idea whats going wrong, thanks for any advices

Body:
The problem is, that you do

clearInterval(id);

if one of the frames reaches its width. That automatically stops the others too. May just stop if all have ended:

function frame(){
 var running=false;
 for(var z=0; z<durationArray.length; z++){
        if(width>durationArray[z]){
            console.log(durationArray[z]);
        }else {
            running=true;
            width++;
            progressArray[z].style.width = width + '%';
       }
  }
  if(!running) clearInterval(id);
};


问:
MongoDB Count Distinct Speed
I'm using the following code in PyMongo:

```<code>db.collection.group(["myField"], {}, {"count":0},"function(o, p){p.count++}" )
</code>```

Which correctly returns the numbers I need but the search takes 30 seconds to complete. Would indexing speed this up? I find it hard to know whether fields should or shouldn't be indexed because I read an article which said don't index too much or everything will slow down so I've indexed nothing..

答:
"group" is slow because it has to execute a Javascript function for each document it encounters. For this reason, the MongoDB manual says "group" is deprecated. "aggregate" has replaced "group" as a fast modern way to do tasks like this:

```<code>for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))
</code>```

See the MongoDB manual section about aggregation.

Title: MongoDB Count Distinct Speed

Body:
I'm using the following code in PyMongo:

db.collection.group(["myField"], {}, {"count":0},"function(o, p){p.count++}" )

Which correctly returns the numbers I need but the search takes 30 seconds to complete. Would indexing speed this up? I find it hard to know whether fields should or shouldn't be indexed because I read an article which said don't index too much or everything will slow down so I've indexed nothing..

Body:
"group" is slow because it has to execute a Javascript function for each document it encounters. For this reason, the MongoDB manual says "group" is deprecated. "aggregate" has replaced "group" as a fast modern way to do tasks like this:

for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

See the MongoDB manual section about aggregation.


问:
PHP + MySQL - What column type should be used to store serialized objects?
With PHP, I am storing serialized objects in a MySQL database.

What column type should I use? I am currently using "LONGTEXT" since basically it's a string.

It's working but I worry that bigger objects might not save correctly.

What column type should I use?

答:
Always use BLOB type to store serialized objects.

use MEDIUMBLOB or just BLOB, as long as those types are sufficient to store your serialized data.

BLOB type holds larger object and are binary safe.

Read more about BLOB


问:
Create two threads, one display odd & other even numbers
I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program?</p>

```<code>public class Mythread {

    public static void main(String[] args) {
        Runnable r = new Runnable1();
        Thread t = new Thread(r);
        t.start();
        Runnable r2 = new Runnable2();
        Thread t2 = new Thread(r2);
        t2.start();
    }
}

class Runnable2 implements Runnable{
    public void run(){
        for(int i=0;i<11;i++){
            if(i%2 == 1)
                System.out.println(i);
        }
    }
}

class Runnable1 implements Runnable{
    public void run(){
        for(int i=0;i<11;i++){
            if(i%2 == 0)
                System.out.println(i);
        }
    }
}
</code>```

答:
Pretty much all that is necessary if you are asked to print even odd numbers in synchronized manner.</p>

```<code>public class ThreadingOddEvenNumbers {

    void main(String[] args) throws InterruptedException {
        Printer printer = new Printer(57);
        Thread t1 = new Thread(new MyRunner(printer, true), "EvenPrinter");
        Thread t2 = new Thread(new MyRunner(printer, false), "OddPrinter");
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

}

class MyRunner implements Runnable {
    private Printer p;
    private boolean evenProperty;

    public MyRunner(Printer p, boolean evenNess) {
        this.p = p;
        evenProperty = evenNess;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            System.out.println(this.getClass().getName() + " "
                    + ex.getMessage());
        }
    }

    public void print() throws InterruptedException {
        while (!p.isJobComplete()) {
            synchronized (p) {
                if (evenProperty)
                    while (p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
                else
                    while (!p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
            }

            synchronized (p) {
                if (evenProperty)
                    p.printEven(Thread.currentThread().getName());
                else
                    p.printOdd(Thread.currentThread().getName());
                p.notifyAll();
                System.out.println("notify called: by: "
                        + Thread.currentThread().getName());
            }
        }
    }
}

class Printer {
    private volatile boolean evenPrinted;
    private volatile boolean jobComplete;
    private int limit;
    private int counter;

    public Printer(int lim) {
        limit = lim;
        counter = 1;
        evenPrinted = true;
        jobComplete = false;
    }

    public void printEven(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = true;
    }

    public void printOdd(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = false;
    }

    private void incrCounter() {
        counter++;
        if (counter >= limit)
            jobComplete = true;
    }

    public int getLimit() {
        return limit;
    }

    public boolean isEvenPrinted() {
        return evenPrinted;
    }

    public boolean isJobComplete() {
        return jobComplete;
    }
}
</code>```

Body:
I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program?

public class Mythread {

    public static void main(String[] args) {
        Runnable r = new Runnable1();
        Thread t = new Thread(r);
        t.start();
        Runnable r2 = new Runnable2();
        Thread t2 = new Thread(r2);
        t2.start();
    }
}

class Runnable2 implements Runnable{
    public void run(){
        for(int i=0;i<11;i++){
            if(i%2 == 1)
                System.out.println(i);
        }
    }
}

class Runnable1 implements Runnable{
    public void run(){
        for(int i=0;i<11;i++){
            if(i%2 == 0)
                System.out.println(i);
        }
    }
}

Body:
Pretty much all that is necessary if you are asked to print even odd numbers in synchronized manner.

public class ThreadingOddEvenNumbers {

    void main(String[] args) throws InterruptedException {
        Printer printer = new Printer(57);
        Thread t1 = new Thread(new MyRunner(printer, true), "EvenPrinter");
        Thread t2 = new Thread(new MyRunner(printer, false), "OddPrinter");
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }

}

class MyRunner implements Runnable {
    private Printer p;
    private boolean evenProperty;

    public MyRunner(Printer p, boolean evenNess) {
        this.p = p;
        evenProperty = evenNess;
    }

    public void run() {
        try {
            print();
        } catch (InterruptedException ex) {
            System.out.println(this.getClass().getName() + " "
                    + ex.getMessage());
        }
    }

    public void print() throws InterruptedException {
        while (!p.isJobComplete()) {
            synchronized (p) {
                if (evenProperty)
                    while (p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
                else
                    while (!p.isEvenPrinted()) {
                        System.out.println("wait by: "
                                + Thread.currentThread().getName());
                        p.wait();
                        if (p.isJobComplete())
                            break;
                    }
            }

            synchronized (p) {
                if (evenProperty)
                    p.printEven(Thread.currentThread().getName());
                else
                    p.printOdd(Thread.currentThread().getName());
                p.notifyAll();
                System.out.println("notify called: by: "
                        + Thread.currentThread().getName());
            }
        }
    }
}

class Printer {
    private volatile boolean evenPrinted;
    private volatile boolean jobComplete;
    private int limit;
    private int counter;

    public Printer(int lim) {
        limit = lim;
        counter = 1;
        evenPrinted = true;
        jobComplete = false;
    }

    public void printEven(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = true;
    }

    public void printOdd(String threadName) {
        System.out.println(threadName + "," + counter);
        incrCounter();
        evenPrinted = false;
    }

    private void incrCounter() {
        counter++;
        if (counter >= limit)
            jobComplete = true;
    }

    public int getLimit() {
        return limit;
    }

    public boolean isEvenPrinted() {
        return evenPrinted;
    }

    public boolean isJobComplete() {
        return jobComplete;
    }
}


问:
easy code not working on empty project ( binding ,input , ng model) in any browser
Im having a problem with the following code, is a simple one, i want to be able to se in my view what i put in the input text. but nothing is happening. when running in the online simulator no problem, but in my browser nothing happens. what im doing wrong?. my project is empty. Also tried it in firefox, explorer and chrome, and not working at all. the only thing i have is this pice of code. have no error in browser console... im using angular cli.
what im doing wrong guys? please help.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div></code>```

SOURCE

答:
    Name: <input ng-model="firstname">

{{firstname}}

```

Body:
Im having a problem with the following code, is a simple one, i want to be able to se in my view what i put in the input text. but nothing is happening. when running in the online simulator no problem, but in my browser nothing happens. what im doing wrong?. my project is empty. Also tried it in firefox, explorer and chrome, and not working at all. the only thing i have is this pice of code. have no error in browser console... im using angular cli.
what im doing wrong guys? please help.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});

    Name: <input ng-model="firstname">

{{firstname}}

SOURCE

Body:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script >
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});
</script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div>


问:
Wordpress numeric pagination without words
My work's Wordpress site needs a numeric pagination for the posts page, however as it's a multilingual site I can't have any words in it like "Previous page" or "Page 1 of 3".

I've tried a couple of different examples that I've found (as I'm not skilled enough to write it myself yet), but they all contain words hidden within queries and I can't figure out how to change them. Eg:

```<code>function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>« First</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹ Previous</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next ›</a>";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last »</a>";
         echo "</div>\n";
     }
}
</code>```

This code shows "Page 1 of 2". If I could just change that to 1/2 for example, that would be perfect. Is anyone able to explain how I could do this, or any alternative methods? Many thanks!

答: In the end I just isolated the text that said "Page 1 of 2" and gave it a display:none; style. Not really a solution but it works for this project.

Body:
My work's Wordpress site needs a numeric pagination for the posts page, however as it's a multilingual site I can't have any words in it like "Previous page" or "Page 1 of 3".

I've tried a couple of different examples that I've found (as I'm not skilled enough to write it myself yet), but they all contain words hidden within queries and I can't figure out how to change them. Eg:

function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "
Page ".$paged." of ".$pages."";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "« First";
         if($paged > 1 && $showitems < $pages) echo "‹ Previous";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "".$i."":"".$i."";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "Next ›";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "Last »";
         echo "
\n";
     }
}

This code shows "Page 1 of 2". If I could just change that to 1/2 for example, that would be perfect. Is anyone able to explain how I could do this, or any alternative methods? Many thanks!


问:
PhpStorm WebStorm: change auto-import source resolution
Here is my file structure

```<code>component.ts
/services
  first.service.ts
  second.service.ts
  index.ts
</code>```

index.ts

```<code>export * from './first.service';
export * from './second.service';
</code>```

From component.ts, I wish to use a service. This is how my IDE (PhpStorm/WebStorm) automatically generates the import code

```<code>import { FirstService } from './services/first.service'
</code>```

Of course this works. But I would prefer:

```<code>import { FirstService } from './services/index'
</code>```

Can this be tweaked through a setting?

Update

I've changed my mind about using barrel files all over my Angular project after reading this thread about the subject. I would recommend reading it to anyone considering doing the same thing.

答: In Settings | Editor | Code Style | TypeScript | Imports, enable Use directory import (Node-style module resolution) . When this checkbox is selected, import statements are generated in compliance with the Node.js module resolution strategy

Body:
Here is my file structure

component.ts
/services
  first.service.ts
  second.service.ts
  index.ts

index.ts

export * from './first.service';
export * from './second.service';

From component.ts, I wish to use a service. This is how my IDE (PhpStorm/WebStorm) automatically generates the import code

import { FirstService } from './services/first.service'

Of course this works. But I would prefer:

import { FirstService } from './services/index'

Can this be tweaked through a setting?

Update

I've changed my mind about using barrel files all over my Angular project after reading this thread about the subject. I would recommend reading it to anyone considering doing the same thing.


问:
How do I make a loading bar for an HTML5 audio element?
I'm trying to make a loading bar (showing percentage loaded/buffered) for an HTML5 audio element.

For the video tag it's possible to calculate using the following:

```<code>video.buffered.end(0) / video.duration
</code>```

But I can't get this to work with the audio tag. It just returns a fix value.

Any idea?

Thanks!

答:
I am not quite sure if i do undestand your prob. but here is a way i used to calculate how much audio is buffered

var audio = document.querySelector('audio');
var set;
window.onload = function(){set=setInterval(buffer,1000);};
    function buffer () {
    if(audio.buffered.length>0){
   var percent = (audio.buffered.end(0) / audio.duration) * 100;
       document.querySelector('p').innerHTML = percent+'%';
     if(percent === 100){
           clearInterval(set);
       }
       }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio src="http://customhtml5video.000webhostapp.com/audio.mp3" controls></audio>
<p></p></code>```

Body:
I'm trying to make a loading bar (showing percentage loaded/buffered) for an HTML5 audio element.

For the video tag it's possible to calculate using the following:

video.buffered.end(0) / video.duration

But I can't get this to work with the audio tag. It just returns a fix value.

Any idea?

Thanks!

Body:
I am not quite sure if i do undestand your prob. but here is a way i used to calculate how much audio is buffered

var audio = document.querySelector('audio');
var set;
window.onload = function(){set=setInterval(buffer,1000);};
    function buffer () {
    if(audio.buffered.length>0){
   var percent = (audio.buffered.end(0) / audio.duration) * 100;
       document.querySelector('p').innerHTML = percent+'%';
     if(percent === 100){
           clearInterval(set);
       }
       }
}

<audio src="http://customhtml5video.000webhostapp.com/audio.mp3" controls></audio>
<p></p>


问:
Is there an optimized method for finding the farthest corner of a cube in 3D
If a have a cube C with 8 corners ( not axis aligned ) and a random point P can I do better than just checking all the corners and picking the corner with the greatest distance from P or is it possible to reduce the number of checks by taking into account the symmetrical nature of the cube?

答:
Transform the point P to the cube's principle basis, i.e. in which it is axially aligned (call the new point Q), and the origin is the centre of the cube in world space

To find the furthest point in this frame, F: using the X-axis as an example, if

Q.x > 0 then F.x = -L, where L is the side length of the cube

Q.x < 0 then F.x = L

Q.x == 0 (strictly abs(Q.x) < EPSILON), then F.x = 0

Do step 2 for the other two axes as well

Transform the resulting point F back to world space, by the inverse transform of the one performed in step 1. This will give the furthest point on the cube that you want.

EDIT: let's see why this could be more efficient.

Original method: 8 X square distance calculations = 8 X (3 floating point multiplications + 2 additions)

New method: 2 matrix multiplications = 2 X (9 fp multiplications + 6 additions)

As you can see, the new method uses fewer multiplications and additions.


问:
Altering attributes in another class in Python
I have been trying to alter a list in class Inventory from class Pod, but I get an error that I am popping from an empty set.  Is there anyway that I can pop from a list from an Inventory instance that I know is populated?  Essentially, I am trying to transfer widgets from Inventory to Pod.</p>

```<code>class Widget():

    def __init__(self):
        self.cost = 6
        self.value = 9

class Inventory():

    def __init__(self):
        self.widgets_inv = []
        self.cost_inv = 0
        self.value_inv = 0

    def buy_inv(self):
        x = int(input("How many widgets to you want to add to inventory? "))
        for i in range(0, x):
            self.widgets_inv.append(Widget())

    def get_inv(self):
        print("You have " + str(len(self.widgets_inv)) + " widgets in inventory.")

    def cost_of_inv(self):
        cost_inv = len(self.widgets_inv) * Widget().cost
        print("The current cost of your inventory is: " + cost_inv + " USD.")

    def value_of_inv(self):
        val_inv = len(self.widgets_inv) * Widget().value
        print("The current value of your inventory is: " + val_inv + " USD.")

class Pod():
    """A pod is a grouping of several widgets.  Widgets are sold in pods"""

    def __init__(self):
        self.pod = []

    def creat_pod(self):
        x = int(input("How many widgets would you like to place in this pod? "))
        for i in range(0, x):
            self.pod.append(Widget())
            Inventory().widgets_inv.pop()
</code>```

答:
You should modify the creat_pod-method, so that you can handover the Inventory-object. This allows you to add widgets to the inventory-object before calling creat_pod-method:

```<code>def creat_pod(self, inventory):
        x = int(input("How many widgets would you like to place in this pod? "))
        for i in range(0, x):
            self.pod.append(Widget())
            inventory.widgets_inv.pop()
</code>```

In your original code you create always a new Inventory-object, which has therefore and empty widget-list:

```<code>Inventory().widgets_inv.pop()
</code>```

Body:
I have been trying to alter a list in class Inventory from class Pod, but I get an error that I am popping from an empty set.  Is there anyway that I can pop from a list from an Inventory instance that I know is populated?  Essentially, I am trying to transfer widgets from Inventory to Pod.

class Widget():

    def __init__(self):
        self.cost = 6
        self.value = 9

class Inventory():

    def __init__(self):
        self.widgets_inv = []
        self.cost_inv = 0
        self.value_inv = 0

    def buy_inv(self):
        x = int(input("How many widgets to you want to add to inventory? "))
        for i in range(0, x):
            self.widgets_inv.append(Widget())

    def get_inv(self):
        print("You have " + str(len(self.widgets_inv)) + " widgets in inventory.")

    def cost_of_inv(self):
        cost_inv = len(self.widgets_inv) * Widget().cost
        print("The current cost of your inventory is: " + cost_inv + " USD.")

    def value_of_inv(self):
        val_inv = len(self.widgets_inv) * Widget().value
        print("The current value of your inventory is: " + val_inv + " USD.")

class Pod():
    """A pod is a grouping of several widgets.  Widgets are sold in pods"""

    def __init__(self):
        self.pod = []

    def creat_pod(self):
        x = int(input("How many widgets would you like to place in this pod? "))
        for i in range(0, x):
            self.pod.append(Widget())
            Inventory().widgets_inv.pop()

Body:
You should modify the creat_pod-method, so that you can handover the Inventory-object. This allows you to add widgets to the inventory-object before calling creat_pod-method:

def creat_pod(self, inventory):
        x = int(input("How many widgets would you like to place in this pod? "))
        for i in range(0, x):
            self.pod.append(Widget())
            inventory.widgets_inv.pop()

In your original code you create always a new Inventory-object, which has therefore and empty widget-list:

Inventory().widgets_inv.pop()


问:
Can't follow an organization in ckan
I setup ckan from source from the latest docs. When a user tries to follow an organization the following error appears on the interface in my browser:

```<code>404 Not Found

The resource could not be found.

Incorrect group type
</code>```

When I run the site using the "paster serve /etc/ckan/default/development.ini" command in my virtualenv I get the following error on my site when following an organization:

```<code>"Server Error

An internal server error occurred"
</code>```

And I get the following traceback on my terminal:

```<code>Error - <type 'exceptions.OSError'>: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'
URL: http://127.0.0.1:5000/group/follow/80a2d460-6c4d-436d-8e3b-45b2efca0752
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__
  app_iter = self.application(environ, sr_checker)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__
  return request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__
  response = request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/config/middleware/pylons_app.py', line 245 in inner
  result = application(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__
  return self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 155 in __call__
  return self.wrap_app(environ, session_start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__
  response = self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__
  response = self.dispatch(controller, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch
  return controller(environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/lib/base.py', line 292 in __call__
  res = WSGIController.__call__(self, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 284 in __call__
  return response(environ, self.start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 341 in __call__
  return self.generate_response(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 333 in generate_response
  return resp(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/response.py', line 917 in __call__
  start_response(self.status, headerlist)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 149 in session_start_response
  session.persist()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 735 in persist
  self._session().save()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 415 in save
  **self.namespace_args)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 635 in __init__
  OpenResourceNamespaceManager.__init__(self, namespace)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 190 in __init__
  self.access_lock = self.get_access_lock()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 647 in get_access_lock
  lock_dir=self.lock_dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 81 in file_synchronizer
  return _synchronizer(identifier, FileSynchronizer, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 74 in _synchronizer
  return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 177 in sync_get
  return self._create(key, createfunc, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 184 in _create
  self[key] = obj = createfunc(*args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 226 in __init__
  extension='.lock'
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 238 in encoded_path
  verify_directory(dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 85 in verify_directory
  os.makedirs(dir)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 150 in makedirs
  makedirs(head, mode)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 157 in makedirs
  mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'
</code>```

Please help.

答:
The exception is saying that it's failing to create a directory due to file permissions. Try the same thing on the command-line:

```<code>mkdir -p /tmp/default/sessions/container_file_lock/4
</code>```

Assuming that fails too, then you have two options:

change your file permissions to allow writes to /tmp

tell CKAN to store its beaker sessions elsewhere where it can write. The relevant CKAN configuration option is: cache_dir.

Title: Can't follow an organization in ckan

Body:
I setup ckan from source from the latest docs. When a user tries to follow an organization the following error appears on the interface in my browser:

404 Not Found

The resource could not be found.

Incorrect group type

When I run the site using the "paster serve /etc/ckan/default/development.ini" command in my virtualenv I get the following error on my site when following an organization:

"Server Error

An internal server error occurred"

And I get the following traceback on my terminal:

Error - <type 'exceptions.OSError'>: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'
URL: http://127.0.0.1:5000/group/follow/80a2d460-6c4d-436d-8e3b-45b2efca0752
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/weberror/errormiddleware.py', line 171 in __call__
  app_iter = self.application(environ, sr_checker)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/publisher.py', line 234 in __call__
  return request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 147 in __call__
  resp = self.call_func(req, *args, **self.kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/dec.py', line 208 in call_func
  return self.func(req, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/fanstatic/injector.py', line 54 in __call__
  response = request.get_response(self.app)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1053 in get_response
  application, catch_exc_info=False)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/request.py', line 1022 in call_application
  app_iter = application(self.environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/config/middleware/pylons_app.py', line 245 in inner
  result = application(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 73 in __call__
  return self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 155 in __call__
  return self.wrap_app(environ, session_start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/routes/middleware.py', line 131 in __call__
  response = self.app(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 125 in __call__
  response = self.dispatch(controller, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/wsgiapp.py', line 324 in dispatch
  return controller(environ, start_response)
File '/home/ammar/ckan/lib/default/src/ckan/ckan/lib/base.py', line 292 in __call__
  res = WSGIController.__call__(self, environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/pylons/controllers/core.py', line 284 in __call__
  return response(environ, self.start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 341 in __call__
  return self.generate_response(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/exc.py', line 333 in generate_response
  return resp(environ, start_response)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/webob/response.py', line 917 in __call__
  start_response(self.status, headerlist)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/middleware.py', line 149 in session_start_response
  session.persist()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 735 in persist
  self._session().save()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/session.py', line 415 in save
  **self.namespace_args)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 635 in __init__
  OpenResourceNamespaceManager.__init__(self, namespace)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 190 in __init__
  self.access_lock = self.get_access_lock()
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/container.py', line 647 in get_access_lock
  lock_dir=self.lock_dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 81 in file_synchronizer
  return _synchronizer(identifier, FileSynchronizer, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 74 in _synchronizer
  return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 177 in sync_get
  return self._create(key, createfunc, *args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 184 in _create
  self[key] = obj = createfunc(*args, **kwargs)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/synchronization.py', line 226 in __init__
  extension='.lock'
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 238 in encoded_path
  verify_directory(dir)
File '/usr/lib/ckan/default/local/lib/python2.7/site-packages/beaker/util.py', line 85 in verify_directory
  os.makedirs(dir)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 150 in makedirs
  makedirs(head, mode)
File '/usr/lib/ckan/default/lib/python2.7/os.py', line 157 in makedirs
  mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/tmp/default/sessions/container_file_lock/4'

Please help.

Body:
The exception is saying that it's failing to create a directory due to file permissions. Try the same thing on the command-line:

mkdir -p /tmp/default/sessions/container_file_lock/4

Assuming that fails too, then you have two options:

change your file permissions to allow writes to /tmp

tell CKAN to store its beaker sessions elsewhere where it can write. The relevant CKAN configuration option is: cache_dir.


问:
WPF: Add 5 Pixels to Column Width
I have a Grid with 4 columns:

```<code><Grid.ColumnDefinitions>
    <ColumnDefinition Width="14" />
    <ColumnDefinition Width="10" />
    <ColumnDefinition Width="{TemplateBinding ActualWidth}" />
    <ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
</code>```

Now i want to add 5 Pixels to the width of the third column? Do i need a converter for this, or is there any other simple trick to do that?

答:
You'll need a converter, but before that, you can't TemplateBinding to ActualWidth.

Stuff will not work like you want it to, because the other columns will cause you control to resize itself.

You will need another solution

Title: WPF: Add 5 Pixels to Column Width

Body:
I have a Grid with 4 columns:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="14" />
    <ColumnDefinition Width="10" />
    <ColumnDefinition Width="{TemplateBinding ActualWidth}" />
    <ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>

Now i want to add 5 Pixels to the width of the third column? Do i need a converter for this, or is there any other simple trick to do that?


问:
ObjectDataSource could not find a non-generic method
I have this ASP.NET code:

```<code><asp:DropDownList
    ID="ddlBrokers"
    runat="server"
    AutoPostBack="true"
    DataSourceID="srcBrokers"
    DataTextField="broker"
    DataValueField="brokerId"
/>

<asp:ObjectDataSource
    id="srcBrokers"
    TypeName="DatabaseComponent.DBUtil"
    SelectMethod="GetBrokers"
    runat="server">
</asp:ObjectDataSource>
</code>```

My DAL code:

```<code>public DataTable GetBrokers(bool? hasImport=null)
{
    SqlCommand cmd = new SqlCommand("usp_GetBrokers");
    if (hasImport.HasValue)
        cmd.Parameters.AddWithValue("@hasImport", hasImport);
    return FillDataTable(cmd, "brokers");
}
</code>```

When the form loads I get this error:

```<code>ObjectDataSource 'srcBrokers' could not find a non-generic method 'GetBrokers' that has no parameters.
</code>```

Is it my optional parameter that is causing the problem? How can I workaround this? Is it possible to have optional parameters with declarative ASP.NET code?

答:
add method:

```<code>public DataTable GetBrokers() {
              return GetBrokers(null);
}
</code>```

and check is it works?

ContentLicense: CC BY-SA 2.5

Body:
I have this ASP.NET code:

<asp:DropDownList
    ID="ddlBrokers"
    runat="server"
    AutoPostBack="true"
    DataSourceID="srcBrokers"
    DataTextField="broker"
    DataValueField="brokerId"
/>

<asp:ObjectDataSource
    id="srcBrokers"
    TypeName="DatabaseComponent.DBUtil"
    SelectMethod="GetBrokers"
    runat="server">
</asp:ObjectDataSource>

My DAL code:

public DataTable GetBrokers(bool? hasImport=null)
{
    SqlCommand cmd = new SqlCommand("usp_GetBrokers");
    if (hasImport.HasValue)
        cmd.Parameters.AddWithValue("@hasImport", hasImport);
    return FillDataTable(cmd, "brokers");
}

When the form loads I get this error:

ObjectDataSource 'srcBrokers' could not find a non-generic method 'GetBrokers' that has no parameters.

Is it my optional parameter that is causing the problem? How can I workaround this? Is it possible to have optional parameters with declarative ASP.NET code?

Body:
add method:

public DataTable GetBrokers() {
              return GetBrokers(null);
}

and check is it works?


问:
react native flexbox split screen
i am trying to split the screen using flexbox, but i am not getting the result i desire, here is what i have

```<code><View style={{flex: 1}}>
    <View style={{flex: 1}}>{/* half of the screen */}</View>

    <View style={{flex: 1}}>{/* the other half */}
        {/*<Swiper>*/}
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
        {/*</Swiper>*/}
    </View>
</View>
</code>```

the problem that i am having is that the other half of the screen expands to take the size of the full screen, it is just appended to the first half without taking into consideration that is bounded by the half it exist in

screenshot

how should i approach this?

答:
Uhm, so I kind of know what I am doing in React Native now, after over a year of learning.</p>

```<code><View style={{ flex: 1 }}>
  <View style={{ backgroundColor: 'gray', flex: 1 }} />

  <View style={{ flex: 1 }}>
    <Swiper>
      <View
        style={{
          alignItems: 'center',
          backgroundColor: 'red',
          justifyContent: 'center',
          height: Dimensions.get('window').height / 2
        }}>
        <Text style={{ color: 'white' }}>Test</Text>
      </View>
      <View
        style={{
          alignItems: 'center',
          backgroundColor: 'green',
          justifyContent: 'center',
          height: Dimensions.get('window').height / 2
        }}>
        <Text style={{ color: 'white' }}>Test</Text>
      </View>
      <View
        style={{
          alignItems: 'center',
          backgroundColor: 'blue',
          justifyContent: 'center',
          height: Dimensions.get('window').height / 2
        }}>
        <Text style={{ color: 'white' }}>Test</Text>
      </View>
    </Swiper>
  </View>
</View>
</code>```

Title: react native flexbox split screen

Body:
i am trying to split the screen using flexbox, but i am not getting the result i desire, here is what i have

<View style={{flex: 1}}>
    <View style={{flex: 1}}>{/* half of the screen */}</View>

    <View style={{flex: 1}}>{/* the other half */}
        {/*<Swiper>*/}
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
            <View style={{flex: 1}}>{/* a quarter of the other half */}</View>
        {/*</Swiper>*/}
    </View>
</View>

the problem that i am having is that the other half of the screen expands to take the size of the full screen, it is just appended to the first half without taking into consideration that is bounded by the half it exist in

screenshot

how should i approach this?

Body:
Uhm, so I kind of know what I am doing in React Native now, after over a year of learning.

<View style={{ flex: 1 }}>
  <View style={{ backgroundColor: 'gray', flex: 1 }} />

  <View style={{ flex: 1 }}>
    <Swiper>
      <View
        style={{
          alignItems: 'center',
          backgroundColor: 'red',
          justifyContent: 'center',
          height: Dimensions.get('window').height / 2
        }}>
        <Text style={{ color: 'white' }}>Test</Text>
      </View>
      <View
        style={{
          alignItems: 'center',
          backgroundColor: 'green',
          justifyContent: 'center',
          height: Dimensions.get('window').height / 2
        }}>
        <Text style={{ color: 'white' }}>Test</Text>
      </View>
      <View
        style={{
          alignItems: 'center',
          backgroundColor: 'blue',
          justifyContent: 'center',
          height: Dimensions.get('window').height / 2
        }}>
        <Text style={{ color: 'white' }}>Test</Text>
      </View>
    </Swiper>
  </View>
</View>


问:
CSS : Overflow-x: hidden, Overflow-y: visible in a carousel with dropdown
Here is my problem. I have a carousel that act like a menu also. When the amount of tabs is higher than the space of width available on your browser, the carousel-controls appears. Everything works fine. But I added as well a dropdown menu on each tabs and here is the thing. If I put overflow:visible, we can see the tabs sliding in and out of the div, which is very ugly.

If I put overflow:hidden, the slider works fine, but then, I can't see anymore my dropdown menu since they are hidden vertically as well. I tried to put overflow-y: visible and overflow-x:hidden but this won't work because if the "x" is visible, it will be considered as auto if the "y" is different. In other words, my slider works, but there is a scroll bar added to show my dropdown, which is very ugly.

I saw on another post to wrap it around a larger container, and I only hide the "x" while my "y" will fall back into the larger container. I can not do that since my carousel will break if the structure is not maintained.

So my question is : How can I do so that my slider looks good (we don't see the tabs sliding in and out) as well as my dropdown menu is showed up!

Here is the link if you want to check this out : https://decktogo.com/pages/downloads_user-manual_brochures

On large screen, you won't see anything wrong. Resize your browser window so that the width of it is around 380px. The slider will come in play and you will see the mess.

If you want my code, you can right click and inspect my website page to look at all the code there.

Thank you for your help,
Jonathan

答:
Problem solved! Unfortunately, it didn't seem to have a good answer for that. So I did an overflow-x: hidden so that my carousel works fine. To solve the dropdown problem, I put a height:400px with margin-bottom:-300px which result in the good final looking with all what it supposed to be. It is just unfortunate that overflow-x and overflow-y doesn't work in that way.

.download .carousel-inner.onebyone-carosel {
  margin:0 40px;
  overflow-x:hidden;
  width: auto;
  height: 400px;
  margin-bottom:-300px;
  z-index: 4;
}

.download .carousel-inner{
  overflow: initial;
}```


问:
C# 6.0 null-coalescing not working correctly for me
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?</p>

```<code>  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";
</code>```

答:
You are trying to access [Value][1] property of Nullable<T> when it does not have the value assigned. As specification says, it will throw and exception:

If a value of type T has not been assigned to the Nullable object,
  you can compare it to null and retrieve its HasValue property, but you
  cannot access its Value property or call its other members.

You have two options here - use null-conditional operator to avoid accessing object properties if object is null:

```<code>string qty = stop.pallets_qty_total?.Value.ToString() ?? "0";
</code>```

Or you can keep in mind that default value for numeric type is zero. And get default value if nullable does not have value assigned:

```<code>string qty = stop.pallets_qty_total.GetValueOrDefault().ToString();
</code>```

That will be also tiny premature performance optimization.

Body:
Very simple question, the following code throws a "Nulllable object must have a value" exception.  But I thought that the ?? was going to handle that?

  string qty = stop.pallets_qty_total.Value.ToString() ?? "0";

Body:
You are trying to access [Value][1] property of Nullable<T> when it does not have the value assigned. As specification says, it will throw and exception:

If a value of type T has not been assigned to the Nullable object,
  you can compare it to null and retrieve its HasValue property, but you
  cannot access its Value property or call its other members.

You have two options here - use null-conditional operator to avoid accessing object properties if object is null:

string qty = stop.pallets_qty_total?.Value.ToString() ?? "0";

Or you can keep in mind that default value for numeric type is zero. And get default value if nullable does not have value assigned:

string qty = stop.pallets_qty_total.GetValueOrDefault().ToString();

That will be also tiny premature performance optimization.


问:
Payment Timeouts - Showing 504 Gateway Timeout
We have a cpouple of sites using website payments standard and are submitting the forms as a post to the https://www.paypal.com/cgi-bin/webscr address

some customers (not all) are experiencing a timeout when trying to get to the paypal payment page after the post.

The site sits and status bar says 'waiting for www.paypal.com'
The web Inspector on chrome shows a 504 Gateway Timeout error after 1 minute and then the user gets sent to a paypal page with a paypal debug-id down at the bottom

This is intermittent, sometimes there are no problems at all then sometimes a user cant get through, so we try at the same time and have no problem

has anyone else seen anything like this?

any ideas?

paypal support are 'looking into it' and said it couldb e a 'problem with our endpoint api' ... all we do is post to them and and then they send back a pdt/ipn when complete. and it works from different locations at the same time one person is down, someone accross thr country is fine, its like when there is a problem, the www.paypal.com address cannot be found by the browser trying to connect

答:
You are not alone. The old PayPal webform integration seems to have this problem every now and then. I believe there is nothing you can do other than hope that your customers are not affected (much).

The only alternative is to use a different PayPal API to integrate it in your shop.


问:
Git: with uncommited work, how to make changes in another branch and come back?
My team is using a very simple Git workflow. Everybody develops in the same branch. I'd like to know which are the series of commands I should do when I'm in the middle of the work and need to fix a bug.

Here is my situation:

Unpushed commited changes in my local master branch

Uncommited modified files

need to fix a bug in origin/master branch

I don't have another branch attached to master

need to push just these files that fix the problem

go back to work

Se that I'm working in the same branch of my coworkers.

Some users pointed that git stash would solve it and so this is a duplicate question. I dispute it, since I didn't even know that this feature existed. The feature solves my problem, but I believe the question is valid since I ask it from another point of view.

答:
you need to stash your changes:

```<code>git stash save "will come back in 5 minutes"
git checkout blahblah
jadajadajada
git checkout where-i-was
git stash pop
</code>```

You are back you where you were

Body:
you need to stash your changes:

git stash save "will come back in 5 minutes"
git checkout blahblah
jadajadajada
git checkout where-i-was
git stash pop

You are back you where you were


问:
for loop iterates strange
Good Morning,
I have a problem with for loop, I tried to make multiply progressbars on page and I try to triger them in one action:

```<code>function startProgressbaring(){

var progressArray = [
    progress1 = document.querySelector('.progressbar-1'),
    progress2 = document.querySelector('.progressbar-2'),
    progress3 = document.querySelector('.progressbar-3'),
    progress4 = document.querySelector('.progressbar-4'),
    progress5 = document.querySelector('.progressbar-5'),
    progress6 = document.querySelector('.progressbar-6')
];
var durationArray = [
     progress1_Duration = 90,
     progress2_Duration = 65,
     progress3_Duration = 70,
     progress4_Duration = 55,
     progress5_Duration = 95,
     progress6_Duration = 90
];

var id = setInterval(frame,30);
var width = 1;

        function frame(){
        for(var z=0; z<durationArray.length; z++){

            if(width>durationArray[z]){
                clearInterval(id);
                console.log(durationArray[z]);
            }else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }

        };
</code>```

Console Log with durationArray returns only 55, for example
six progressbars have values between 56 and 60 not the values from durationArray,
no idea whats going wrong, thanks for any advices

答: I don't understand what you are trying to accomplish, but the code can be explained. You are not setting the width of your progress bars to any values in durationArray, you are setting your progress bars to the width value: progressArray[z].style.width = width + '%';. width will eventually be larger than the smallest value in the durationArray. When this happens, you stop the interval with clearInterval. width will increase a couple more times while for loop iterates for the last time.

Title: for loop iterates strange

Body:
Good Morning,
I have a problem with for loop, I tried to make multiply progressbars on page and I try to triger them in one action:

function startProgressbaring(){

var progressArray = [
    progress1 = document.querySelector('.progressbar-1'),
    progress2 = document.querySelector('.progressbar-2'),
    progress3 = document.querySelector('.progressbar-3'),
    progress4 = document.querySelector('.progressbar-4'),
    progress5 = document.querySelector('.progressbar-5'),
    progress6 = document.querySelector('.progressbar-6')
];
var durationArray = [
     progress1_Duration = 90,
     progress2_Duration = 65,
     progress3_Duration = 70,
     progress4_Duration = 55,
     progress5_Duration = 95,
     progress6_Duration = 90
];

var id = setInterval(frame,30);
var width = 1;

        function frame(){
        for(var z=0; z<durationArray.length; z++){

            if(width>durationArray[z]){
                clearInterval(id);
                console.log(durationArray[z]);
            }else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }

        };

Console Log with durationArray returns only 55, for example
six progressbars have values between 56 and 60 not the values from durationArray,
no idea whats going wrong, thanks for any advices


问:
How to get the total number of positive, neutral and negative tweets in SQL Server?
I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 ---  ---  ---  ---  --- 700 ---  ---  ---  ---  800

The schema for the tables involved in this query:

```<code>T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText
</code>```

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

```<code>SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6
</code>```

答:
I don't see why you need T_tweet for this.  The JOIN seems unnecessary:

```<code>SELECT SUM(CASE WHEN ts.SentimentLabel = 'Positive' THEN 1 ELSE 0
           END) as PositiveCount,
       SUM(CASE WHEN ts.SentimentLabel = 'Neutral' THEN 1 ELSE 0
           END) as NeutralCount,
       SUM(CASE WHEN ts.SentimentLabel = 'Negative' THEN 1 ELSE 0
           END) as NegativeCount
FROM dbo.T_TweetSentiment ts
WHERE ts.TypeId = 6;
</code>```

The only reason you would need the join is if you had TweetIds in T_TweetSentiment that are not in the tweets table.  That seems unlikely (and would be a sign of an issue with the data design).

Body:
I am a new SQL developer and I am trying to write a query that will retrieve the total number of positive, negative and neutral tweets in the database. The result should look like the following:

PositivesCount --- NeutralCount --- NegativeCount

500 ---  ---  ---  ---  --- 700 ---  ---  ---  ---  800

The schema for the tables involved in this query:

T_TweetSentiment Table: Id, TweetId, SentimentLabel, TypeId
T_Tweet Table: Id, TweetText

The T_TweetSentiment table contains three different sentiment labels; positive, negative and neutral. I would like to retrieve the total number of positive tweets, neutral tweets and negative tweets as illustrated above. So could you please tell me how I can get the desired result?

Here's the query I have but it is not working:

SELECT  MAX(CASE WHEN ts.SentimentLabel = 'Positive' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS PositivesCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Neutral'  THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NeutralsCount,
        MAX(CASE WHEN ts.SentimentLabel = 'Negative' THEN COUNT(ts.SentimentLabel) ELSE NULL END) AS NegativeCount
FROM            dbo.T_TweetSentiment AS ts INNER JOIN
                         dbo.T_Tweet AS t ON ts.TweetId = t.Id
WHERE    ts.TypeId = 6

Body:
I don't see why you need T_tweet for this.  The JOIN seems unnecessary:

SELECT SUM(CASE WHEN ts.SentimentLabel = 'Positive' THEN 1 ELSE 0
           END) as PositiveCount,
       SUM(CASE WHEN ts.SentimentLabel = 'Neutral' THEN 1 ELSE 0
           END) as NeutralCount,
       SUM(CASE WHEN ts.SentimentLabel = 'Negative' THEN 1 ELSE 0
           END) as NegativeCount
FROM dbo.T_TweetSentiment ts
WHERE ts.TypeId = 6;

The only reason you would need the join is if you had TweetIds in T_TweetSentiment that are not in the tweets table.  That seems unlikely (and would be a sign of an issue with the data design).


问:
Recursively Create a Menu using two Lists
I'm having trouble making a dynamic menu using ASP.NET MVC where the menu is organized according to your Groups in Active Directory. To cut through useless details, I have retrieved two lists: one gives me all the folders of the menu, the other gives me all the files. How would one go about recursively creating the menu, knowing that folders can have subfolders, and subsubfolders and so on? In my project they are called I have two models DocumentModel and CategoryModel as follows :

```<code>//Files
public class DocumentModel
{
    public long iDDocument { get; set; }
    public long iDCategory { get; set; }
    public string docName { get; set; }
    public string link { get; set; }
    public string type { get; set; }
}
//Folders
public class CategoryModel
{
    public long iDCategory { get; set; }
    public string nom { get; set; }
    public int iDParentCategory { get; set; }
}
</code>```

I then pass them to my view using a bigger model:

```<code>public class CatDocViewModel
{
    public IEnumerable<CategoryModel> catModel { get; set; }
    public IEnumerable<DocumentModel> docModel { get; set; }
}
</code>```

So my idea is to make a recursive method in a partial view. Using Razor helpers I can make a recursive method, but I'm having a hard time with these kinds of methods.

Another problem arising is that I use IEnumerable so I have to loop through them, will that be too costly for the algorithm since I will recurse and loop again etc ...? But I also cannot make it without recursion since the depth of folders is unknown, so I have to recurse until I hit the end and then roll back up. But How?

I don't think anyone can make the algorithm but if you had some directions to point me in so  I can maybe delve into recursivity and understand how to do it?

EDIT As suggested in the marked answer, here is what I would do to then build then Child lists:

```<code>    public List<CategoryModel> getDocumentChilren(List<CategoryModel> categories, List<DocumentModel> documents)
    {
        foreach(var cat in categories)
        {
            if (cat.idParentCategory == 0)
                continue;
            foreach(var nextCat in categories)
            {
                if (nextCat.idParentCategory == cat.idParentCategory && nextCat.idCategory != cat.idCategory)
                    cat.childCategories.Add(nextCat);
            }
            foreach (var nextDoc in documents)
            {
                if (nextDoc.idCategory == cat.idCategory)
                    cat.childDocuments.Add(nextDoc);
            }
        }
        return categories;
    }
</code>```

This is O(n^2) I believe so is it ok? If I were to make an estimation, I'd have about 20 entries per loop, so that wouldn't be too greedy?

答:
I would organize the folders in a class more suitable for a tree structure like this:

```<code>public class CategoryModel
{
    public long iDCategory { get; set; }
    public string nom { get; set; }
    public List<CategoryModel> ChildCategories {get;set;}
    public List<DocumentModel> ChildDocuments {get;set;}
}
</code>```

Then, instead of using CatDocViewModel , you could use List<CategoryModel> as the view model for the menu.

Body:
I'm having trouble making a dynamic menu using ASP.NET MVC where the menu is organized according to your Groups in Active Directory. To cut through useless details, I have retrieved two lists: one gives me all the folders of the menu, the other gives me all the files. How would one go about recursively creating the menu, knowing that folders can have subfolders, and subsubfolders and so on? In my project they are called I have two models DocumentModel and CategoryModel as follows :

//Files
public class DocumentModel
{
    public long iDDocument { get; set; }
    public long iDCategory { get; set; }
    public string docName { get; set; }
    public string link { get; set; }
    public string type { get; set; }
}
//Folders
public class CategoryModel
{
    public long iDCategory { get; set; }
    public string nom { get; set; }
    public int iDParentCategory { get; set; }
}

I then pass them to my view using a bigger model:

public class CatDocViewModel
{
    public IEnumerable<CategoryModel> catModel { get; set; }
    public IEnumerable<DocumentModel> docModel { get; set; }
}

So my idea is to make a recursive method in a partial view. Using Razor helpers I can make a recursive method, but I'm having a hard time with these kinds of methods.

Another problem arising is that I use IEnumerable so I have to loop through them, will that be too costly for the algorithm since I will recurse and loop again etc ...? But I also cannot make it without recursion since the depth of folders is unknown, so I have to recurse until I hit the end and then roll back up. But How?

I don't think anyone can make the algorithm but if you had some directions to point me in so  I can maybe delve into recursivity and understand how to do it?

EDIT As suggested in the marked answer, here is what I would do to then build then Child lists:

    public List<CategoryModel> getDocumentChilren(List<CategoryModel> categories, List<DocumentModel> documents)
    {
        foreach(var cat in categories)
        {
            if (cat.idParentCategory == 0)
                continue;
            foreach(var nextCat in categories)
            {
                if (nextCat.idParentCategory == cat.idParentCategory && nextCat.idCategory != cat.idCategory)
                    cat.childCategories.Add(nextCat);
            }
            foreach (var nextDoc in documents)
            {
                if (nextDoc.idCategory == cat.idCategory)
                    cat.childDocuments.Add(nextDoc);
            }
        }
        return categories;
    }

This is O(n^2) I believe so is it ok? If I were to make an estimation, I'd have about 20 entries per loop, so that wouldn't be too greedy?

Body:
I would organize the folders in a class more suitable for a tree structure like this:

public class CategoryModel
{
    public long iDCategory { get; set; }
    public string nom { get; set; }
    public List<CategoryModel> ChildCategories {get;set;}
    public List<DocumentModel> ChildDocuments {get;set;}
}

Then, instead of using CatDocViewModel , you could use List<CategoryModel> as the view model for the menu.


问:
What does select{} do?
Reading The Go Memory Model, I fell on this code snippet.

```<code>var limit = make(chan int, 3)

func main() {
    for _, w := range work {
        go func(w func()) {
            limit <- 1
            w()
            <-limit
        }(w)
    }
    select{}
}
</code>```

I understand what this function is supposed to do – limit concurrency to 3 goroutines at any time – but I don't understand what the final select{} does. I expect this is some way to keep main alive until all goroutines have finished running, but I can't really say for sure.

What happens in an empty select?

答: In generally, select{} is used for infinite loop.

Title: What does select{} do?

Body:
Reading The Go Memory Model, I fell on this code snippet.

var limit = make(chan int, 3)

func main() {
    for _, w := range work {
        go func(w func()) {
            limit <- 1
            w()
            <-limit
        }(w)
    }
    select{}
}

I understand what this function is supposed to do – limit concurrency to 3 goroutines at any time – but I don't understand what the final select{} does. I expect this is some way to keep main alive until all goroutines have finished running, but I can't really say for sure.

What happens in an empty select?


问:
Scala: delay code bloc execution or cancel it
I'm pretty new to Scala and have a background in Java.

The problem I'm facing is that I'd like to execute a function after 5 minutes. And also be able to cancel this at any time.

In java I would basically use TimerTask, and set it to 5 min. If I would like to cancel, I just call cancel method. The nice thing is, I can use that Java class in Scala. But as I'm still learning Scala, I'm just wondering if I'm missing any better way of accomplishing that in a better way. I ran into Future and Await.result Scala classes, but I'm having a hard time figuring it out.

Any advices?

答:
Typically, if you are using some kind of a framework, it would provide its own abstraction to deal with scheduled tasks. Finagle has a Timer class, based on netty's HashedWheelTimer for example, Akka has Scheduler, etc.
(It is a good idea to use the same scheduling framework throughout the entire application, because that allows for a more efficient use of resources).

If you are just writing "vanilla" scala code without any framework, there is nothing wrong with just using TimerTask directly or, perhaps, make a little wrapper around it, so that it is not as awkward to use in scala code:

```<code>class FutureTask[T](f: => Future[T]) extends TimerTask {
  val promise = Promise[T]()
  def run(): Unit = promise.completeWith(f)
  override def cancel() = {
     val result = super.cancel
     if(result) promise.complete(Failure(new CancellationException))
     result
  }
}

object FutureTask {
   implicit def toFuture[T](task: FutureTask[T]) = task.promise.future

   def scheduleFlat[T](when: Duration)(f: => Future[T])(implicit timer: Timer = defaultTimer): FutureTask[T] = {
     val task = new FutureTask(f)
     timer.schedule(task, when.toMillis)
     task
   }

   def schedule[T](when: Duration)(f: => T)(implicit timer: Timer = defaultTimer, ctx: ExecutionContext): FutureTask[T] =
     scheduleFlat(when)(Future(f))(timer)

   val defaultTimer = new java.util.Timer(true)
}
</code>```

Now you can do things like:

```<code>val someTask = FutureTask
  .schedule(5 seconds) { println("Hello!") }
someTask.onComplete { result => println("Completed with " + result) }
someTask.cancel
Await.result(someTask, 2 seconds)
</code>```

etc.

Body:
Typically, if you are using some kind of a framework, it would provide its own abstraction to deal with scheduled tasks. Finagle has a Timer class, based on netty's HashedWheelTimer for example, Akka has Scheduler, etc.
(It is a good idea to use the same scheduling framework throughout the entire application, because that allows for a more efficient use of resources).

If you are just writing "vanilla" scala code without any framework, there is nothing wrong with just using TimerTask directly or, perhaps, make a little wrapper around it, so that it is not as awkward to use in scala code:

class FutureTask[T](f: => Future[T]) extends TimerTask {
  val promise = Promise[T]()
  def run(): Unit = promise.completeWith(f)
  override def cancel() = {
     val result = super.cancel
     if(result) promise.complete(Failure(new CancellationException))
     result
  }
}

object FutureTask {
   implicit def toFuture[T](task: FutureTask[T]) = task.promise.future

   def scheduleFlat[T](when: Duration)(f: => Future[T])(implicit timer: Timer = defaultTimer): FutureTask[T] = {
     val task = new FutureTask(f)
     timer.schedule(task, when.toMillis)
     task
   }

   def schedule[T](when: Duration)(f: => T)(implicit timer: Timer = defaultTimer, ctx: ExecutionContext): FutureTask[T] =
     scheduleFlat(when)(Future(f))(timer)

   val defaultTimer = new java.util.Timer(true)
}

Now you can do things like:

val someTask = FutureTask
  .schedule(5 seconds) { println("Hello!") }
someTask.onComplete { result => println("Completed with " + result) }
someTask.cancel
Await.result(someTask, 2 seconds)

etc.


问:
Why a same SQL query from Datagrip and embeded in Python code in SQL different have outputs?
I get two different outputs whether the query is made on Datagrip from pure SQL or on Jupyter with an SQL query nested in some Python code.

The query is a COUNT of specific states from several group of users.

Here are the group of user for this case :

```<code>                              ids
grupos
0       [160, 161, 365, 386, 471]
1                      [296, 306]
</code>```

The table in my database is like this :

The code :

From Jupyter :

```<code>for i, ids in enumerate(res['ids']):
    cur.execute("""SELECT COUNT(swipe.eclipse_id),
    subscriber_hashtag.hashtag_id
    FROM subscriber_hashtag
    INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
    LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
    WHERE (swipe.state= 3 OR swipe.state = 6 or swipe.state=9) AND subscriber_hashtag.subscriber_id in %s
    GROUP BY subscriber_hashtag.hashtag_id
        ORDER BY COUNT(swipe.eclipse_id) DESC;""",
    (tuple(res.iloc[i]['ids']),))

n = cur.fetchall()
listado = [{"count": elem[0], "eclipse_id": elem[1]} for elem in n]
</code>```

From Datagrip :

I have to separate the queries, otherwise it mixed the results.

```<code>SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
  INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
  LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
  WHERE (swipe.state= 3 OR swipe.state = 6 or swipe.state=9) AND subscriber_hashtag.subscriber_id = 160 OR subscriber_hashtag.subscriber_id = 161 OR subscriber_hashtag.subscriber_id = 365 OR subscriber_hashtag.subscriber_id = 386 OR subscriber_hashtag.subscriber_id = 471 OR subscriber_hashtag.subscriber_id = 499
    GROUP BY subscriber_hashtag.hashtag_id
      ORDER BY COUNT(swipe.eclipse_id) DESC;
</code>```

Then

```<code>SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
  INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
  LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
  WHERE (swipe.state= 3 OR swipe.state = 6 or swipe.state=9) AND subscriber_hashtag.subscriber_id = 296 OR subscriber_hashtag.subscriber_id = 306
    GROUP BY subscriber_hashtag.hashtag_id
      ORDER BY COUNT(swipe.eclipse_id) DESC;
</code>```

Outputs :

From Jupyter :

```<code>[(1500L, 996), (1185L, 592), (480L, 1214), (432L, 329), (375L, 398), (306L, 357), (300L, 473), (288L, 325), (225L, 322), (207L, 321), (207L, 1385), (195L, 1445), (180L, 1049), (108L, 334), (105L, 1183), (90L, 387), (81L, 324), (75L, 617), (72L, 379), (63L, 1331), (54L, 2546), (54L, 2545), (48L, 961), (48L, 962), (45L, 1382), (30L, 1432), (30L, 1429), (27L, 1334), (24L, 1128), (18L, 1376), (18L, 386), (18L, 1345), (18L, 1335), (9L, 1354), (9L, 1356), (9L, 1355), (9L, 1357), (9L, 1361), (9L, 1364), (9L, 1374), (9L, 1375), (9L, 1373)]
</code>```

From Datagrip :

You can see there is nothing in common between the two kind of outputs :

First query on [160, 161, 365, 386, 471]:

```<code>3000    397
2967    321
2352    329
2233    960
2000    392
1975    685
1896    337
1536    529
637 328
553 704
240 2545
240 2546
237 652
196 758
196 573
147 483
98  584
98  450
98  448
79  2549
79  2554
79  2552
79  2553
79  2551
79  2550
58  1376
56  428
49  451
49  759
49  449
49  760
34  2580
32  325
29  2547
29  425
25  322
13  594
12  334
9   427
6   323
3   347
3   595
3   345
1   521
1   333
</code>```

Second query on [296, 306]:

```<code>6600    996
5214    592
2880    329
2112    1214
1920    325
1650    398
1500    322
1380    321
1380    1385
858 1445
792 1049
720 334
600 387
540 324
480 379
462 1183
420 1331
360 2546
360 2545
330 617
306 357
300 473
300 1382
180 1334
132 1432
132 1429
120 386
120 1335
120 1376
120 1345
60  1364
60  1374
60  1356
60  1357
60  1355
60  1361
60  1354
60  1375
60  1373
48  962
48  961
24  1128
</code>```

答:
Essentially it is an SQL logic issue in the mix of AND and OR in WHERE clause. In your DataGrip you need to wrap all the OR clauses in parentheses to replicate the Python version with one contained IN() clause. Below two statements should yield same results:

DataGrip adjusted SQL

SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag
  ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe
  ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE (swipe.state= 3 OR swipe.state = 6 OR swipe.state=9) AND
      (subscriber_hashtag.subscriber_id = 160 OR
       subscriber_hashtag.subscriber_id = 161 OR
       subscriber_hashtag.subscriber_id = 365 OR
       subscriber_hashtag.subscriber_id = 386 OR
       subscriber_hashtag.subscriber_id = 471 OR
       subscriber_hashtag.subscriber_id = 499)
GROUP BY subscriber_hashtag.hashtag_id
ORDER BY COUNT(swipe.eclipse_id) DESC;
```

<p><strong>Python</strong> rendered SQL</p>

<pre class="lang-sql prettyprint-override"><code>SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag
  ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe
  ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE (swipe.state= 3 OR swipe.state = 6 OR swipe.state=9) AND
      subscriber_hashtag.subscriber_id IN (160,161,365,386,471,499)
GROUP BY subscriber_hashtag.hashtag_id
ORDER BY COUNT(swipe.eclipse_id) DESC;
</code>```

Body:
I get two different outputs whether the query is made on Datagrip from pure SQL or on Jupyter with an SQL query nested in some Python code.

The query is a COUNT of specific states from several group of users.

Here are the group of user for this case :

                              ids
grupos
0       [160, 161, 365, 386, 471]
1                      [296, 306]

The table in my database is like this :

The code :

From Jupyter :

for i, ids in enumerate(res['ids']):
    cur.execute("""SELECT COUNT(swipe.eclipse_id),
    subscriber_hashtag.hashtag_id
    FROM subscriber_hashtag
    INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
    LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
    WHERE (swipe.state= 3 OR swipe.state = 6 or swipe.state=9) AND subscriber_hashtag.subscriber_id in %s
    GROUP BY subscriber_hashtag.hashtag_id
        ORDER BY COUNT(swipe.eclipse_id) DESC;""",
    (tuple(res.iloc[i]['ids']),))

n = cur.fetchall()
listado = [{"count": elem[0], "eclipse_id": elem[1]} for elem in n]

From Datagrip :

I have to separate the queries, otherwise it mixed the results.

SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
  INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
  LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
  WHERE (swipe.state= 3 OR swipe.state = 6 or swipe.state=9) AND subscriber_hashtag.subscriber_id = 160 OR subscriber_hashtag.subscriber_id = 161 OR subscriber_hashtag.subscriber_id = 365 OR subscriber_hashtag.subscriber_id = 386 OR subscriber_hashtag.subscriber_id = 471 OR subscriber_hashtag.subscriber_id = 499
    GROUP BY subscriber_hashtag.hashtag_id
      ORDER BY COUNT(swipe.eclipse_id) DESC;

Then

SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id  FROM subscriber_hashtag
  INNER JOIN eclipse_hashtag ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
  LEFT OUTER JOIN swipe ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
  WHERE (swipe.state= 3 OR swipe.state = 6 or swipe.state=9) AND subscriber_hashtag.subscriber_id = 296 OR subscriber_hashtag.subscriber_id = 306
    GROUP BY subscriber_hashtag.hashtag_id
      ORDER BY COUNT(swipe.eclipse_id) DESC;

Outputs :

From Jupyter :

[(1500L, 996), (1185L, 592), (480L, 1214), (432L, 329), (375L, 398), (306L, 357), (300L, 473), (288L, 325), (225L, 322), (207L, 321), (207L, 1385), (195L, 1445), (180L, 1049), (108L, 334), (105L, 1183), (90L, 387), (81L, 324), (75L, 617), (72L, 379), (63L, 1331), (54L, 2546), (54L, 2545), (48L, 961), (48L, 962), (45L, 1382), (30L, 1432), (30L, 1429), (27L, 1334), (24L, 1128), (18L, 1376), (18L, 386), (18L, 1345), (18L, 1335), (9L, 1354), (9L, 1356), (9L, 1355), (9L, 1357), (9L, 1361), (9L, 1364), (9L, 1374), (9L, 1375), (9L, 1373)]

From Datagrip :

You can see there is nothing in common between the two kind of outputs :

First query on [160, 161, 365, 386, 471]:

3000    397
2967    321
2352    329
2233    960
2000    392
1975    685
1896    337
1536    529
637 328
553 704
240 2545
240 2546
237 652
196 758
196 573
147 483
98  584
98  450
98  448
79  2549
79  2554
79  2552
79  2553
79  2551
79  2550
58  1376
56  428
49  451
49  759
49  449
49  760
34  2580
32  325
29  2547
29  425
25  322
13  594
12  334
9   427
6   323
3   347
3   595
3   345
1   521
1   333

Second query on [296, 306]:

6600    996
5214    592
2880    329
2112    1214
1920    325
1650    398
1500    322
1380    321
1380    1385
858 1445
792 1049
720 334
600 387
540 324
480 379
462 1183
420 1331
360 2546
360 2545
330 617
306 357
300 473
300 1382
180 1334
132 1432
132 1429
120 386
120 1335
120 1376
120 1345
60  1364
60  1374
60  1356
60  1357
60  1355
60  1361
60  1354
60  1375
60  1373
48  962
48  961
24  1128

Body:
Essentially it is an SQL logic issue in the mix of AND and OR in WHERE clause. In your DataGrip you need to wrap all the OR clauses in parentheses to replicate the Python version with one contained IN() clause. Below two statements should yield same results:

DataGrip adjusted SQL

SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag
  ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe
  ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE (swipe.state= 3 OR swipe.state = 6 OR swipe.state=9) AND
      (subscriber_hashtag.subscriber_id = 160 OR
       subscriber_hashtag.subscriber_id = 161 OR
       subscriber_hashtag.subscriber_id = 365 OR
       subscriber_hashtag.subscriber_id = 386 OR
       subscriber_hashtag.subscriber_id = 471 OR
       subscriber_hashtag.subscriber_id = 499)
GROUP BY subscriber_hashtag.hashtag_id
ORDER BY COUNT(swipe.eclipse_id) DESC;

Python rendered SQL

SELECT COUNT(swipe.eclipse_id), subscriber_hashtag.hashtag_id
FROM subscriber_hashtag
INNER JOIN eclipse_hashtag
  ON eclipse_hashtag.hashtag_id = subscriber_hashtag.hashtag_id
LEFT OUTER JOIN swipe
  ON subscriber_hashtag.subscriber_id = swipe.subscriber_id
WHERE (swipe.state= 3 OR swipe.state = 6 OR swipe.state=9) AND
      subscriber_hashtag.subscriber_id IN (160,161,365,386,471,499)
GROUP BY subscriber_hashtag.hashtag_id
ORDER BY COUNT(swipe.eclipse_id) DESC;


答:
You have to stash the files

git add . Add stuff like you normally would

git stash stores it for later

git checkout main do your work

git commit commit your changes in main branch

git checkout your_branch after you're done with that branch go back

git stash pop brings back your work

Title: Git: with uncommited work, how to make changes in another branch and come back?

Body:
My team is using a very simple Git workflow. Everybody develops in the same branch. I'd like to know which are the series of commands I should do when I'm in the middle of the work and need to fix a bug.

Here is my situation:

Unpushed commited changes in my local master branch

Uncommited modified files

need to fix a bug in origin/master branch

I don't have another branch attached to master

need to push just these files that fix the problem

go back to work

Se that I'm working in the same branch of my coworkers.

Some users pointed that git stash would solve it and so this is a duplicate question. I dispute it, since I didn't even know that this feature existed. The feature solves my problem, but I believe the question is valid since I ask it from another point of view.