问:
Javascript setTimeout function call with event argument?
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

```<code>function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}
</code>```

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

答:
Try:

```<code>function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(function(){checkPos(e);}, 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
}
</code>```

EDIT due to OP comments..

To have access to an updated event each time checkPos is fired:

```<code>var myNamespace = {};

$('body').mousemove(function(e) {
    myNamespace.mouseEvent = e;
});

function checkPos() {
    doSomethingWith(myNamespace.mouseEvent);
}

timerID = setInterval(checkPos, 500);
</code>```

Body:
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

Body:
Try:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(function(){checkPos(e);}, 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
}

EDIT due to OP comments..

To have access to an updated event each time checkPos is fired:

var myNamespace = {};

$('body').mousemove(function(e) {
    myNamespace.mouseEvent = e;
});

function checkPos() {
    doSomethingWith(myNamespace.mouseEvent);
}

timerID = setInterval(checkPos, 500);


来源: stackexchange

问:
creating a random background color in SASS
I am attempting to have a rollover effect have 1-3 different colors in Sass. How would I do this? Here's my code so far..

```<code>input[type=submit] {
    font-size:1.3em;
    padding:5px;
    font-family:$paragraphFont;
    width:400px;
    border:1px solid #888;
    box-sizing:border-box;
    margin-top:15px;
    cursor:pointer;
    transition:background-color .2s ease-in-out;

    &:hover {
        cursor:pointer;
        background-color:#3cde77;
    }
}

<form>
    <p>Name:</p><input type="text" />
    <p>Email:</p><input type="text" />
    <p>Message:</p><textarea></textarea>
    <input type="submit" value =" Send Message" />
</form>
</code>```

I image you could use the random() function somehow and assign my colors to a number but I don't know how.

Any thoughts guys?

答:
This is not a complete solution, and I'm sure it's not a good solution, but it is a pure CSS solution: http://codepen.io/anon/pen/oZJqxR

The idea is that you have your button constantly cycling background colors with a CSS keyframe animation, but hidden behind a mask. When you hover, the mask is removed and the animation is paused, giving you a 'frozen' color that is picked based on where the cycle is when your mouse enters the button.

HTML:

```<code><button><span>Hover me</span></button>
</code>```

The CSS

```<code>button {
  padding: 0.5rem 2rem;
  border: 1px solid #CCC;
  font-size: 1.5rem;
  background: pink;
  position: relative;
  -webkit-animation: cycle 1s steps(3) infinite;
  animation: cycle 1s steps(3) infinite;
}
button:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #DDD;
}
button span {
  position: relative;
  z-index: 1;
}
button:hover {
  -webkit-animation-play-state: paused;
  animation-play-state: paused;
}
button:hover:after {
  display: none;
}

@keyframes cycle {
  50% {
    background: blue;
  }
  100% {
    background: green;
  }
}
</code>```

This currently isn't picking cleanly between the 3 stated colors - some intermediate colors are shown. This is down to the keyframe animation and the steps declaration on the button - I'm sure it can be done, but it requires fine-tuning.

Last caveat - this is way more resource intensive than just picking a colour with javascript - it would get very heavy if you had more than a couple of these elements on a page at once.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to have a rollover effect have 1-3 different colors in Sass. How would I do this? Here's my code so far..

input[type=submit] {
    font-size:1.3em;
    padding:5px;
    font-family:$paragraphFont;
    width:400px;
    border:1px solid #888;
    box-sizing:border-box;
    margin-top:15px;
    cursor:pointer;
    transition:background-color .2s ease-in-out;

    &:hover {
        cursor:pointer;
        background-color:#3cde77;
    }
}

<form>

Name:
<input type="text" />

Email:
<input type="text" />

Message:
<textarea></textarea>
    <input type="submit" value =" Send Message" />
</form>

I image you could use the random() function somehow and assign my colors to a number but I don't know how.

Any thoughts guys?

Body:
This is not a complete solution, and I'm sure it's not a good solution, but it is a pure CSS solution: http://codepen.io/anon/pen/oZJqxR

The idea is that you have your button constantly cycling background colors with a CSS keyframe animation, but hidden behind a mask. When you hover, the mask is removed and the animation is paused, giving you a 'frozen' color that is picked based on where the cycle is when your mouse enters the button.

HTML:

<button><span>Hover me</span></button>

The CSS

button {
  padding: 0.5rem 2rem;
  border: 1px solid #CCC;
  font-size: 1.5rem;
  background: pink;
  position: relative;
  -webkit-animation: cycle 1s steps(3) infinite;
  animation: cycle 1s steps(3) infinite;
}
button:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #DDD;
}
button span {
  position: relative;
  z-index: 1;
}
button:hover {
  -webkit-animation-play-state: paused;
  animation-play-state: paused;
}
button:hover:after {
  display: none;
}

@keyframes cycle {
  50% {
    background: blue;
  }
  100% {
    background: green;
  }
}

This currently isn't picking cleanly between the 3 stated colors - some intermediate colors are shown. This is down to the keyframe animation and the steps declaration on the button - I'm sure it can be done, but it requires fine-tuning.

Last caveat - this is way more resource intensive than just picking a colour with javascript - it would get very heavy if you had more than a couple of these elements on a page at once.


问:
Avoid looping to get one particular column of values from Set<Entity> in Java
I have a code snippet in Java as follows:

```<code>Set<BookDO> bookSet = shopDO.getBooks();
    Collection<String> bookCollection = null;
    if (bookSet != null && !bookSet .isEmpty()) {
      bookCollection = new ArrayList<String>();
      for (BookDO book : bookSet) {
        bookCollection .add(book.getName());
      }
    }
</code>```

Finally I want the only Collection of book names to pass it to an API which displays the output.

Is it possible to avoid the for loop to improve performance ?

答:
If Java8 - use lambdas. They are compiled differently and good for JIT - this construction will act faster.

```<code>Collection<String> bookCollection = bookSet.stream().map(BookDO::getName()).collect(toSet())
</code>```

You also may store map instead of set if the collection is not changing.
bookMap = new HashMap
You'll have to create map only once (HasSet uses HashMap in it's implementation, so there will be no performance or memory issues). When you need to get books you call:

```<code>bookMap.keySet();
</code>```

When names:

```<code>bookMap.values();
</code>```

Body:
I have a code snippet in Java as follows:

Set<BookDO> bookSet = shopDO.getBooks();
    Collection<String> bookCollection = null;
    if (bookSet != null && !bookSet .isEmpty()) {
      bookCollection = new ArrayList<String>();
      for (BookDO book : bookSet) {
        bookCollection .add(book.getName());
      }
    }

Finally I want the only Collection of book names to pass it to an API which displays the output.

Is it possible to avoid the for loop to improve performance ?

Body:
If Java8 - use lambdas. They are compiled differently and good for JIT - this construction will act faster.

Collection<String> bookCollection = bookSet.stream().map(BookDO::getName()).collect(toSet())

You also may store map instead of set if the collection is not changing.
bookMap = new HashMap
You'll have to create map only once (HasSet uses HashMap in it's implementation, so there will be no performance or memory issues). When you need to get books you call:

bookMap.keySet();

When names:

bookMap.values();


问:
JSON_ERROR when adding Symfony app
I just installed Symfony on my CentOS setup running with PHP 7.0.14. I am however having the following issue when trying to run symfony new project_name:

```<code>    PHP Notice:  Use of undefined constant JSON_ERROR_DEPTH - assumed 'JSON_ERROR_DEPTH' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_STATE_MISMATCH - assumed 'JSON_ERROR_STATE_MISMATCH' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_CTRL_CHAR - assumed 'JSON_ERROR_CTRL_CHAR' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_SYNTAX - assumed 'JSON_ERROR_SYNTAX' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_UTF8 - assumed 'JSON_ERROR_UTF8' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Fatal error:  Uncaught Error: Call to undefined function json_decode() in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php:142
Stack trace:
#0 phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Message/Response.php(145): GuzzleHttp\Utils::jsonDecode('{"lts":"2.8.18"...', true, 512, 0)
#1 phar:///usr/local/bin/symfony/src/Symfony/Installer/NewCommand.php(127): GuzzleHttp\Message\Response->json()
#2 phar:///usr/local/bin/symfony/src/Symfony/Installer/NewCommand.php(65): Symfony\Installer\NewCommand->checkSymfonyVersionIsInstallable()
#3 phar:///usr/local/bin/symfony/vendor/symfony/console/Command/Command.php(259): Symfony\Installer\NewCommand->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#4 phar:///usr/local/bin/symfony/vendor/symfony/console/Application.php(878): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#5 phar:///us in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 142
</code>```

I've checked around the web for answers, and have already tried setting phar.readonly = Off in php.ini

答: Hassan was right, I was missing the json-extension. Fixed it by running sudo yum install php70u-json

Title: JSON_ERROR when adding Symfony app

Body:
I just installed Symfony on my CentOS setup running with PHP 7.0.14. I am however having the following issue when trying to run symfony new project_name:

    PHP Notice:  Use of undefined constant JSON_ERROR_DEPTH - assumed 'JSON_ERROR_DEPTH' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_STATE_MISMATCH - assumed 'JSON_ERROR_STATE_MISMATCH' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_CTRL_CHAR - assumed 'JSON_ERROR_CTRL_CHAR' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_SYNTAX - assumed 'JSON_ERROR_SYNTAX' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Notice:  Use of undefined constant JSON_ERROR_UTF8 - assumed 'JSON_ERROR_UTF8' in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 134
PHP Fatal error:  Uncaught Error: Call to undefined function json_decode() in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php:142
Stack trace:
#0 phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Message/Response.php(145): GuzzleHttp\Utils::jsonDecode('{"lts":"2.8.18"...', true, 512, 0)
#1 phar:///usr/local/bin/symfony/src/Symfony/Installer/NewCommand.php(127): GuzzleHttp\Message\Response->json()
#2 phar:///usr/local/bin/symfony/src/Symfony/Installer/NewCommand.php(65): Symfony\Installer\NewCommand->checkSymfonyVersionIsInstallable()
#3 phar:///usr/local/bin/symfony/vendor/symfony/console/Command/Command.php(259): Symfony\Installer\NewCommand->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#4 phar:///usr/local/bin/symfony/vendor/symfony/console/Application.php(878): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#5 phar:///us in phar:///usr/local/bin/symfony/vendor/guzzlehttp/guzzle/src/Utils.php on line 142

I've checked around the web for answers, and have already tried setting phar.readonly = Off in php.ini


问:
java unable to find the error to print a prime number
This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong   </p>

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
    public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
    public static Scanner input = new Scanner(System.in);
    public static void main(String args[])
    {
        int inputs = 4;
        input(inputs);
        for(int i = 0; i < inputs; i++){
            for(int j = 0+i; j < inputs; j++){
                if(i != j)
                    System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
            }
        }   }

    public static int isPrime (int sumPair)
    {
        boolean primeVal =true ;
        if(sumPair < 2)
            primeVal= false;
        else if(sumPair ==2)
            primeVal=true;
        else if (sumPair % 2 == 0)
            primeVal = false;
        else
        {
            int stop = (int)Math.sqrt(sumPair);
            for (int d = 3; d <= stop && primeVal; d = d + 2)
            {
                if (sumPair % d == 0)
                    primeVal = false;
            }
        }
        return(sumPair);
    }

    public static void input(int inputNumbers)
    {
        while(numbers.size() < inputNumbers){ // while there is more inputs needed
            System.out.print("Enter a positive integer: ");
            int num = input.nextInt();
            if(num > 0) // if the input is valid
                numbers.add(num);
            else // if the input is not valid
                while (num <= 0) { // while the input is not valid
                    System.out.print("Enter a positive integer: ");
                    num = input.nextInt(); // get the next int if it wasn't valid
                    if(num > 0) { // if the input gets valid
                        numbers.add(num);
                    }
                }
            System.out.println("Thank you.");
        }
    }

    public static int sumPair(int num1, int num2)
    {
        return num1 + num2;
    }

}
</code>```

答:
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value.  Try this instead:

```<code>public static boolean isPrime (int sumPair) {
    boolean primeVal = true;
    if (sumPair < 2 || sumPair % 2 == 0) {
        primeVal = false;
    }
    else {
        int stop = (int)Math.sqrt(sumPair);
        for (int d=3; d <= stop; d += 2) {
            if (sumPair % d == 0) {
                primeVal = false;
                break;
            }
        }
    }
    return primeVal;
}
</code>```

Use this main() method:

```<code>public static void main (String args[]) {
    int inputs = 4;
    input(inputs);
    for (int i=0; i < inputs-1; i++) {
        for (int j=i+1; j < inputs; j++) {
            boolean prime = isPrime(numbers.get(i) + numbers.get(j));
            if (prime) {
                System.out.println(numbers.get(i) + " + " + numbers.get(j));
            }
        }
    }
}
</code>```

Body:
This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
    public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
    public static Scanner input = new Scanner(System.in);
    public static void main(String args[])
    {
        int inputs = 4;
        input(inputs);
        for(int i = 0; i < inputs; i++){
            for(int j = 0+i; j < inputs; j++){
                if(i != j)
                    System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
            }
        }   }

    public static int isPrime (int sumPair)
    {
        boolean primeVal =true ;
        if(sumPair < 2)
            primeVal= false;
        else if(sumPair ==2)
            primeVal=true;
        else if (sumPair % 2 == 0)
            primeVal = false;
        else
        {
            int stop = (int)Math.sqrt(sumPair);
            for (int d = 3; d <= stop && primeVal; d = d + 2)
            {
                if (sumPair % d == 0)
                    primeVal = false;
            }
        }
        return(sumPair);
    }

    public static void input(int inputNumbers)
    {
        while(numbers.size() < inputNumbers){ // while there is more inputs needed
            System.out.print("Enter a positive integer: ");
            int num = input.nextInt();
            if(num > 0) // if the input is valid
                numbers.add(num);
            else // if the input is not valid
                while (num <= 0) { // while the input is not valid
                    System.out.print("Enter a positive integer: ");
                    num = input.nextInt(); // get the next int if it wasn't valid
                    if(num > 0) { // if the input gets valid
                        numbers.add(num);
                    }
                }
            System.out.println("Thank you.");
        }
    }

    public static int sumPair(int num1, int num2)
    {
        return num1 + num2;
    }

}

Body:
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value.  Try this instead:

public static boolean isPrime (int sumPair) {
    boolean primeVal = true;
    if (sumPair < 2 || sumPair % 2 == 0) {
        primeVal = false;
    }
    else {
        int stop = (int)Math.sqrt(sumPair);
        for (int d=3; d <= stop; d += 2) {
            if (sumPair % d == 0) {
                primeVal = false;
                break;
            }
        }
    }
    return primeVal;
}

Use this main() method:

public static void main (String args[]) {
    int inputs = 4;
    input(inputs);
    for (int i=0; i < inputs-1; i++) {
        for (int j=i+1; j < inputs; j++) {
            boolean prime = isPrime(numbers.get(i) + numbers.get(j));
            if (prime) {
                System.out.println(numbers.get(i) + " + " + numbers.get(j));
            }
        }
    }
}


问:
ng-if not working with simple javascript
ng-if is not working when I change the values through simple javascript function.My function is getting called but the changes in values cannot be seen in view. Please refer below code.

HTML

```<code><div id="span" ng-app='MyModule' ng-cloak ng-controller="MyController">

<div ng-if="!bool">
  This is for true
</div>
<div ng-if="bool">
  This is False
</div>
{{bool}}
<br>
<input type="submit" ng-click = "myfunction('test')" value="ng-if button">
</div>
<input type="submit" onClick = "check1()" value="simple JS button">
</code>```

JS

```<code>angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.bool = true;
$scope.myfunction = function (data) {
    $scope.bool = !$scope.bool;
};
});
function check1() {
    angular.element(document.getElementById('span')).scope().myfunction('test');
}
</code>```

When I use ng-click button it changes value of bool changes, but same doesn't happens with simple JS button . Actually I am implementing Angular in a page that already uses jQuery, so I need to use simple JS button.

JS Fiddle : JS Fiddle

答:
At first, ng-click is able to parse an angular expression.

Second, it handles the reference to the current scope and performs a call to $scope.$apply to notify any watchers to update. If you would add a call to angular.element(document.getElementById('span')).scope().$apply() in your function, it should work as expected.

Body:
ng-if is not working when I change the values through simple javascript function.My function is getting called but the changes in values cannot be seen in view. Please refer below code.

HTML

  This is for true

  This is False

{{bool}}

<input type="submit" ng-click = "myfunction('test')" value="ng-if button">

<input type="submit" onClick = "check1()" value="simple JS button">

JS

angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.bool = true;
$scope.myfunction = function (data) {
    $scope.bool = !$scope.bool;
};
});
function check1() {
    angular.element(document.getElementById('span')).scope().myfunction('test');
}

When I use ng-click button it changes value of bool changes, but same doesn't happens with simple JS button . Actually I am implementing Angular in a page that already uses jQuery, so I need to use simple JS button.

JS Fiddle : JS Fiddle


问:
ExtJS 6 plugin.rowwidget Resize row body component on grid resize
I have a grid with Ext.grid.plugin.RowWidget. When grid is resized expanded row body components remains with origin width. How I can fix this issue?

As temporary solution I added resize event handler as follows

```<code>            listeners: {
                resize: function (grid) {
                    Ext.each(grid.query('characterPanel'), function (rowBodyComponent) {
                        //if(rowBodyComponent.isVisible()) does not work
                        //rowBodyComponent.updateLayout(); does not work
                        rowBodyComponent.setWidth('100%');
                    });
                }
            }
</code>```

but it seems bad solution for me. Also, it has an issue - all row body components resized regardess of its visibility and in case of many collapsed (after expand) rows may affect performance of my app.

Any ideas?

Here is simple fiddle illustrating my problem and what I've tried already.

答:
Add an ID to the plugin:

```<code>{
    ptype: 'rowwidget',
    id: 'rowwidget',
    widget: {
        xtype: 'characterPanel',
        bind: {},
    }
}
</code>```

then you can get the plugin by the given id:

```<code>grid.getPlugin('rowwidget');
</code>```

This plugin holds a property which is called recordsExpanded.
This contains all internalIds of the expanded records and the current state of the expansion aswell.

In your onResize-function you can do this:

```<code>let plugin = grid.getPlugin('rowwidget');
if (plugin && plugin.recordsExpanded) {
    for (let internalId in plugin.recordsExpanded) {
        let record = grid.store.getByInternalId(internalId);
        if (!Ext.isEmpty(record)) {
            plugin.getWidget(grid.getView(), record).setWidth('100%');
        }
    }
}
</code>```

But you should add a delay (at least of 1) to the function call to ensure the resizing is done.

```<code>listeners: {
    resize: {
        delay: 1,
        fn: function() {
            // do stuff
        }
    }
}
</code>```

Without the delay, the widget sometimes does not resize after making the row bigger.

Body:
I have a grid with Ext.grid.plugin.RowWidget. When grid is resized expanded row body components remains with origin width. How I can fix this issue?

As temporary solution I added resize event handler as follows

            listeners: {
                resize: function (grid) {
                    Ext.each(grid.query('characterPanel'), function (rowBodyComponent) {
                        //if(rowBodyComponent.isVisible()) does not work
                        //rowBodyComponent.updateLayout(); does not work
                        rowBodyComponent.setWidth('100%');
                    });
                }
            }

but it seems bad solution for me. Also, it has an issue - all row body components resized regardess of its visibility and in case of many collapsed (after expand) rows may affect performance of my app.

Any ideas?

Here is simple fiddle illustrating my problem and what I've tried already.

Body:
Add an ID to the plugin:

{
    ptype: 'rowwidget',
    id: 'rowwidget',
    widget: {
        xtype: 'characterPanel',
        bind: {},
    }
}

then you can get the plugin by the given id:

grid.getPlugin('rowwidget');

This plugin holds a property which is called recordsExpanded.
This contains all internalIds of the expanded records and the current state of the expansion aswell.

In your onResize-function you can do this:

let plugin = grid.getPlugin('rowwidget');
if (plugin && plugin.recordsExpanded) {
    for (let internalId in plugin.recordsExpanded) {
        let record = grid.store.getByInternalId(internalId);
        if (!Ext.isEmpty(record)) {
            plugin.getWidget(grid.getView(), record).setWidth('100%');
        }
    }
}

But you should add a delay (at least of 1) to the function call to ensure the resizing is done.

listeners: {
    resize: {
        delay: 1,
        fn: function() {
            // do stuff
        }
    }
}

Without the delay, the widget sometimes does not resize after making the row bigger.


问:
Java Read a file and create an object for each corresponding row
I have a CSV file that I am reading from. I have created a constructor with six arguments for initialising the six fields and a public string method to convert a string into the format I need.

```<code>public Hill(int number, String name, String countyName, double height, double latitude, double longitude) {
    this.number = number;
    this.name = name;
    this.countyName = countyName;
    this.height = height;
    this.latitude = latitude;
    this.longitude = longitude;
}
</code>```

Now what I am trying to achieve is after opening the file and reading it, it creates the corresponding object and then to return the list of the items.

I was given an inital method of public static List<Hill> readHills()

I have commented out a line which i tried to create a new object from simply because I wasn't sure if I was doing it right, so i just printed out as a test to see what my code was doing and it seems that the new object line is redundant.
Currently my code is:

```<code>public static List<Hill> readHills() {
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/TOSHIBA/Desktop/hills.csv"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Scanner finalFileName = fileName;
    List<Hill> list = new ArrayList<Hill>() {
        {
                for(int i = 0; i < 21; i++) {
                    String line = finalFileName.nextLine();
                    String[] splitted = line.split(",");
                    //add(new Hill(1, "", "", 100, 100, 100));
                    System.out.println(Arrays.toString(splitted));
                }

            }
    };
    return list;
}
</code>```

In the code where I create the object I put a sample value but technically I want the 6 fields of the new object to be from the file I read. If i try adding the field names, i get a red line saying Non static method cannot be referenced from a static method

Where am i going wrong? And why is my line of code useless?

I continued trying to play with the code but can't get anywhere, I think my issue is not understand the method name i have been given; i.e. Why and what does public static List<Hill> readHills() do?

I tried using Hill newHill = new Hill( int number, String name, String countyName,double height, double latitude, double longitude); but can't since I cant reference a non-static field from a static context

答:
For starters: this here

```<code>List<Hill> list = new ArrayList<Hill>() {
</code>```

is valid syntax, but not at all what you want.

Just go for:

```<code>List<Hill> list = new ArrayList<>();
</code>```

instead. What you are doing creates an anonymous inner class; and that is totally not required here; and instead leading to many of the issues you see.

Then: you have to turn your strings into the correct type:

```<code> String[] splitted = line.split(",");
</code>```

gives you an array of String objects. You have to convert those; so that you can pass them to the constructor accordingly (your constructor expects an int value as first parameter, not a String for example!)

```<code>Hill hill = new Hill(Integer.parseInt(splitted[0]), splitted[1], ...
</code>```

and so on.

And then you do:

```<code>list.add(hill);
</code>```

But the tricky part is: such parsing relies on "correct" input. So you should be prepared for all kinds of error handling.

And beyond that: unless this is homework, then do not implement your own CSV parser. Use some existing library for that (see here for ideas). You see: doing correct CSV parsing, that works with all the subtle quirks of this format is not easy. You can easily spend hours on this task; to then find that the next CSV file you work with ... contains yet another (valid!) variation of CSV input that breaks your self-written parser. (believe me, I have been there)

And finally: if such things already overburden you, then the real takeaway is: accept that you are not there yet. Step back; get back into learning mode and understand all those basic Java things.

Body:
I have a CSV file that I am reading from. I have created a constructor with six arguments for initialising the six fields and a public string method to convert a string into the format I need.

public Hill(int number, String name, String countyName, double height, double latitude, double longitude) {
    this.number = number;
    this.name = name;
    this.countyName = countyName;
    this.height = height;
    this.latitude = latitude;
    this.longitude = longitude;
}

Now what I am trying to achieve is after opening the file and reading it, it creates the corresponding object and then to return the list of the items.

I was given an inital method of public static List<Hill> readHills()

I have commented out a line which i tried to create a new object from simply because I wasn't sure if I was doing it right, so i just printed out as a test to see what my code was doing and it seems that the new object line is redundant.
Currently my code is:

public static List<Hill> readHills() {
    Scanner fileName = null;
    try {
        fileName = new Scanner(new File("C:/Users/TOSHIBA/Desktop/hills.csv"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Scanner finalFileName = fileName;
    List<Hill> list = new ArrayList<Hill>() {
        {
                for(int i = 0; i < 21; i++) {
                    String line = finalFileName.nextLine();
                    String[] splitted = line.split(",");
                    //add(new Hill(1, "", "", 100, 100, 100));
                    System.out.println(Arrays.toString(splitted));
                }

            }
    };
    return list;
}

In the code where I create the object I put a sample value but technically I want the 6 fields of the new object to be from the file I read. If i try adding the field names, i get a red line saying Non static method cannot be referenced from a static method

Where am i going wrong? And why is my line of code useless?

I continued trying to play with the code but can't get anywhere, I think my issue is not understand the method name i have been given; i.e. Why and what does public static List<Hill> readHills() do?

I tried using Hill newHill = new Hill( int number, String name, String countyName,double height, double latitude, double longitude); but can't since I cant reference a non-static field from a static context

Body:
For starters: this here

List<Hill> list = new ArrayList<Hill>() {

is valid syntax, but not at all what you want.

Just go for:

List<Hill> list = new ArrayList<>();

instead. What you are doing creates an anonymous inner class; and that is totally not required here; and instead leading to many of the issues you see.

Then: you have to turn your strings into the correct type:

 String[] splitted = line.split(",");

gives you an array of String objects. You have to convert those; so that you can pass them to the constructor accordingly (your constructor expects an int value as first parameter, not a String for example!)

Hill hill = new Hill(Integer.parseInt(splitted[0]), splitted[1], ...

and so on.

And then you do:

list.add(hill);

But the tricky part is: such parsing relies on "correct" input. So you should be prepared for all kinds of error handling.

And beyond that: unless this is homework, then do not implement your own CSV parser. Use some existing library for that (see here for ideas). You see: doing correct CSV parsing, that works with all the subtle quirks of this format is not easy. You can easily spend hours on this task; to then find that the next CSV file you work with ... contains yet another (valid!) variation of CSV input that breaks your self-written parser. (believe me, I have been there)

And finally: if such things already overburden you, then the real takeaway is: accept that you are not there yet. Step back; get back into learning mode and understand all those basic Java things.


答:
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).

You made a nice isPrime function, you should call it.

You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.

Your code should look like:

```<code>for(int i = 0; i < inputs; i++){
  for(int j = 0+i; j < inputs; j++){
    ni = numbers.get(i);
    nj = numbers.get(j);
    if(isPrime(ni+nj)){
      System.out.println(ni + " + " + nj + " = "+  (ni + nj));
    }
  }
}
</code>```

What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.

Title: java unable to find the error to print a prime number

Body:
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).

You made a nice isPrime function, you should call it.

You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.

Your code should look like:

for(int i = 0; i < inputs; i++){
  for(int j = 0+i; j < inputs; j++){
    ni = numbers.get(i);
    nj = numbers.get(j);
    if(isPrime(ni+nj)){
      System.out.println(ni + " + " + nj + " = "+  (ni + nj));
    }
  }
}

What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.


问:
cannot resolve method 'getFont(?)'
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

```<code>cannot resolve method 'getFont(?)'
</code>```

Previously I used to do the following:

```<code>Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
</code>```

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.

答: I haven't use it yet however as far as I know you can target Android O device only if you update your Android Studio to 2.4. And you need to update your SDK to latest build as well. Because as doc says getFont() available in Android O.</p>

Title: cannot resolve method 'getFont(?)'

Body:
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

cannot resolve method 'getFont(?)'

Previously I used to do the following:

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.


问:
Making a simple JSONP call to Twitchtv API?
I'm working on a FreeCodeCamp project that involves making a JSONP call to the Twitchtv API(https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api), and thought I've tried to make my code as simple and straightforward as possible: </p>

```<code>       var members =["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp",    "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
    var memberData = [];

  $.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?',    function(data) {
   console.log(data);
 });
</code>```

<p>It does not print anything. As far as I understand, the "?callback=?" portion of getJSON call makes it a JSONP request, so that shouldn't be an issue. The array of "members" isn't really in use right now, but I included it on the off chance that it's involved with the error. I'm not really sure what the issue is, any help is appreciated. </p>

答:
On the FreeCodeCamp forum you can find many informations, but I can tell you what I already know:

to see the errors on codepen it's better to use the browser console: you can't get the errors information on the codepen console (at least not using its default options).

You can't use the url "h77ps://api.twitch.tv/kraken" without having a key (details here : https://blog.twitch.tv/client-id-required-for-kraken-api-calls-afbb8e95f843). You can use instead this workaround "https://wind-bow.gomix.me/twitch-api".

last thing: I was using jQuery like you to do the project, and it worked, but it's not working anymore; I don't know exactly why, but I know I was having trouble with its pure json request. Now I fixed it using Ajax and explicitly asking for "dataType : 'jsonp'"

Body:
I'm working on a FreeCodeCamp project that involves making a JSONP call to the Twitchtv API(https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api), and thought I've tried to make my code as simple and straightforward as possible:

       var members =["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp",    "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
    var memberData = [];

  $.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?',    function(data) {
   console.log(data);
 });

It does not print anything. As far as I understand, the "?callback=?" portion of getJSON call makes it a JSONP request, so that shouldn't be an issue. The array of "members" isn't really in use right now, but I included it on the off chance that it's involved with the error. I'm not really sure what the issue is, any help is appreciated.


问:
Tkinter, make a window when certain conditions are met?
I'm trying to run a Tkinter window if the user enters a specific number, but it's not working. Here's my code:

```<code>#Import Tkinter module
from tkinter import *

ans = int (input('What is 100 x 10? '))
if ans == int ('1000'):

        #Create a window and set Geometry
        pyr = Tk()
        pyr.geometry('300x300')

        #Title window
        pyr.title("Right")

        #Set background color using hex code
        pyr.configure(background = "#32cd32")

        #Create Labels
        lbl = Label(pyr, text="Correct!", bg="#32cd32")

        # Packing
        lbl.grid(column=2, row=1)

        #Draw window and start application
        pyr.mainloop

else:
        #Create a window and set Geometry
        pyw = Tk()
        pyw.geometry('300x300')

        #Title window
        pyw.title("Wrong")

        #Set background color using hex code
        pyw.configure(background = "#ff0000")

        #Create Labels
        lbl1 = Label(pyw, text="Nope!", bg="#32cd32")

        # Packing
        lbl1.grid(column=2, row=1)

        #Draw window and start application
        pyw.mainloop()
</code>```

What happens is I enter 1000 or a different number and nothing happens. It just sits there, doesn't even print a ">>>" to show it's done. What am I doing wrong? Thanks

答:
The two main problems with your code are basically two typos:

You forgot to call the mainloop function in the "correct" case (add ())

You are using pyf instead of pyr and pyw in some places

I'd also suggest moving the window-opening stuff into a method to reduce code duplication and using isdigit to check whether the input is a number before trying to cast to int.

```<code>def open_window(title, message, color):
    pyr = Tk()
    pyr.geometry('300x300')
    pyr.title(title)
    pyr.configure(background = color)
    lbl = Label(pyr, text=message, bg=color)
    lbl.grid(column=2, row=1)
    pyr.mainloop()

ans = input('What is 100 x 10? ')
if ans.isdigit() and int(ans) == 1000:
    open_window("Right", "Correct", "#32cd32")
else:
    open_window("Wrong", "Nope", "#ff0000")
</code>```

Body:
I'm trying to run a Tkinter window if the user enters a specific number, but it's not working. Here's my code:

#Import Tkinter module
from tkinter import *

ans = int (input('What is 100 x 10? '))
if ans == int ('1000'):

        #Create a window and set Geometry
        pyr = Tk()
        pyr.geometry('300x300')

        #Title window
        pyr.title("Right")

        #Set background color using hex code
        pyr.configure(background = "#32cd32")

        #Create Labels
        lbl = Label(pyr, text="Correct!", bg="#32cd32")

        # Packing
        lbl.grid(column=2, row=1)

        #Draw window and start application
        pyr.mainloop

else:
        #Create a window and set Geometry
        pyw = Tk()
        pyw.geometry('300x300')

        #Title window
        pyw.title("Wrong")

        #Set background color using hex code
        pyw.configure(background = "#ff0000")

        #Create Labels
        lbl1 = Label(pyw, text="Nope!", bg="#32cd32")

        # Packing
        lbl1.grid(column=2, row=1)

        #Draw window and start application
        pyw.mainloop()

What happens is I enter 1000 or a different number and nothing happens. It just sits there, doesn't even print a ">>>" to show it's done. What am I doing wrong? Thanks

Body:
The two main problems with your code are basically two typos:

You forgot to call the mainloop function in the "correct" case (add ())

You are using pyf instead of pyr and pyw in some places

I'd also suggest moving the window-opening stuff into a method to reduce code duplication and using isdigit to check whether the input is a number before trying to cast to int.

def open_window(title, message, color):
    pyr = Tk()
    pyr.geometry('300x300')
    pyr.title(title)
    pyr.configure(background = color)
    lbl = Label(pyr, text=message, bg=color)
    lbl.grid(column=2, row=1)
    pyr.mainloop()

ans = input('What is 100 x 10? ')
if ans.isdigit() and int(ans) == 1000:
    open_window("Right", "Correct", "#32cd32")
else:
    open_window("Wrong", "Nope", "#ff0000")


问:
Parsing a Quickbook IIF format file
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.

The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.

When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.

How would you parse such a file?

Edit: An example

```<code>!CUST   NAME    REFNUM  TIMESTAMP   BADDR1  BADDR2  BADDR3  BADDR4  BADDR5  SADDR1  SADDR2  SADDR3  SADDR4  SADDR5  PHONE1  PHONE2  FAXNUM  CONT1   CONT2   CTYPE   TERMS   TAXABLE LIMIT   RESALENUM   REP TAXITEM NOTEPAD SALUTATION  COMPANYNAME FIRSTNAME   MIDINIT LASTNAME    CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    CUSTFLD6    CUSTFLD7    CUSTFLD8    CUSTFLD9    CUSTFLD10   CUSTFLD11   CUSTFLD12   CUSTFLD13   CUSTFLD14   CUSTFLD15   JOBDESC JOBTYPE JOBSTATUS   JOBSTART    JOBPROJEND  JOBEND  HIDDEN  DELCOUNT
CUST    St. Mark    359 1176670332  Saint Mark Catholic Church  609 W Main St   City, State Zip
!CLASS  NAME    REFNUM  TIMESTAMP   HIDDEN  DELCOUNT
!INVITEM    NAME    REFNUM  TIMESTAMP   INVITEMTYPE DESC    PURCHASEDESC    ACCNT   ASSETACCNT  COGSACCNT   QNTY    QNTY    PRICE   COST    TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND    REORDERPOINT    EXTRA   CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    DEP_TYPE    ISPASSEDTHRU    HIDDEN  DELCOUNT    USEID
INVITEM Labor   1   1119915308  SERV    Labor                                                                                0
!TIMEACT    DATE    JOB EMP ITEM    PITEM   DURATION    PROJ    NOTE    XFERTOPAYROLL   BILLINGSTATUS
TIMEACT 3/8/08  876 Development Jane Doe {Consultant}   Labor       00:15       Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names.  N   1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant}   Labor       01:00       Preparing Studio    N   1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant}   Labor       00:06       REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
    N   1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant}   Labor       01:00       Fixing Kandis's computer - replaced entire computer with similar system N   1
</code>```

答:
I did it:</p>

```<code> public DataSet parseIIF(Stream file) {
            iifSet = new DataSet();
            String fileText;

            using (StreamReader sr = new StreamReader(file)) {
                fileText = sr.ReadToEnd();
            }
            //replace line breaks with tabs
            //fileText.Replace('\n', '\t');
            fileText = fileText.Replace("\r\n", "\n");
            fileText = fileText.Replace('\r', '\n');

            //split along tabs
            string[] lines = fileText.Split('\n');

            this.createTables(lines, iifSet);
            this.fillSet(lines, iifSet);

            return iifSet;
        }

        /// <summary>
        /// Reads an array of lines and parses them into tables for the dataset
        /// </summary>
        /// <param name="lines">String Array of lines from the iif file</param>
        /// <param name="iifSet">DataSet to be manipulated</param>
        private void fillSet(string[] lines, DataSet set) {
            //CODING HORROR
            //WARNING: I will monkey with the for loop index, be prepared!
            for (int i = 0; i < lines.Length; i++) {
                if (this.isTableHeader(lines[i])) {
                    //ignore this line, tables are alread defined
                    continue;
                }
                if (lines[i] == "" || lines[i] == "\r" || lines[i] == "\n\r" || lines[i] == "\n") {
                    //ignore lines that are empty if not inside a record
                    //probably the end of the file, it always ends with a blank line break
                    continue;
                }

                if (lines[i].IndexOf(";__IMPORTED__") != -1) {
                    continue;
                    //just signifying that it's been imported by quickbook's timer before, don't need it
                }

                string line = lines[i];
                while (!isFullLine(line, set)){
                    i++;            //<--------------------------- MONKEYING done here!
                    line += lines[i];
                }
                //now, the line should be complete, we can parse it by tabs now
                this.parseRecord(line, set);
            }
        }

        private void parseRecord(string line, DataSet set) {
            if (isTableHeader(line)) {
                //we don't want to deal with headers here
                return;
            }

            String tablename = line.Split('\t')[0];
            //this just removes the first value and the line break from the last value
            String[] parameters = this.createDataRowParams(line);

            //add it to the dataset
            set.Tables[tablename].Rows.Add(parameters);
        }

        private bool isFullLine(string line, DataSet set) {
            if (isTableHeader(line)) {
                return true;    //assumes table headers won't have line breaks
            }
            int values = line.Split('\t').Length;
            string tableName = line.Split('\t')[0];
            int columns = set.Tables[tableName].Columns.Count;

            if (values < columns) {
                return false;
            } else {
                return true;
            }
        }

        private void createTables(string[] lines, DataSet set) {
            for (int index = 0; index < lines.Length; index++) {
                if (this.isTableHeader(lines[index])) {
                    set.Tables.Add(createTable(lines[index]));
                }
            }
        }

        private bool isTableHeader(string tab) {
            if (tab.StartsWith("!"))
                return true;
            else
                return false;
        }

        private bool isNewLine(string p) {
            if (p.StartsWith("!"))
                return true;
            if (iifSet.Tables[p.Split('\t')[0]] != null)    //that little mess there grabs the first record in the line, sorry about the mess
                return true;
            return false;
        }

    private DataTable createTable(string line) {
        String[] values = line.Split('\t');

        //first value is always the title
        //remove the ! from it
        values[0] = values[0].Substring(1);     //remove the first character
        DataTable dt = new DataTable(values[0]);
        values[0] = null;   //hide first title so it doesn't get used, cheaper than resetting array
        foreach (String name in values) {
            if (name == null || name == "")
                continue;
            DataColumn dc = new DataColumn(name, typeof(String));
            try {
                dt.Columns.Add(dc);
            } catch (DuplicateNameException) {
                //odd
                dc = new DataColumn(name + "_duplicateCol" + dt.Columns.Count.ToString());
                dt.Columns.Add(dc);
                //if there is a triple, just throw it
            }
        }

        return dt;
    }

   private string getTableName(string line) {
        String[] values = line.Split('\t');

        //first value is always the title
        if(values[0].StartsWith("!")){
            //remove the ! from it
            values[0] = values[0].Substring(1);     //remove the first character
        }
        return values[0];
    }

    private string[] createDataRowParams(string line) {
        string[] raw = line.Split('\t');
        string[] values = new string[raw.Length - 1];

        //copy all values except the first one
        for (int i = 0; i < values.Length; i++) {
            values[i] = raw[i + 1];
        }

        //remove last line break from the record
        if (values[values.Length - 1].EndsWith("\n")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\n'));
        } else if (values[values.Length - 1].EndsWith("\n\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf("\n\r"));
        } else if (values[values.Length - 1].EndsWith("\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\r'));
        }

        return values;
    }

    private string[] createDataRowParams(string line, int max) {
        string[] raw = line.Split('\t');

        int length = raw.Length - 1;
        if (length > max) {
            length = max;
        }

        string[] values = new string[length];
        for (int i = 0; i < length; i++) {
            values[i] = raw[i + 1];
        }

        if (values[values.Length - 1].EndsWith("\n")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\n'));
        } else if (values[values.Length - 1].EndsWith("\n\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf("\n\r"));
        } else if (values[values.Length - 1].EndsWith("\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\r'));
        }

        return values;
    }
</code>```

OwnerDisplayName: Malfist

Title: Parsing a Quickbook IIF format file

Body:
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.

The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.

When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.

How would you parse such a file?

Edit: An example

!CUST   NAME    REFNUM  TIMESTAMP   BADDR1  BADDR2  BADDR3  BADDR4  BADDR5  SADDR1  SADDR2  SADDR3  SADDR4  SADDR5  PHONE1  PHONE2  FAXNUM  CONT1   CONT2   CTYPE   TERMS   TAXABLE LIMIT   RESALENUM   REP TAXITEM NOTEPAD SALUTATION  COMPANYNAME FIRSTNAME   MIDINIT LASTNAME    CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    CUSTFLD6    CUSTFLD7    CUSTFLD8    CUSTFLD9    CUSTFLD10   CUSTFLD11   CUSTFLD12   CUSTFLD13   CUSTFLD14   CUSTFLD15   JOBDESC JOBTYPE JOBSTATUS   JOBSTART    JOBPROJEND  JOBEND  HIDDEN  DELCOUNT
CUST    St. Mark    359 1176670332  Saint Mark Catholic Church  609 W Main St   City, State Zip
!CLASS  NAME    REFNUM  TIMESTAMP   HIDDEN  DELCOUNT
!INVITEM    NAME    REFNUM  TIMESTAMP   INVITEMTYPE DESC    PURCHASEDESC    ACCNT   ASSETACCNT  COGSACCNT   QNTY    QNTY    PRICE   COST    TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND    REORDERPOINT    EXTRA   CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    DEP_TYPE    ISPASSEDTHRU    HIDDEN  DELCOUNT    USEID
INVITEM Labor   1   1119915308  SERV    Labor                                                                                0
!TIMEACT    DATE    JOB EMP ITEM    PITEM   DURATION    PROJ    NOTE    XFERTOPAYROLL   BILLINGSTATUS
TIMEACT 3/8/08  876 Development Jane Doe {Consultant}   Labor       00:15       Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names.  N   1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant}   Labor       01:00       Preparing Studio    N   1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant}   Labor       00:06       REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
    N   1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant}   Labor       01:00       Fixing Kandis's computer - replaced entire computer with similar system N   1

LastEditorDisplayName: Malfist

Body:
I did it:

 public DataSet parseIIF(Stream file) {
            iifSet = new DataSet();
            String fileText;

            using (StreamReader sr = new StreamReader(file)) {
                fileText = sr.ReadToEnd();
            }
            //replace line breaks with tabs
            //fileText.Replace('\n', '\t');
            fileText = fileText.Replace("\r\n", "\n");
            fileText = fileText.Replace('\r', '\n');

            //split along tabs
            string[] lines = fileText.Split('\n');

            this.createTables(lines, iifSet);
            this.fillSet(lines, iifSet);

            return iifSet;
        }

        /// <summary>
        /// Reads an array of lines and parses them into tables for the dataset
        /// </summary>
        /// <param name="lines">String Array of lines from the iif file</param>
        /// <param name="iifSet">DataSet to be manipulated</param>
        private void fillSet(string[] lines, DataSet set) {
            //CODING HORROR
            //WARNING: I will monkey with the for loop index, be prepared!
            for (int i = 0; i < lines.Length; i++) {
                if (this.isTableHeader(lines[i])) {
                    //ignore this line, tables are alread defined
                    continue;
                }
                if (lines[i] == "" || lines[i] == "\r" || lines[i] == "\n\r" || lines[i] == "\n") {
                    //ignore lines that are empty if not inside a record
                    //probably the end of the file, it always ends with a blank line break
                    continue;
                }

                if (lines[i].IndexOf(";__IMPORTED__") != -1) {
                    continue;
                    //just signifying that it's been imported by quickbook's timer before, don't need it
                }

                string line = lines[i];
                while (!isFullLine(line, set)){
                    i++;            //<--------------------------- MONKEYING done here!
                    line += lines[i];
                }
                //now, the line should be complete, we can parse it by tabs now
                this.parseRecord(line, set);
            }
        }

        private void parseRecord(string line, DataSet set) {
            if (isTableHeader(line)) {
                //we don't want to deal with headers here
                return;
            }

            String tablename = line.Split('\t')[0];
            //this just removes the first value and the line break from the last value
            String[] parameters = this.createDataRowParams(line);

            //add it to the dataset
            set.Tables[tablename].Rows.Add(parameters);
        }

        private bool isFullLine(string line, DataSet set) {
            if (isTableHeader(line)) {
                return true;    //assumes table headers won't have line breaks
            }
            int values = line.Split('\t').Length;
            string tableName = line.Split('\t')[0];
            int columns = set.Tables[tableName].Columns.Count;

            if (values < columns) {
                return false;
            } else {
                return true;
            }
        }

        private void createTables(string[] lines, DataSet set) {
            for (int index = 0; index < lines.Length; index++) {
                if (this.isTableHeader(lines[index])) {
                    set.Tables.Add(createTable(lines[index]));
                }
            }
        }

        private bool isTableHeader(string tab) {
            if (tab.StartsWith("!"))
                return true;
            else
                return false;
        }

        private bool isNewLine(string p) {
            if (p.StartsWith("!"))
                return true;
            if (iifSet.Tables[p.Split('\t')[0]] != null)    //that little mess there grabs the first record in the line, sorry about the mess
                return true;
            return false;
        }

    private DataTable createTable(string line) {
        String[] values = line.Split('\t');

        //first value is always the title
        //remove the ! from it
        values[0] = values[0].Substring(1);     //remove the first character
        DataTable dt = new DataTable(values[0]);
        values[0] = null;   //hide first title so it doesn't get used, cheaper than resetting array
        foreach (String name in values) {
            if (name == null || name == "")
                continue;
            DataColumn dc = new DataColumn(name, typeof(String));
            try {
                dt.Columns.Add(dc);
            } catch (DuplicateNameException) {
                //odd
                dc = new DataColumn(name + "_duplicateCol" + dt.Columns.Count.ToString());
                dt.Columns.Add(dc);
                //if there is a triple, just throw it
            }
        }

        return dt;
    }

   private string getTableName(string line) {
        String[] values = line.Split('\t');

        //first value is always the title
        if(values[0].StartsWith("!")){
            //remove the ! from it
            values[0] = values[0].Substring(1);     //remove the first character
        }
        return values[0];
    }

    private string[] createDataRowParams(string line) {
        string[] raw = line.Split('\t');
        string[] values = new string[raw.Length - 1];

        //copy all values except the first one
        for (int i = 0; i < values.Length; i++) {
            values[i] = raw[i + 1];
        }

        //remove last line break from the record
        if (values[values.Length - 1].EndsWith("\n")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\n'));
        } else if (values[values.Length - 1].EndsWith("\n\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf("\n\r"));
        } else if (values[values.Length - 1].EndsWith("\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\r'));
        }

        return values;
    }

    private string[] createDataRowParams(string line, int max) {
        string[] raw = line.Split('\t');

        int length = raw.Length - 1;
        if (length > max) {
            length = max;
        }

        string[] values = new string[length];
        for (int i = 0; i < length; i++) {
            values[i] = raw[i + 1];
        }

        if (values[values.Length - 1].EndsWith("\n")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\n'));
        } else if (values[values.Length - 1].EndsWith("\n\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf("\n\r"));
        } else if (values[values.Length - 1].EndsWith("\r")) {
            values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\r'));
        }

        return values;
    }


答:
They way I did it was like this:

```<code>private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
.

textView = (TextView) findViewById(R.id.textView);
Typeface mTextView = Typeface.createFromAsset(getAssets(),"fonts/your_font_style.ttf");
textView.setTypeface(mTextView);
</code>```

Hope this will help you.

Title: cannot resolve method 'getFont(?)'

Body:
They way I did it was like this:

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
.

textView = (TextView) findViewById(R.id.textView);
Typeface mTextView = Typeface.createFromAsset(getAssets(),"fonts/your_font_style.ttf");
textView.setTypeface(mTextView);

Hope this will help you.


问:
GET Web API Method returns method not allowed
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

```<code>public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}
</code>```

and this is how I enabled CORS:

```<code>config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
</code>```

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

```<code>GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6
</code>```

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

```<code>public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
</code>```

答:
I fixed this issue and the bug was rather interesting to me.

Problem was that this method CommitReserve was coming from an interface and apparently(sorry, for not mentioning it, but I thought it was not relevant, silly me!) attributes are not inherited(routing was working because of the name of the method), once applied to interface methods, in the implementing class.

I fixed this with making IReserveController an abstract class.

However I looked upon the IL code of method CommitReserve once like abstract method of an abstract class and once like interface method and I saw no significant difference which bugs me , because now I want to know what is responsible for this.

Body:
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}

and this is how I enabled CORS:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}


问:
How to set Delivery order state to 'done' with XMLRPC Odoo 9
I want to set delivery order state to done from PHP via xmlrpc, so I'm trying it like this,

```<code>$write = $client->write('stock.picking', array(23), ["state" =>"done"]);
</code>```

Using this method works to set any other parameter, but it does not set state to done

Can you see what I'm doing wrong here or what is the proper way to set it done

答:
You are not allow to write state field in stock.picking , because state field is calculative store field in stock.picking model odoo.

You must update state field of stock.move, odoo will automatically change state of stock.picking.

You can follow below odoo code.

picking.move_lines.write({'state':'done'})

This may help you.

Body:
I want to set delivery order state to done from PHP via xmlrpc, so I'm trying it like this,

$write = $client->write('stock.picking', array(23), ["state" =>"done"]);

Using this method works to set any other parameter, but it does not set state to done

Can you see what I'm doing wrong here or what is the proper way to set it done


问:
Xamarin Forms List View Show Different Pages?
New to Xamarin here. How can I make each item on a listview go to a different page in Xamarin Forms?

For example, something like Facebook app:

答:
The main flow is simple. You have your ListView, you attach an event on the ItemTapped to it, in code behind in the ItemTap handle method you can access which item was tapped and with that information you decide where you want to navigate.</p>

```<code>void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
{
    // Item tapped
    var item = e.Item as YourItemThatWasBinded;

    if (item == null) return;

    // Choose the page to navigate to based on the item selected.
    // You decide what logic use inside this method if can be as simple using IFs.
    var page = GetPageToNavigateWithItem(item);

    // Navigate
    Navigation.PushAsync(page);
}
</code>```

Body:
The main flow is simple. You have your ListView, you attach an event on the ItemTapped to it, in code behind in the ItemTap handle method you can access which item was tapped and with that information you decide where you want to navigate.

void Handle_ItemTapped(object sender, ItemTappedEventArgs e)
{
    // Item tapped
    var item = e.Item as YourItemThatWasBinded;

    if (item == null) return;

    // Choose the page to navigate to based on the item selected.
    // You decide what logic use inside this method if can be as simple using IFs.
    var page = GetPageToNavigateWithItem(item);

    // Navigate
    Navigation.PushAsync(page);
}


问:
Check parameter in Lambda Expression
I have this code:

```<code> Function<Integer, String> converter = (num) -> Integer.toString(num);
</code>```

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

答:
The preferred one according KISS is checking its type before the Function calling.

```<code>if(input instanceof Integer){
    return converter.apply((Integer)input);
}else{
    //throw exception;
}
</code>```

OR you need use Optional filtering the input.

```<code>Function<Integer, String> converter = (num) -> Integer.toString(num);

String result = Optional.ofNullable(input)
            .filter(Integer.class::isInstance)
            .map(Integer.class::cast)
            .map(converter).orElseThrow(IllegalArgumentException::new);
</code>```

OR you can combine Optional & Function to declaring two functions one is checking the type, another one is converter, but I think this is unnecessary and over coding in your situation.

```<code>Function<Object, Integer> typeChecking = (input) -> (Integer) Optional.ofNullable(input)
        .filter(Integer.class::isInstance)
        .orElseThrow(IllegalArgumentException::new);

Function<Integer, String> intToString = (num) -> Integer.toString(num);

Function<Object, String> converter = typeChecking.andThen(intToString);
</code>```

Checking parameter type in lambda expression will resulting in your lambda bloated,and usually unnecessary because you can't pass incompatible types to the lambda expression if you define your FunctionInterface with exactly parameter types,if you do like @Holger was given a CalssCastException will be thrown.

Title: Check parameter in Lambda Expression

Body:
I have this code:

 Function<Integer, String> converter = (num) -> Integer.toString(num);

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

Body:
The preferred one according KISS is checking its type before the Function calling.

if(input instanceof Integer){
    return converter.apply((Integer)input);
}else{
    //throw exception;
}

OR you need use Optional filtering the input.

Function<Integer, String> converter = (num) -> Integer.toString(num);

String result = Optional.ofNullable(input)
            .filter(Integer.class::isInstance)
            .map(Integer.class::cast)
            .map(converter).orElseThrow(IllegalArgumentException::new);

OR you can combine Optional & Function to declaring two functions one is checking the type, another one is converter, but I think this is unnecessary and over coding in your situation.

Function<Object, Integer> typeChecking = (input) -> (Integer) Optional.ofNullable(input)
        .filter(Integer.class::isInstance)
        .orElseThrow(IllegalArgumentException::new);

Function<Integer, String> intToString = (num) -> Integer.toString(num);

Function<Object, String> converter = typeChecking.andThen(intToString);

Checking parameter type in lambda expression will resulting in your lambda bloated,and usually unnecessary because you can't pass incompatible types to the lambda expression if you define your FunctionInterface with exactly parameter types,if you do like @Holger was given a CalssCastException will be thrown.


答: Use $scope.apply . This is because angulars digest cycle will not know if your value changes outside of its scope like in a simple JS function.</p>

Title: ng-if not working with simple javascript

Body:
ng-if is not working when I change the values through simple javascript function.My function is getting called but the changes in values cannot be seen in view. Please refer below code.

HTML

  This is for true

  This is False

{{bool}}

<input type="submit" ng-click = "myfunction('test')" value="ng-if button">

<input type="submit" onClick = "check1()" value="simple JS button">

JS

angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.bool = true;
$scope.myfunction = function (data) {
    $scope.bool = !$scope.bool;
};
});
function check1() {
    angular.element(document.getElementById('span')).scope().myfunction('test');
}

When I use ng-click button it changes value of bool changes, but same doesn't happens with simple JS button . Actually I am implementing Angular in a page that already uses jQuery, so I need to use simple JS button.

JS Fiddle : JS Fiddle


问:
how to use angular 2 file uploaf in ES5?
I try to use angular 2 file upload, yet it's only explained for TypeScript, and I'm using ES5

what should I do?

I use this library:
https://github.com/valor-software/ng2-file-upload

I know Angular 2 can be written in ES5 and I have already written applications in ES5 using Angular 2 and Material 2

答:
To use ng2-file-upload package with es5 you can take umd bundle

https://unpkg.com/ng2-file-upload@1.2.0/bundles/ng2-file-upload.umd.js

If you open it you can notice

```<code>root["ng2-file-upload.umd"] = factory(root["@angular/core"], root["@angular/common"]);
</code>```

So before loading this script without any loaders you have to do something like this:

```<code>window["@angular/core"] = ng.core;
window["@angular/common"] = ng.common;
</code>```

then you can get reference to FileUploadModule module and other classes via:

```<code>var FileUploadModule = window['ng2-file-upload.umd'].FileUploadModule;
</code>```

JsFiddle Example Angular2 v4.0.1 es5 nf2-file-upload

Body:
To use ng2-file-upload package with es5 you can take umd bundle

https://unpkg.com/ng2-file-upload@1.2.0/bundles/ng2-file-upload.umd.js

If you open it you can notice

root["ng2-file-upload.umd"] = factory(root["@angular/core"], root["@angular/common"]);

So before loading this script without any loaders you have to do something like this:

window["@angular/core"] = ng.core;
window["@angular/common"] = ng.common;

then you can get reference to FileUploadModule module and other classes via:

var FileUploadModule = window['ng2-file-upload.umd'].FileUploadModule;

JsFiddle Example Angular2 v4.0.1 es5 nf2-file-upload


问:
Spring Integration xpath expression Multiple Condition Check
I have an SAP IDOC that I want to filter but I am Stuck at one Place.

Here is a Sample XML

```<code>    <E1EDK14 SEGMENT="1">
        <QUALF>007</QUALF>
        <ORGID>10</ORGID>
    </E1EDK14>
    <E1EDK14 SEGMENT="1">
        <QUALF>008</QUALF>
        <ORGID>BP01</ORGID>
    </E1EDK14>
    <E1EDK14 SEGMENT="1">
        <QUALF>012</QUALF>
        <ORGID>ZMOR</ORGID>
    </E1EDK14>
</code>```

The Condition would be Something like

if QUALF = 12 and ORGID = ZOR then process else ignore

My Code is Something like this

```<code><int-xml:xpath-router id="splitORGID" input-channel="ORDERS" evaluate-as-string="true" resolution-required="false" default-output-channel="ORDER-TYPE-NOT-SUPPORTED">
    <int-xml:xpath-expression id="splitORGIDExpression" expression="//E1EDK14/ORGID" />
    <int-xml:mapping value="ZOR" channel="ALLOW_ORDERS" />
</int-xml:xpath-router>
</code>```

I would like to know if this is correct.

答:
This is the Solution I came up with and it is working fine</p>

```<code><int-xml:xpath-router id="splitORGID" input-channel="CUSTORDERS" evaluate-as-string="true" resolution-required="false" default-output-channel="ORDERTYPE-NOTSUPPORTED-KTOKD">
    <int-xml:xpath-expression id="splitORGIDExpression" expression="//E1EDK14[QUALF=012]/ORGID" />
    <int-xml:mapping value="ZOR" channel="ORDERS" />
    <int-xml:mapping value="ZSCO" channel="ORDERS" />
    <int-xml:mapping value="ZMOR" channel="HISTORICALORDERS" />
</int-xml:xpath-router>
</code>```

Body:
I have an SAP IDOC that I want to filter but I am Stuck at one Place.

Here is a Sample XML

    <E1EDK14 SEGMENT="1">
        <QUALF>007</QUALF>
        <ORGID>10</ORGID>
    </E1EDK14>
    <E1EDK14 SEGMENT="1">
        <QUALF>008</QUALF>
        <ORGID>BP01</ORGID>
    </E1EDK14>
    <E1EDK14 SEGMENT="1">
        <QUALF>012</QUALF>
        <ORGID>ZMOR</ORGID>
    </E1EDK14>

The Condition would be Something like

if QUALF = 12 and ORGID = ZOR then process else ignore

My Code is Something like this

<int-xml:xpath-router id="splitORGID" input-channel="ORDERS" evaluate-as-string="true" resolution-required="false" default-output-channel="ORDER-TYPE-NOT-SUPPORTED">
    <int-xml:xpath-expression id="splitORGIDExpression" expression="//E1EDK14/ORGID" />
    <int-xml:mapping value="ZOR" channel="ALLOW_ORDERS" />
</int-xml:xpath-router>

I would like to know if this is correct.

Body:
This is the Solution I came up with and it is working fine

<int-xml:xpath-router id="splitORGID" input-channel="CUSTORDERS" evaluate-as-string="true" resolution-required="false" default-output-channel="ORDERTYPE-NOTSUPPORTED-KTOKD">
    <int-xml:xpath-expression id="splitORGIDExpression" expression="//E1EDK14[QUALF=012]/ORGID" />
    <int-xml:mapping value="ZOR" channel="ORDERS" />
    <int-xml:mapping value="ZSCO" channel="ORDERS" />
    <int-xml:mapping value="ZMOR" channel="HISTORICALORDERS" />
</int-xml:xpath-router>


问:
PHP greek url convert
I have a URL like: domain.tld/Σχετικά_με_μας

[edit]
Reading the $_SERVER['REQUEST_URI'] I get to work with:

```<code>%CE%A3%CF%87%CE%B5%CF%84%CE%B9%CE%BA%CE%AC_%CE%BC%CE%B5_%CE%BC%CE%B1%CF%82
</code>```

[/edit]

In PHP I need to convert it to HTML, I get pretty far with:

```<code>htmlentities(urldecode($navstring), ENT_QUOTES, 'UTF-8');
</code>```

It results in:

```<code>ΣχετικÎ¬_με_μας
</code>```

but the 'ά' becomes 'Î¬' But I need it converted to

```<code>ά
</code>```

I'dd really appreciate help. I need a universal solution, not a "string replace"

答:
I have been playing around a little, and the following worked. Use mb-convert-encoding instead of htmlentities.:

```<code>mb_convert_encoding(urldecode($navstring),'HTML-ENTITIES','UTF-8');
//string(90) "domain.tld/Σχετικά_με_μας"
</code>```

See mb-convert-encoding

Title: PHP greek url convert

Body:
I have a URL like: domain.tld/Σχετικά_με_μας

[edit]
Reading the $_SERVER['REQUEST_URI'] I get to work with:

%CE%A3%CF%87%CE%B5%CF%84%CE%B9%CE%BA%CE%AC_%CE%BC%CE%B5_%CE%BC%CE%B1%CF%82

[/edit]

In PHP I need to convert it to HTML, I get pretty far with:

htmlentities(urldecode($navstring), ENT_QUOTES, 'UTF-8');

It results in:

ΣχετικÎ¬_με_μας

but the 'ά' becomes 'Î¬' But I need it converted to

ά

I'dd really appreciate help. I need a universal solution, not a "string replace"

Body:
I have been playing around a little, and the following worked. Use mb-convert-encoding instead of htmlentities.:

mb_convert_encoding(urldecode($navstring),'HTML-ENTITIES','UTF-8');
//string(90) "domain.tld/&Sigma;&chi;&epsilon;&tau;&iota;&kappa;&#940;_&mu;&epsilon;_&mu;&alpha;&sigmaf;"

See mb-convert-encoding


问:
postgresql Select date from min value
I want to select list of people, who have FIRST time 'E' diagnosis from 2016-01-01.

my code looks like

```<code>SELECT DISTINCT ON(form25.visit.patient_id )
        form25.visit.patient_id,
        CONCAT(demographics.party.firstname,' ', demographics.party.lastname) AS pacientas,
        form25.visit.disease_code,
        demographics.party.code,
        form25.visit.date,
        form25.diagnose.disease_type
    FROM form25.visit
    JOIN demographics.party
        ON form25.visit.patient_id = demographics.party.id
    JOIN form25.diagnose
        ON form25.visit.patient_id = form25.diagnose.card_id
    WHERE form25.visit.disease_code LIKE 'E%'
        AND form25.diagnose.disease_type = '+'
        AND form25.visit.date >= '2016-01-01'
    ORDER BY form25.visit.patient_id, form25.visit.date ASC
</code>```

result i get:

```<code>patients E.. 2013,2014,2016, 2017
</code>```

(contains E.. with 2016 so I see them)

All I want is to eliminate those who have date(s) with E.. before 2016, and see only those who had it first time from 2016.

答:
First, your query would be much easier to read (and write) if you used table aliases.

Second, you can get what you want by doing an aggregation and then looking at the minimum date:

```<code>SELECT v.patient_id, CONCAT(p.firstname, ' ', p.lastname) AS pacientas,
       MIN(v.date) as first_date
FROM form25.visit v JOIN
     demographics.party p
     ON v.patient_id = p.id JOIN
     form25.diagnose d
     ON v.patient_id = d.card_id
WHERE v.disease_code LIKE 'E%' AND d.disease_type = '+'
GROUP BY patient_id, pacientas
HAVING MIN(v.date) >= '2016-01-01';
</code>```

Note that this gives you the patients that meet the conditions.  If you need visit details, you can join back or use window functions.

Title: postgresql Select date from min value

Body:
I want to select list of people, who have FIRST time 'E' diagnosis from 2016-01-01.

my code looks like

SELECT DISTINCT ON(form25.visit.patient_id )
        form25.visit.patient_id,
        CONCAT(demographics.party.firstname,' ', demographics.party.lastname) AS pacientas,
        form25.visit.disease_code,
        demographics.party.code,
        form25.visit.date,
        form25.diagnose.disease_type
    FROM form25.visit
    JOIN demographics.party
        ON form25.visit.patient_id = demographics.party.id
    JOIN form25.diagnose
        ON form25.visit.patient_id = form25.diagnose.card_id
    WHERE form25.visit.disease_code LIKE 'E%'
        AND form25.diagnose.disease_type = '+'
        AND form25.visit.date >= '2016-01-01'
    ORDER BY form25.visit.patient_id, form25.visit.date ASC

result i get:

patients E.. 2013,2014,2016, 2017

(contains E.. with 2016 so I see them)

All I want is to eliminate those who have date(s) with E.. before 2016, and see only those who had it first time from 2016.

Body:
First, your query would be much easier to read (and write) if you used table aliases.

Second, you can get what you want by doing an aggregation and then looking at the minimum date:

SELECT v.patient_id, CONCAT(p.firstname, ' ', p.lastname) AS pacientas,
       MIN(v.date) as first_date
FROM form25.visit v JOIN
     demographics.party p
     ON v.patient_id = p.id JOIN
     form25.diagnose d
     ON v.patient_id = d.card_id
WHERE v.disease_code LIKE 'E%' AND d.disease_type = '+'
GROUP BY patient_id, pacientas
HAVING MIN(v.date) >= '2016-01-01';

Note that this gives you the patients that meet the conditions.  If you need visit details, you can join back or use window functions.


问:
Is using "final" parameter thread safe in Java
In this example, is it sufficient to declare the parameter obj as final to safely use it in the thread, below?

```<code>public void doSomethingAsync (final Object obj)
{
  Thread thread = new Thread ()
  {
    @Override public void run () { ... do something with obj ... }
  }

  thread.start ();
}
</code>```

At first glance it may seem fine. A caller invokes doSomethingAsync and obj gets cached until needed in the thread.

But what happens if there are a burst of calls to doSomethingAsync such that they complete before the threads have done anything with obj?

If the Java compiler simply makes obj into a member variable, the last call to doSomethingAsync will overwrite the prior values of obj, making prior invocations of the thread use a wrong value. Or, does the compiler generate a queue or some dimensioned storage for obj so that each thread gets the proper value?

答:
If the Java compiler simply makes obj into a member variable, the last call to doSomethingAsync will overwrite the prior values of obj, making prior invocations of the thread use a wrong value

No, this will not happen. The subsequent call to doSomethingAsync cannot overwrite the obj captured by previous invocations of doSomethingAsync. This stands even if you remove the final keyword (assume java let you do it for just this time).

I think your question ultimately is about how closure works/is implemented in java. However, your code is not demonstrating the complication in the proper way because the code is not even trying to modify the variable obj in the same lexical scope.

In a way Java is not really capturing the variable obj, but its value. You could write the your code in a different way, and the overall effect is the same:

```<code>class YourThread extends Thread {
    private Object param;

    public YourThread (Object obj){
        param = obj;
    }

    @Override
    public void run(){
        //do something with your param
    }
}
</code>```

and you no longer need the final keyword:

```<code>public void doSomethingAsync (Object obj){
    Thread t = new YourThread (obj);
    t.start();
}
</code>```

Now, say you have two instances of YourThread created, how could the second instance modify what has been passed as parameter to the first instance?

Closure in Other Languages

In other languages, magical things can indeed happen, but to show it you need to write the code slightly different:

```<code>public void doSomethingAsync (Object obj){
    //Here let's assume obj is not null
    Thread thread = new Thread (){
        @Override
        public void run () { ... /*do something with obj*/ ... }
    }

    thread.start ();
    obj = null;
}
</code>```

This is not valid Java code, but in certain languages code like that is allowed. And the thread, when its run method is executed, might see obj as null.

Similarly, in the below code (again, not valid in Java), thread2 could potentially impact thread1 if thread2 executes first and changes obj in its run method:

```<code>public void doSomethingAsync (Object obj){

    Thread thread1 = new Thread (){
        @Override
        public void run () { ... /*do something with obj*/ ... }
    }

    thread1.start ();

    Thread thread2 = new Thread (){
        @Override
        public void run () { ... /*do something with obj*/ ... }
    }

    thread2.start ();
}
</code>```

Back to Java

The reason Java forces you to put a final on obj is that although Java's syntax looks extremely similar to the closure syntax used in other languages, it is not doing the same closure semantics. Knowing it is final, Java does not need to create capturing object (thus additional heap allocation), but use something similar to YourThread behind the scene. See this link for more details

Body:
In this example, is it sufficient to declare the parameter obj as final to safely use it in the thread, below?

public void doSomethingAsync (final Object obj)
{
  Thread thread = new Thread ()
  {
    @Override public void run () { ... do something with obj ... }
  }

  thread.start ();
}

At first glance it may seem fine. A caller invokes doSomethingAsync and obj gets cached until needed in the thread.

But what happens if there are a burst of calls to doSomethingAsync such that they complete before the threads have done anything with obj?

If the Java compiler simply makes obj into a member variable, the last call to doSomethingAsync will overwrite the prior values of obj, making prior invocations of the thread use a wrong value. Or, does the compiler generate a queue or some dimensioned storage for obj so that each thread gets the proper value?

Body:
If the Java compiler simply makes obj into a member variable, the last call to doSomethingAsync will overwrite the prior values of obj, making prior invocations of the thread use a wrong value

No, this will not happen. The subsequent call to doSomethingAsync cannot overwrite the obj captured by previous invocations of doSomethingAsync. This stands even if you remove the final keyword (assume java let you do it for just this time).

I think your question ultimately is about how closure works/is implemented in java. However, your code is not demonstrating the complication in the proper way because the code is not even trying to modify the variable obj in the same lexical scope.

In a way Java is not really capturing the variable obj, but its value. You could write the your code in a different way, and the overall effect is the same:

class YourThread extends Thread {
    private Object param;

    public YourThread (Object obj){
        param = obj;
    }

    @Override
    public void run(){
        //do something with your param
    }
}

and you no longer need the final keyword:

public void doSomethingAsync (Object obj){
    Thread t = new YourThread (obj);
    t.start();
}

Now, say you have two instances of YourThread created, how could the second instance modify what has been passed as parameter to the first instance?

Closure in Other Languages

In other languages, magical things can indeed happen, but to show it you need to write the code slightly different:

public void doSomethingAsync (Object obj){
    //Here let's assume obj is not null
    Thread thread = new Thread (){
        @Override
        public void run () { ... /*do something with obj*/ ... }
    }

    thread.start ();
    obj = null;
}

This is not valid Java code, but in certain languages code like that is allowed. And the thread, when its run method is executed, might see obj as null.

Similarly, in the below code (again, not valid in Java), thread2 could potentially impact thread1 if thread2 executes first and changes obj in its run method:

public void doSomethingAsync (Object obj){

    Thread thread1 = new Thread (){
        @Override
        public void run () { ... /*do something with obj*/ ... }
    }

    thread1.start ();

    Thread thread2 = new Thread (){
        @Override
        public void run () { ... /*do something with obj*/ ... }
    }

    thread2.start ();
}

Back to Java

The reason Java forces you to put a final on obj is that although Java's syntax looks extremely similar to the closure syntax used in other languages, it is not doing the same closure semantics. Knowing it is final, Java does not need to create capturing object (thus additional heap allocation), but use something similar to YourThread behind the scene. See this link for more details