问:
How to test an ES6 class that needs jquery?
I have an ES6 module that needs jquery.

```<code>import $ from 'jquery';

export class Weather {
    /**
     * Constructor for Weather class
     *
     * @param latitude
     * @param longitude
     */
    constructor(latitude, longitude) {
        this.latitude  = latitude;
        this.longitude = longitude;
    }

    /**
     * Fetches the weather using API
     */
    getWeather() {
        return $.ajax({
            url: 'http://localhost:8080/weather?lat=' + this.latitude + '&lon=' + this.longitude,
            method: "GET",
        }).promise();
    }
}
</code>```

Module works fine when use it in my main module but the issue is with the test that I am writing for it.

Here's the test:

```<code>import {Weather} from '../js/weather';
import chai from 'chai';
import sinon from 'sinon';

chai.should();

describe('weatherbot', function() {
    beforeEach(function() {
        this.xhr = sinon.useFakeXMLHttpRequest();

        this.requests = [];
        this.xhr.onCreate = function(xhr) {
            this.requests.push(xhr);
        }.bind(this);
    });

    afterEach(function() {
        this.xhr.restore();
    });

    it('should return a resolved promise if call is successful', (done) => {
        let weather = new Weather(43.65967339999999, -79.72506369999999);

        let data = '{"coord":{"lon":-79.73,"lat":43.66},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":15.28,"pressure":1009,"humidity":82,"temp_min":13,"temp_max":17},"visibility":24140,"wind":{"speed":7.2,"deg":30},"clouds":{"all":90},"dt":1496770020,"sys":{"type":1,"id":3722,"message":0.0047,"country":"CA","sunrise":1496741873,"sunset":1496797083},"id":5907364,"name":"Brampton","cod":200}';

        weather.getWeather().then((data) => {
            expect(data.main.temp).to.equal(15.28);
            done();
        });

        this.requests[0].respond("GET", "/weather?lat=43.659673399999996&lon=-79.72506369999999", [
            200, {"Content-Type":"application/json"}, JSON.stringify(data)
        ]);
    });
});
</code>```

And here's my package.json:

```<code>{
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.1.0",
    "babel-polyfill": "^6.3.14",
    "babel-preset-es2015": "^6.1.18",
    "chai": "^3.5.0",
    "copy-webpack-plugin": "^0.2.0",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "mocha": "^3.4.1",
    "mocha-webpack": "^1.0.0-beta.1",
    "qunitjs": "^2.3.2",
    "sinon": "^2.2.0",
    "style-loader": "^0.16.1",
    "svg-inline-loader": "^0.7.1",
    "webpack": "*",
    "webpack-dev-server": "^1.12.1",
    "webpack-node-externals": "^1.6.0"
  },
  "scripts": {
    "build": "webpack",
    "watch": "webpack --watch --display-error-details",
    "start": "webpack-dev-server --hot --inline --port 8383",
    "test": "mocha --compilers js:babel-core/register ./test/*.js",
    "test:watch": "npm run test -- --watch"
  },
  "babel": {
    "presets": [
      "es2015"
    ]
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1",
    "webpack": "*"
  }
}
</code>```

As you can see I only have to do npm test to run the test.

When do npm test, I get this error:

```<code>TypeError: _jquery2.default.ajax is not a function
      at Weather.getWeather (js/weather.js:19:18)
      at Context.<anonymous> (test/index.js:26:17)
</code>```

But I am importing the jquery in the module, why it might be happening?

答:
Unless it is ES6 module that has default export that is being imported (which jQuery is not), the proper way to import it is

```<code>import * as $ from 'jquery';
</code>```

The way how CommonJS modules are treated with import is the responsibility of build tool. default imports for non-ES6 modules was (erroneously) supported at least in older Webpack versions. And no version restriction for

```<code>"webpack": "*"
</code>```

dependency is a direct way to broken builds.

Body:
I have an ES6 module that needs jquery.

import $ from 'jquery';

export class Weather {
    /**
     * Constructor for Weather class
     *
     * @param latitude
     * @param longitude
     */
    constructor(latitude, longitude) {
        this.latitude  = latitude;
        this.longitude = longitude;
    }

    /**
     * Fetches the weather using API
     */
    getWeather() {
        return $.ajax({
            url: 'http://localhost:8080/weather?lat=' + this.latitude + '&lon=' + this.longitude,
            method: "GET",
        }).promise();
    }
}

Module works fine when use it in my main module but the issue is with the test that I am writing for it.

Here's the test:

import {Weather} from '../js/weather';
import chai from 'chai';
import sinon from 'sinon';

chai.should();

describe('weatherbot', function() {
    beforeEach(function() {
        this.xhr = sinon.useFakeXMLHttpRequest();

        this.requests = [];
        this.xhr.onCreate = function(xhr) {
            this.requests.push(xhr);
        }.bind(this);
    });

    afterEach(function() {
        this.xhr.restore();
    });

    it('should return a resolved promise if call is successful', (done) => {
        let weather = new Weather(43.65967339999999, -79.72506369999999);

        let data = '{"coord":{"lon":-79.73,"lat":43.66},"weather":[{"id":521,"main":"Rain","description":"shower rain","icon":"09d"}],"base":"stations","main":{"temp":15.28,"pressure":1009,"humidity":82,"temp_min":13,"temp_max":17},"visibility":24140,"wind":{"speed":7.2,"deg":30},"clouds":{"all":90},"dt":1496770020,"sys":{"type":1,"id":3722,"message":0.0047,"country":"CA","sunrise":1496741873,"sunset":1496797083},"id":5907364,"name":"Brampton","cod":200}';

        weather.getWeather().then((data) => {
            expect(data.main.temp).to.equal(15.28);
            done();
        });

        this.requests[0].respond("GET", "/weather?lat=43.659673399999996&lon=-79.72506369999999", [
            200, {"Content-Type":"application/json"}, JSON.stringify(data)
        ]);
    });
});

And here's my package.json:

{
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.1.0",
    "babel-polyfill": "^6.3.14",
    "babel-preset-es2015": "^6.1.18",
    "chai": "^3.5.0",
    "copy-webpack-plugin": "^0.2.0",
    "css-loader": "^0.28.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "mocha": "^3.4.1",
    "mocha-webpack": "^1.0.0-beta.1",
    "qunitjs": "^2.3.2",
    "sinon": "^2.2.0",
    "style-loader": "^0.16.1",
    "svg-inline-loader": "^0.7.1",
    "webpack": "*",
    "webpack-dev-server": "^1.12.1",
    "webpack-node-externals": "^1.6.0"
  },
  "scripts": {
    "build": "webpack",
    "watch": "webpack --watch --display-error-details",
    "start": "webpack-dev-server --hot --inline --port 8383",
    "test": "mocha --compilers js:babel-core/register ./test/*.js",
    "test:watch": "npm run test -- --watch"
  },
  "babel": {
    "presets": [
      "es2015"
    ]
  },
  "dependencies": {
    "bootstrap": "^3.3.7",
    "jquery": "^3.2.1",
    "webpack": "*"
  }
}

As you can see I only have to do npm test to run the test.

When do npm test, I get this error:

TypeError: _jquery2.default.ajax is not a function
      at Weather.getWeather (js/weather.js:19:18)
      at Context.<anonymous> (test/index.js:26:17)

But I am importing the jquery in the module, why it might be happening?

Body:
Unless it is ES6 module that has default export that is being imported (which jQuery is not), the proper way to import it is

import * as $ from 'jquery';

The way how CommonJS modules are treated with import is the responsibility of build tool. default imports for non-ES6 modules was (erroneously) supported at least in older Webpack versions. And no version restriction for

"webpack": "*"

dependency is a direct way to broken builds.


来源: stackexchange

问:
Java collections vs manual loops - Coding challenges/interview best practices
For coding challenges/interview as well as optimization, is it good to use collections at all? For example, check the palindrome running time for below program

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

public class Palindrome {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        if(isPalindrome(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

        if(isPalindromeUsingSet(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

    }

    public static boolean isPalindrome(String str) {
        final long startTime = System.nanoTime();
        final long duration;
        for (int i=0;i<str.length()/2;i++) {
            if(str.charAt(i) != str.charAt(str.length() -1 -i)) {
                duration = System.nanoTime() - startTime;
                System.out.println("isPalindrome - " + duration);
                return false;
            }
        }
        duration = System.nanoTime() - startTime;
        System.out.println("isPalindrome - " + duration);

        return true;
    }

    public static boolean isPalindromeUsingSet(String str) {
    final long startTime = System.nanoTime();
    final long duration;
    Set<Character> charSet = new HashSet<>();
    for (int i=0;i<str.length()/2;i++) {
        if(charSet.add(str.charAt(i)) == false) {
            duration = System.nanoTime() - startTime;
            System.out.println("isPalindromeUsingSet - " + duration);
            return false;
        } else {
            charSet.remove(str.charAt(i));
        }
    }
    duration = System.nanoTime() - startTime;
    System.out.println("isPalindromeUsingSet - " + duration);
    return true;
}

}
</code>```

Running Time as calculated is shown below.

```<code>AMANAPLANACANALPANAMA
isPalindrome - 7788
YES
isPalindromeUsingSet - 745473
YES
</code>```

My couple of questions are:

So java collections are mostly safe and versatile in various CRUD
operations, why not use them?

For coding better optimized solutions, should I look for one loop
execution, use a lot of O(1) data structures?

My approach in learning optmization code:

For each coding problem, solve my crude way of java and data
structures.

Go and study the best solution later, calculate time and complexity and adapt in my solutions gradually.

Background:
I've been coding java for couple of years.  Now learning coding for puzzles, algorithms and time complexity for acing bigger interviews!

Any good direction is appreciated.

Thanks

答: Closed after understanding the comparison was wrong with two functions. </p>

ContentLicense: CC BY-SA 3.0

Body:
For coding challenges/interview as well as optimization, is it good to use collections at all? For example, check the palindrome running time for below program

    import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Palindrome {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        if(isPalindrome(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

        if(isPalindromeUsingSet(str)) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }

    }

    public static boolean isPalindrome(String str) {
        final long startTime = System.nanoTime();
        final long duration;
        for (int i=0;i<str.length()/2;i++) {
            if(str.charAt(i) != str.charAt(str.length() -1 -i)) {
                duration = System.nanoTime() - startTime;
                System.out.println("isPalindrome - " + duration);
                return false;
            }
        }
        duration = System.nanoTime() - startTime;
        System.out.println("isPalindrome - " + duration);

        return true;
    }

    public static boolean isPalindromeUsingSet(String str) {
    final long startTime = System.nanoTime();
    final long duration;
    Set<Character> charSet = new HashSet<>();
    for (int i=0;i<str.length()/2;i++) {
        if(charSet.add(str.charAt(i)) == false) {
            duration = System.nanoTime() - startTime;
            System.out.println("isPalindromeUsingSet - " + duration);
            return false;
        } else {
            charSet.remove(str.charAt(i));
        }
    }
    duration = System.nanoTime() - startTime;
    System.out.println("isPalindromeUsingSet - " + duration);
    return true;
}

}

Running Time as calculated is shown below.

AMANAPLANACANALPANAMA
isPalindrome - 7788
YES
isPalindromeUsingSet - 745473
YES

My couple of questions are:

So java collections are mostly safe and versatile in various CRUD
operations, why not use them?

For coding better optimized solutions, should I look for one loop
execution, use a lot of O(1) data structures?

My approach in learning optmization code:

For each coding problem, solve my crude way of java and data
structures.

Go and study the best solution later, calculate time and complexity and adapt in my solutions gradually.

Background:
I've been coding java for couple of years.  Now learning coding for puzzles, algorithms and time complexity for acing bigger interviews!

Any good direction is appreciated.

Thanks


问:
Use materialize to show simple_form errors
I would like know as i can to utilize the materialize errors on simple_form.

My form is:

```<code>  <div class="input-field col s6 offset-s3">
    <%= f.email_field :email, required: true, autofocus: true, placeholder: "Email", class: "validate" %>
  </div>
</code>```

I want that in addition to showing red the form it also shows an error message.

答:
If you want to show errors you can add this after you initialise the form.

<%= simple_form_for yourObject do |f| %>

<% if f.object.errors.any? %>

<%= pluralize( f.object.errors.count, "error") %> prohibited this field_group from being saved:

    <% f.object.errors.full_messages.each do |message| %>

<%= message %>

    <% end %>

<% end %>

<% end %>
```

Body:
I would like know as i can to utilize the materialize errors on simple_form.

My form is:

    <%= f.email_field :email, required: true, autofocus: true, placeholder: "Email", class: "validate" %>

I want that in addition to showing red the form it also shows an error message.

Body:
If you want to show errors you can add this after you initialise the form.

<%= simple_form_for yourObject do |f| %>

<% if f.object.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize( f.object.errors.count, "error") %> prohibited this field_group from being saved:</h2>
    <ul>
    <% f.object.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
    </ul>
  </div>
<% end %>

<% end %>


问:
cut a field from its position & place it in different position
I have 2 files - file1 & file2 with contents as shown.

```<code>cat file1.txt

1,2,3

cat file2.txt

a,b,c
</code>```

& the desired output is as below,

```<code>a,1,b,2,c,3
</code>```

Can anyone please help to achieve this?

Till now i have tried this,

```<code>paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3
</code>```

& the output came as 1,2,3,a,b,c

But using 'cut' is not the good approach i think.
Becuase here i know there are 3 values in both files, but if the values are more, above command will not be helpful.

答:
```<code>$ awk '
    BEGIN { FS=OFS="," }
    NR==FNR { split($0,a); next }
    {
        for (i=1;i<=NF;i++) {
            printf "%s%s%s%s", $i, OFS, a[i], (i<NF?OFS:ORS)
        }
    }
' file1 file2
a,1,b,2,c,3
</code>```

or if you prefer:

```<code>$ paste -d, file2 file1 |
awk '
    BEGIN { FS=OFS="," }
    {
        n=NF/2
        for (i=1;i<=n;i++) {
            printf "%s%s%s%s", $i, OFS, $(i+n), (i<n?OFS:ORS)
        }
    }
'
a,1,b,2,c,3
</code>```

Body:
I have 2 files - file1 & file2 with contents as shown.

cat file1.txt

1,2,3

cat file2.txt

a,b,c

& the desired output is as below,

a,1,b,2,c,3

Can anyone please help to achieve this?

Till now i have tried this,

paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3

& the output came as 1,2,3,a,b,c

But using 'cut' is not the good approach i think.
Becuase here i know there are 3 values in both files, but if the values are more, above command will not be helpful.

Body:
$ awk '
    BEGIN { FS=OFS="," }
    NR==FNR { split($0,a); next }
    {
        for (i=1;i<=NF;i++) {
            printf "%s%s%s%s", $i, OFS, a[i], (i<NF?OFS:ORS)
        }
    }
' file1 file2
a,1,b,2,c,3

or if you prefer:

$ paste -d, file2 file1 |
awk '
    BEGIN { FS=OFS="," }
    {
        n=NF/2
        for (i=1;i<=n;i++) {
            printf "%s%s%s%s", $i, OFS, $(i+n), (i<n?OFS:ORS)
        }
    }
'
a,1,b,2,c,3


问:
Wordpress: How to get the Header Image ID
Short story:
I'm trying to get the ID of the Header Image in Wordpress.

All I found was this guide, which dosn't seem to work anymore:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/

Long Story
I'm trying to make the WP Header responsive with an srcset. so I don't want to use this code

```<code><img id="masthead-bg" src="<?php header_image() ?>" alt="">
</code>```

...but instead want to use the wp_get_attachment_image_srcset function to get the srcset of my header image. Only problem: I need an Image ID for this function -> The ID of my Header image.

```<code><img id="masthead-bg"
src="<?php header_image() ?>"
srcset="<?php echo wp_get_attachment_image_srcset( image_id(), 'thumbnail' ); ?>"
sizes="100vw" alt="">
</code>```

Any suggestions?

答:
To answer the original question, I've found the simplest way to get the ID while I was filtering the markup that gets outputted by <?php the_header_image_tag(); ?> (introduced in v4.4).

```<code>function header_img_markup( $html, $header, $attr) {

    // we can get the image ID by passing its src url to this method
    $header_img_id = attachment_url_to_postid($attr['src']);

    // now we can get its metadata from the db
    $header_img_data = wp_get_attachment_metadata($header_img_id);

    // now we can use the data
    $customSizeWidth = $header_img_data['sizes']['my-custom-size']['width'];

    // ...your custom output here...
    return $html;
}
add_filter('get_header_image_tag', 'header_img_markup', 20, 3);
</code>```

Body:
Short story:
I'm trying to get the ID of the Header Image in Wordpress.

All I found was this guide, which dosn't seem to work anymore:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/

Long Story
I'm trying to make the WP Header responsive with an srcset. so I don't want to use this code

<img id="masthead-bg" src="<?php header_image() ?>" alt="">

...but instead want to use the wp_get_attachment_image_srcset function to get the srcset of my header image. Only problem: I need an Image ID for this function -> The ID of my Header image.

<img id="masthead-bg"
src="<?php header_image() ?>"
srcset="<?php echo wp_get_attachment_image_srcset( image_id(), 'thumbnail' ); ?>"
sizes="100vw" alt="">

Any suggestions?

Body:
To answer the original question, I've found the simplest way to get the ID while I was filtering the markup that gets outputted by <?php the_header_image_tag(); ?> (introduced in v4.4).

function header_img_markup( $html, $header, $attr) {

    // we can get the image ID by passing its src url to this method
    $header_img_id = attachment_url_to_postid($attr['src']);

    // now we can get its metadata from the db
    $header_img_data = wp_get_attachment_metadata($header_img_id);

    // now we can use the data
    $customSizeWidth = $header_img_data['sizes']['my-custom-size']['width'];

    // ...your custom output here...
    return $html;
}
add_filter('get_header_image_tag', 'header_img_markup', 20, 3);


问:
How to Run 1.7 Javascript
Is there a way to run scripts on a 1.7 javascript engine. The why?
I'm working with a language that is basically a forked version of 1.7 javascript but its inside of a server side box that is very slow and difficult to debug. </p>

答: Use old browsers? But that has it's own bundle of problems. If the webpages you are trying to run on this old server don't support the current Javascript language, you're better off updating the webpages instead of trying to find a way to interpret them differently.</p>

Title: How to Run 1.7 Javascript


问:
How to add a string to the string pool
When a class is loaded by the bootstrap class loader from a class file, it adds to the string pool the strings contained in its constant pool.

However, what if I build my own class loader? How to ask to add a string literal into the string pool?

I don't think that String.intern() answers to my question since to do so, you already need to have a String.

Complementary question: who does take care of the string pool? I can read at http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29 that the class String has a pool of strings: is it the same one? Is it a static field?

答:
All of the compile-time constant Strings in Java are automatically interned.(So they will be inserted into the StringTable (String pool))

Hope it's helped you.
Further information about string interning on my blog: http://www.zoltanraffai.com/blog/?p=74

ContentLicense: CC BY-SA 4.0

Title: How to add a string to the string pool


问:
How to rewrite this Java class to a Kotlin data class?
I have this in Java :

```<code>public class User {

    String name;
    String id;
    int age;

    public User(String name) {
        this.name = name;
    }

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}
</code>```

In a Kotlin class its something like this :

```<code>class User {

    var name: String?=null
    var id: String?=null
    var age: Int = 0

    constructor(name: String) {
        this.name = name
    }

    constructor(name: String, id: String) {
        this.name = name
        this.id = id
    }

    constructor(id: String, age: Int) {
        this.id = id
        this.age = age
    }

    constructor() {}

    override fun toString(): String {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}'
    }
}
</code>```

What I need to know, is how to do that in a data class with the 4 different constructors and the setters and getters

答:
You can use a combination of default and named arguments, so there is no need for  multiple constructors. Define your data class like this:

```<code>data class User(var name: String? = null, var age: Int = 0, var id: String? = null)
</code>```

And then construct it any number of ways.

```<code>User(name = "Foo") // returns User("Foo", 0, null)
User(name = "Foo", age = 21) // returns User("Foo", 21, null)
User(id = "x") // returns User(null, 0, "x")
User("Foo", 21, "x") // returns User("Foo", 21, "x")
User(id = "x", name = "Foo", age = 21) // returns User("Foo", 21, "x")
etc...
</code>```

The getters and setters are defined for you, no need to define them either.

Body:
I have this in Java :

public class User {

    String name;
    String id;
    int age;

    public User(String name) {
        this.name = name;
    }

    public User(String name, String id) {
        this.name = name;
        this.id = id;
    }

    public User(String id, int age) {
        this.id = id;
        this.age = age;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}';
    }
}

In a Kotlin class its something like this :

class User {

    var name: String?=null
    var id: String?=null
    var age: Int = 0

    constructor(name: String) {
        this.name = name
    }

    constructor(name: String, id: String) {
        this.name = name
        this.id = id
    }

    constructor(id: String, age: Int) {
        this.id = id
        this.age = age
    }

    constructor() {}

    override fun toString(): String {
        return "User{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +
                '}'
    }
}

What I need to know, is how to do that in a data class with the 4 different constructors and the setters and getters

Body:
You can use a combination of default and named arguments, so there is no need for  multiple constructors. Define your data class like this:

data class User(var name: String? = null, var age: Int = 0, var id: String? = null)

And then construct it any number of ways.

User(name = "Foo") // returns User("Foo", 0, null)
User(name = "Foo", age = 21) // returns User("Foo", 21, null)
User(id = "x") // returns User(null, 0, "x")
User("Foo", 21, "x") // returns User("Foo", 21, "x")
User(id = "x", name = "Foo", age = 21) // returns User("Foo", 21, "x")
etc...

The getters and setters are defined for you, no need to define them either.


问:
Extract string between by [" "]
how can I extract string between [" "]
I have eg: ["x"], so how can I extract just x and assign it to a
variable
I have tried this:

```<code>String str = "[x]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
</code>```

I can get x using the above code but my string is enclosed between [" "]

答:
The easiest way would be the following:

```<code>String s = "aaaa [\"axas\"]";
String result = s.substring(s.indexOf("[\"")+2, s.indexOf("\"]"));
</code>```

\" stands for a character " - \ is an escape character and it is the missing part in your solution.

results in:

Title: Extract string between by [" "]

Body:
how can I extract string between [" "]
I have eg: ["x"], so how can I extract just x and assign it to a
variable
I have tried this:

String str = "[x]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

I can get x using the above code but my string is enclosed between [" "]

Body:
The easiest way would be the following:

String s = "aaaa [\"axas\"]";
String result = s.substring(s.indexOf("[\"")+2, s.indexOf("\"]"));

\" stands for a character " - \ is an escape character and it is the missing part in your solution.

results in:


问:
UIDevice.current.setValue(value, forKey: "orientation") does not work if phone held in landscape and tilted 45 - 90 degrees
I'm using

```<code>let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
</code>```

to force the presenting view controller to show in landscape right. This is part of a navigation controller flow. This works as expected, but if the phone is held in landscape and titled between 45 and 90 degrees the view will present in portrait. The method is called and the expected value is correct, but no change to landscape occurs. This can be reproduced in a bare bones project with a navigation controller.

Does anyone have any idea what might cause this behavior?

答:
Try this:

```<code>open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    get {
        return UIInterfaceOrientationMask.landscapeRight
    }
}

open override var shouldAutorotate: Bool {
    get {
        return false
    }
}

open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    get {
        return UIInterfaceOrientation.landscapeRight
    }
}
</code>```

From @Dragos answer on Setting device orientation in Swift iOS

Body:
I'm using

let value = UIInterfaceOrientation.landscapeRight.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

to force the presenting view controller to show in landscape right. This is part of a navigation controller flow. This works as expected, but if the phone is held in landscape and titled between 45 and 90 degrees the view will present in portrait. The method is called and the expected value is correct, but no change to landscape occurs. This can be reproduced in a bare bones project with a navigation controller.

Does anyone have any idea what might cause this behavior?

Body:
Try this:

open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    get {
        return UIInterfaceOrientationMask.landscapeRight
    }
}

open override var shouldAutorotate: Bool {
    get {
        return false
    }
}

open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    get {
        return UIInterfaceOrientation.landscapeRight
    }
}

From @Dragos answer on Setting device orientation in Swift iOS


问:
Akka stream sliding window to control reduce emit to sink by SourceQueue
Update : I put my question in test project  to explain what I mean in detail

=====================================================================

I have Akka source that contiune read from database table, and groupby some key then reduce it. However it seems after I apply reduce function, the data never send to sink, it will contiune reduce since upstream always have data coming.

I read some post, and tried groupedWithin and sliding, but it does not work as I thought, it only group the message to larger part but never make the upstream pause and emit to sink. Following is the code in Akka stream 2.5.2

The Source reduce code:

```<code>source = source
  .groupedWithin(100, FiniteDuration.apply(1, TimeUnit.SECONDS))
  .sliding(3, 1)
  .mapConcat(i -> i)
  .mapConcat(i -> i)
  .groupBy(2000000, i -> i.getEntityName())
  .map(i -> new Pair<>(i.getEntityName(), i))
  .reduce((l, r) ->{ l.second().setAction(r.second().getAction() + l.second().getAction()); return l;})
  .map(i -> i.second())
  .mergeSubstreams();
</code>```

The Sink and run:

```<code>Sink<Object, CompletionStage<Done>> sink =
        Sink.foreach(i -> System.out.println(i))
final RunnableGraph<SourceQueueWithComplete<Object>> run = source.toMat(sink, Keep.left());
run.run(materIalizer);
</code>```

I have also tried .takeWhile(predicated); I use timer to switch predicated value true and false, but it seems it will only take the first switch to false, when I switch back to true it is not restart upstream.

Please help me thanks in advance!

=================================================

Update for

information about the type of elements

Add what I want:
I have class call SystemCodeTracking contains 2 attributes (id, entityName)

I will have list of object: (1, "table1"), (2, "table2"), (3, "table3"),(4, "table1"),(5, "table3")

I would like to groupBy entityName then sum the id , therefore, the result I would like to see is following

```<code>("table1" 1+4),("table3", 3+5),("table2", 2)
</code>```

The code I am doing now is following

```<code>source
.groupBy(2000000, systemCodeTracking -> systemCodeTracking.getEntityName)
.map(systemCodeTracking -> new Pair<String, Integer>(systemCodeTracking.getEntityName, SystemCodeTracking.getId()))
.scan(....)
</code>```

my question right now is more on how to build scan inital state
should I do ?

```<code>scan(new Pair<>("", 0), (first, second) -> first.setId(first.getId() + second.getId()))
</code>```

答:
So what you want, if I understand everything well is:

first, group by id

then group by time window, and inside this time window, sum all the systemCodeTracking.getId()

For the first part, you'll need groupBy. For the second part groupedWithin. However, they do not work the same: the first one will give you subflows, while the second one will give you a flow of lists.

Therefore, we will have to handle them differently.

First, let's write a reducer for your lists:

```<code>private SystemCodeTracking reduceList(List<SystemCodeTracking> list) throws Exception {
    if (list.isEmpty()) {
        throw new Exception();
    } else {
        SystemCodeTracking building = list.get(0);
        building.setId(0L);
        list.forEach(next -> building.setId(building.getId() + next.getId()));
        return building;
    }
}
</code>```

So for each element in the list, we increment the building.id to get the value we want when the whole list has been traversed.

Now you just need to do

```<code>Source<SystemCodeTracking, SourceQueueWithComplete<SystemCodeTracking>> loggedSource = source
    .groupBy(20000, SystemCodeTracking::getEntityName) // group by name
    .groupedWithin(100, FiniteDuration.create(10, TimeUnit.SECONDS)   // for a given name, group by time window (or by packs of 100)
    .filterNot(List::isEmpty)                          // remove empty elements from the flow (if no element has passed in the last second, to avoid error in reducer)
    .map(this::reduceList)                             // reduce each list to sum the ids
    .log("====== doing reduceing ")                    // log each passing element using akka logger, rather than `System.out.println`
    .mergeSubstreams()                                 // merge back all elements with different names
</code>```

Body:
Update : I put my question in test project  to explain what I mean in detail

=====================================================================

I have Akka source that contiune read from database table, and groupby some key then reduce it. However it seems after I apply reduce function, the data never send to sink, it will contiune reduce since upstream always have data coming.

I read some post, and tried groupedWithin and sliding, but it does not work as I thought, it only group the message to larger part but never make the upstream pause and emit to sink. Following is the code in Akka stream 2.5.2

The Source reduce code:

source = source
  .groupedWithin(100, FiniteDuration.apply(1, TimeUnit.SECONDS))
  .sliding(3, 1)
  .mapConcat(i -> i)
  .mapConcat(i -> i)
  .groupBy(2000000, i -> i.getEntityName())
  .map(i -> new Pair<>(i.getEntityName(), i))
  .reduce((l, r) ->{ l.second().setAction(r.second().getAction() + l.second().getAction()); return l;})
  .map(i -> i.second())
  .mergeSubstreams();

The Sink and run:

Sink<Object, CompletionStage<Done>> sink =
        Sink.foreach(i -> System.out.println(i))
final RunnableGraph<SourceQueueWithComplete<Object>> run = source.toMat(sink, Keep.left());
run.run(materIalizer);

I have also tried .takeWhile(predicated); I use timer to switch predicated value true and false, but it seems it will only take the first switch to false, when I switch back to true it is not restart upstream.

Please help me thanks in advance!

=================================================

Update for

information about the type of elements

Add what I want:
I have class call SystemCodeTracking contains 2 attributes (id, entityName)

I will have list of object: (1, "table1"), (2, "table2"), (3, "table3"),(4, "table1"),(5, "table3")

I would like to groupBy entityName then sum the id , therefore, the result I would like to see is following

("table1" 1+4),("table3", 3+5),("table2", 2)

The code I am doing now is following

source
.groupBy(2000000, systemCodeTracking -> systemCodeTracking.getEntityName)
.map(systemCodeTracking -> new Pair<String, Integer>(systemCodeTracking.getEntityName, SystemCodeTracking.getId()))
.scan(....)

my question right now is more on how to build scan inital state
should I do ?

scan(new Pair<>("", 0), (first, second) -> first.setId(first.getId() + second.getId()))

Body:
So what you want, if I understand everything well is:

first, group by id

then group by time window, and inside this time window, sum all the systemCodeTracking.getId()

For the first part, you'll need groupBy. For the second part groupedWithin. However, they do not work the same: the first one will give you subflows, while the second one will give you a flow of lists.

Therefore, we will have to handle them differently.

First, let's write a reducer for your lists:

private SystemCodeTracking reduceList(List<SystemCodeTracking> list) throws Exception {
    if (list.isEmpty()) {
        throw new Exception();
    } else {
        SystemCodeTracking building = list.get(0);
        building.setId(0L);
        list.forEach(next -> building.setId(building.getId() + next.getId()));
        return building;
    }
}

So for each element in the list, we increment the building.id to get the value we want when the whole list has been traversed.

Now you just need to do

Source<SystemCodeTracking, SourceQueueWithComplete<SystemCodeTracking>> loggedSource = source
    .groupBy(20000, SystemCodeTracking::getEntityName) // group by name
    .groupedWithin(100, FiniteDuration.create(10, TimeUnit.SECONDS)   // for a given name, group by time window (or by packs of 100)
    .filterNot(List::isEmpty)                          // remove empty elements from the flow (if no element has passed in the last second, to avoid error in reducer)
    .map(this::reduceList)                             // reduce each list to sum the ids
    .log("====== doing reduceing ")                    // log each passing element using akka logger, rather than `System.out.println`
    .mergeSubstreams()                                 // merge back all elements with different names


问:
Back button from activity 2 closes down the app instead of going to activity 1 in Android 7
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.

Then the whole app closed when pressing back button from the second activity.

I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.

I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.

It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).

Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:

Activity 1:

```<code>Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
</code>```

答:
I think you just misused the Intent constructor. According to the documentation, you used this constructor Intent(String action). The one that you atually want should be this one Intent(Context packageContext, Class<?> cls).

In the first activity (therefore this being the instance of your first activity), you should write:

```<code>Intent glIntent = new Intent(this, astral.worldstriall.GLActivity.class);
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(glIntent);
</code>```

Body:
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.

Then the whole app closed when pressing back button from the second activity.

I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.

I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.

It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).

Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:

Activity 1:

Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

Body:
I think you just misused the Intent constructor. According to the documentation, you used this constructor Intent(String action). The one that you atually want should be this one Intent(Context packageContext, Class<?> cls).

In the first activity (therefore this being the instance of your first activity), you should write:

Intent glIntent = new Intent(this, astral.worldstriall.GLActivity.class);
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(glIntent);


答:
```<code>package soquestion;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SOQuestion {

    public static void main(String[] args) {
        String str = "[\"foo\"] and [\"bar\"]";
        System.out.println("String is: " + str);
        Pattern p = Pattern.compile("\\[\\\"(.*?)\\\"\\]");
        Matcher m = p.matcher(str);
        while (m.find()) {
            System.out.println("Result: " + m.group(1));
        }
    }

}
</code>```

Results in:

```<code>String is: ["foo"] and ["bar"]
Result: foo
Result: bar
</code>```

Title: Extract string between by [" "]

Body:
package soquestion;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SOQuestion {

    public static void main(String[] args) {
        String str = "[\"foo\"] and [\"bar\"]";
        System.out.println("String is: " + str);
        Pattern p = Pattern.compile("\\[\\\"(.*?)\\\"\\]");
        Matcher m = p.matcher(str);
        while (m.find()) {
            System.out.println("Result: " + m.group(1));
        }
    }

}

Results in:

String is: ["foo"] and ["bar"]
Result: foo
Result: bar


问:
androidplot 1.4.3 redraw run-time analysis with JNI getY (idx) access
i did evaluate the run-time performance of a 6 XYSeries plot setup (500 X axis samples) on a nexus 7 2013 with simple synthesized sine waves in the getY (idx) functs and compared it to a JNI getY (idx) based setup where the JNI C++ code simply fetched the data from a buffer within the JNI capsule

here is a simplified setup for the synthesized sine wave generation (example shows one XYSeries)

```<code>public static int  DatCnt = 0 ;
       static long DatSav ;

@Override
public double GetY (int idx) // being called by super.getY (idx), which implements XYSeries
{
  long t0 = 0 ;

  if (DatCnt >    0) { DatCnt-- ; t0 = System.nanoTime () ; }
  if (DatCnt == 499)   DatSav   = t0 ;

  double dat = Sin (idx) * 45 + 50 ;

//if (DatCnt >    0 &&
//    DatCnt <   10) {
//  Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %d", (System.nanoTime () - t0) / 1000, DatCnt)) ;
//}
  if (DatCnt ==   1) {                                                                   ActPlotNew0.Tsum += t0 - DatSav ;
    Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %6d", (t0 - DatSav) / 1000, ActPlotNew0.Tsum / 1000)) ;
  }
  return dat ;
//return Sin (idx) * 45 + 50 ;
}
</code>```

and this is the android monitor output

```<code>06-04 16:14:40.707 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1493 y_523
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_23
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 233989457389
06-04 16:14:40.861 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  33874  33874
06-04 16:14:40.901 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  26428  60302
06-04 16:14:40.938 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24627  84930
06-04 16:14:40.974 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  25299 110229
06-04 16:14:41.010 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  24047 134277
06-04 16:14:41.046 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  25299 159576
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_517
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 272247
06-04 16:14:41.129 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  24322  24322
06-04 16:14:41.165 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  24536  48858
06-04 16:14:41.200 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24688  73547
06-04 16:14:41.236 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  24414  97961
06-04 16:14:41.271 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23895 121856
06-04 16:14:41.305 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  23834 145690
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_37
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 256622
06-04 16:14:41.387 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  23834  23834
06-04 16:14:41.429 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  30395  54229
06-04 16:14:41.473 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  28411  82641
06-04 16:14:41.507 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  23406 106048
06-04 16:14:41.542 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23803 129852
06-04 16:14:41.576 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  24108 153961
</code>```

a vertical scroll will start the loop with the DatUpd () functs being called periodically

```<code>public static long Tstart, Tsum ;

public synchronized void DataUpd ()
{

  LogI (String.format ("sum %d", (System.nanoTime () - Tstart) / 1000)) ;

  DataY_0.DatCnt = 500 ;
  DataY_1.DatCnt = 500 ;
  DataY_2.DatCnt = 500 ;
  DataY_3.DatCnt = 500 ;
  DataY_4.DatCnt = 500 ;
  DataY_5.DatCnt = 500 ;

  Tstart = System.nanoTime () ;
  Tsum   = 0 ;

  Plot.redraw () ;
}
</code>```

the "dat3 25299 110229" shows the exex times for each series (dat0 - dat5), whereas the 1st number is the individual time accumulation from the x-data 0 to 500, and the 2nd is a running time tally ... 25299 us for the dat3 series and 110299 us for dat0 to dat3 and so on ... an average data fetch time per ZYSeries is about 25 ms

the total sum of 272247 us is the time from the 1st DatUpd () call to the next one in the scroll operation ... i didn't have a hook into when the plot redraw process was complete

the total getY (idx) data fetch time for all 6 XYSeries is 159576 us and the total redraw cycle time 272247 us ... 272247 - 159576 = 112671 us

of course i do not have any idea of the percentage of the remaining time (after the fetch time) of 112671 us, which is androidplot time and which is scroll gesture processing

and now to the C++ JNI setup timing

```<code>06-04 17:09:39.783 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1620 y_497
06-04 17:09:39.881 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_16
06-04 17:09:39.882 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 25543273
06-04 17:09:39.947 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36865  36865
06-04 17:09:39.995 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36956  73822
06-04 17:09:40.032 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36224 110046
06-04 17:09:40.085 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  42205 152252
06-04 17:09:40.138 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  41778 194030
06-04 17:09:40.202 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  53955 247985
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_724
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 344085
06-04 17:09:40.293 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36956  36956
06-04 17:09:40.341 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36651  73608
06-04 17:09:40.377 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36315 109924
06-04 17:09:40.429 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  40954 150878
06-04 17:09:40.481 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  40802 191680
06-04 17:09:40.534 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41015 232696
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_4
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 329620
06-04 17:09:40.619 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36712  36712
06-04 17:09:40.666 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36499  73211
06-04 17:09:40.702 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36163 109375
06-04 17:09:40.779 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  63323 172698
06-04 17:09:40.836 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  42266 214965
06-04 17:09:40.888 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41259 256225
</code>```

comparison :

accumulated fetch time is 247985 us

the sine synthesized data fetches take an average 25 ms / series whereas the C++ JNI data fetches take about 40 ms ... 15 ms longer, an increase of 60 % over the sine wave synthesis example

the percentage of the getY (idx) synthesized sine wave generation time portion is unknown and so is what else is happening inside androidplot from one getY (idx) to the next one

25 ms / 500 x-samples is 50 us, 15 ms / 500 x-samples = 30 us   ... assuming that the sine calculation can't take the majority of the 50 us i would say that a single getY (idx) call processing, not counting the data fetch takes maybe 40 to 45 us ...

the C++ JNI data fetch time of 30 us is not lightning fast, but something i have to live with ... 30 us * 500 * 6 = 90 ms for the whole data fetch only portion ... i could do this 10 times / sec if the redraw wouldn't take any time

i use the FastLineAndPointRenderer.Formatter setup

```<code>public static FastLineAndPointRenderer.Formatter LineFormat (int color, int width, int dash, int spc)
{
  Paint paint = new Paint () ;
  paint.setColor (color) ;
  paint.setStyle (Paint.Style.STROKE) ;
  paint.setAntiAlias (false) ;
  paint.setStrokeWidth (PixelUtils.dpToPix (width)) ;
  paint.setPathEffect (new DashPathEffect (
                       new float [] { PixelUtils.dpToPix (dash), PixelUtils.dpToPix (spc) }, 0)) ;

  FastLineAndPointRenderer.Formatter line = new FastLineAndPointRenderer.Formatter (paint.getColor (), null, null) ;
  line.setLinePaint     (paint) ;
  line.setVertexPaint       (null) ;
  line.setPointLabelFormatter (null) ;

  return line ;
}
</code>```

please, can anyone shine a bit more light onto my setup and comment this paper

is there a way to speed it up and still sick with 500 x-points ... that's what's being used in QT on the desktop setup and it's zippy zippy fast

what can be improved and what additional info should i provide

i hope i do not have made too many typos ;)

答:
i switched now the XYSeries interface to the new FastXYSeries and added a minMax () returning the following region

```<code>private RectRegion Region = new RectRegion (0, TApCfgX.SzeX (), 0, TApCfg.SzeY ()) ;
</code>```

where x-max is 50 and y-max = 1000, since the graph has 50 x-values and the y-data is not exceeding 1000

the speed stayed about the same as without it

my setup is a fixed one of 50 x-samples and y = 0 to 1000

i can move the graph via and offset variable in my getY (idx) implementation through a longer buffer

i do not intend to use any built in zoom functions

what would be the conditions where an increase in speed could be noticed

overall i'm very happy with the speed improvement by switching from the (now insane looking) 500 x-samples to 50 samples

i need to either fetch every 10th y-data in my JNI C++ getY (idx) access function or average over all 10 ... todo next

Body:
i did evaluate the run-time performance of a 6 XYSeries plot setup (500 X axis samples) on a nexus 7 2013 with simple synthesized sine waves in the getY (idx) functs and compared it to a JNI getY (idx) based setup where the JNI C++ code simply fetched the data from a buffer within the JNI capsule

here is a simplified setup for the synthesized sine wave generation (example shows one XYSeries)

public static int  DatCnt = 0 ;
       static long DatSav ;

@Override
public double GetY (int idx) // being called by super.getY (idx), which implements XYSeries
{
  long t0 = 0 ;

  if (DatCnt >    0) { DatCnt-- ; t0 = System.nanoTime () ; }
  if (DatCnt == 499)   DatSav   = t0 ;

  double dat = Sin (idx) * 45 + 50 ;

//if (DatCnt >    0 &&
//    DatCnt <   10) {
//  Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %d", (System.nanoTime () - t0) / 1000, DatCnt)) ;
//}
  if (DatCnt ==   1) {                                                                   ActPlotNew0.Tsum += t0 - DatSav ;
    Log.i ("com.efiLabs.PlotXYtst", String.format ("dat0 %6d %6d", (t0 - DatSav) / 1000, ActPlotNew0.Tsum / 1000)) ;
  }
  return dat ;
//return Sin (idx) * 45 + 50 ;
}

and this is the android monitor output

06-04 16:14:40.707 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1493 y_523
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_23
06-04 16:14:40.797 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 233989457389
06-04 16:14:40.861 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  33874  33874
06-04 16:14:40.901 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  26428  60302
06-04 16:14:40.938 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24627  84930
06-04 16:14:40.974 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  25299 110229
06-04 16:14:41.010 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  24047 134277
06-04 16:14:41.046 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  25299 159576
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_517
06-04 16:14:41.069 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 272247
06-04 16:14:41.129 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  24322  24322
06-04 16:14:41.165 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  24536  48858
06-04 16:14:41.200 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  24688  73547
06-04 16:14:41.236 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  24414  97961
06-04 16:14:41.271 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23895 121856
06-04 16:14:41.305 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  23834 145690
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_37
06-04 16:14:41.326 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 256622
06-04 16:14:41.387 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat0  23834  23834
06-04 16:14:41.429 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat1  30395  54229
06-04 16:14:41.473 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat2  28411  82641
06-04 16:14:41.507 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat3  23406 106048
06-04 16:14:41.542 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat4  23803 129852
06-04 16:14:41.576 18061-18061/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: dat5  24108 153961

a vertical scroll will start the loop with the DatUpd () functs being called periodically

public static long Tstart, Tsum ;

public synchronized void DataUpd ()
{

  LogI (String.format ("sum %d", (System.nanoTime () - Tstart) / 1000)) ;

  DataY_0.DatCnt = 500 ;
  DataY_1.DatCnt = 500 ;
  DataY_2.DatCnt = 500 ;
  DataY_3.DatCnt = 500 ;
  DataY_4.DatCnt = 500 ;
  DataY_5.DatCnt = 500 ;

  Tstart = System.nanoTime () ;
  Tsum   = 0 ;

  Plot.redraw () ;
}

the "dat3 25299 110229" shows the exex times for each series (dat0 - dat5), whereas the 1st number is the individual time accumulation from the x-data 0 to 500, and the 2nd is a running time tally ... 25299 us for the dat3 series and 110299 us for dat0 to dat3 and so on ... an average data fetch time per ZYSeries is about 25 ms

the total sum of 272247 us is the time from the 1st DatUpd () call to the next one in the scroll operation ... i didn't have a hook into when the plot redraw process was complete

the total getY (idx) data fetch time for all 6 XYSeries is 159576 us and the total redraw cycle time 272247 us ... 272247 - 159576 = 112671 us

of course i do not have any idea of the percentage of the remaining time (after the fetch time) of 112671 us, which is androidplot time and which is scroll gesture processing

and now to the C++ JNI setup timing

06-04 17:09:39.783 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onDown x_1620 y_497
06-04 17:09:39.881 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_16
06-04 17:09:39.882 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 25543273
06-04 17:09:39.947 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36865  36865
06-04 17:09:39.995 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36956  73822
06-04 17:09:40.032 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36224 110046
06-04 17:09:40.085 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  42205 152252
06-04 17:09:40.138 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  41778 194030
06-04 17:09:40.202 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  53955 247985
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_724
06-04 17:09:40.226 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 344085
06-04 17:09:40.293 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36956  36956
06-04 17:09:40.341 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36651  73608
06-04 17:09:40.377 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36315 109924
06-04 17:09:40.429 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  40954 150878
06-04 17:09:40.481 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  40802 191680
06-04 17:09:40.534 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41015 232696
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: onScroll x_4
06-04 17:09:40.555 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: sum 329620
06-04 17:09:40.619 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rdif  36712  36712
06-04 17:09:40.666 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: rpm   36499  73211
06-04 17:09:40.702 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: tdif  36163 109375
06-04 17:09:40.779 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext0  63323 172698
06-04 17:09:40.836 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: ext1  42266 214965
06-04 17:09:40.888 4067-4067/com.efiLabs.PlotXY2tst I/com.efiLabs.PlotXYtst: raw2  41259 256225

comparison :

accumulated fetch time is 247985 us

the sine synthesized data fetches take an average 25 ms / series whereas the C++ JNI data fetches take about 40 ms ... 15 ms longer, an increase of 60 % over the sine wave synthesis example

the percentage of the getY (idx) synthesized sine wave generation time portion is unknown and so is what else is happening inside androidplot from one getY (idx) to the next one

25 ms / 500 x-samples is 50 us, 15 ms / 500 x-samples = 30 us   ... assuming that the sine calculation can't take the majority of the 50 us i would say that a single getY (idx) call processing, not counting the data fetch takes maybe 40 to 45 us ...

the C++ JNI data fetch time of 30 us is not lightning fast, but something i have to live with ... 30 us * 500 * 6 = 90 ms for the whole data fetch only portion ... i could do this 10 times / sec if the redraw wouldn't take any time

i use the FastLineAndPointRenderer.Formatter setup

public static FastLineAndPointRenderer.Formatter LineFormat (int color, int width, int dash, int spc)
{
  Paint paint = new Paint () ;
  paint.setColor (color) ;
  paint.setStyle (Paint.Style.STROKE) ;
  paint.setAntiAlias (false) ;
  paint.setStrokeWidth (PixelUtils.dpToPix (width)) ;
  paint.setPathEffect (new DashPathEffect (
                       new float [] { PixelUtils.dpToPix (dash), PixelUtils.dpToPix (spc) }, 0)) ;

  FastLineAndPointRenderer.Formatter line = new FastLineAndPointRenderer.Formatter (paint.getColor (), null, null) ;
  line.setLinePaint     (paint) ;
  line.setVertexPaint       (null) ;
  line.setPointLabelFormatter (null) ;

  return line ;
}

please, can anyone shine a bit more light onto my setup and comment this paper

is there a way to speed it up and still sick with 500 x-points ... that's what's being used in QT on the desktop setup and it's zippy zippy fast

what can be improved and what additional info should i provide

i hope i do not have made too many typos ;)

Body:
i switched now the XYSeries interface to the new FastXYSeries and added a minMax () returning the following region

private RectRegion Region = new RectRegion (0, TApCfgX.SzeX (), 0, TApCfg.SzeY ()) ;

where x-max is 50 and y-max = 1000, since the graph has 50 x-values and the y-data is not exceeding 1000

the speed stayed about the same as without it

my setup is a fixed one of 50 x-samples and y = 0 to 1000

i can move the graph via and offset variable in my getY (idx) implementation through a longer buffer

i do not intend to use any built in zoom functions

what would be the conditions where an increase in speed could be noticed

overall i'm very happy with the speed improvement by switching from the (now insane looking) 500 x-samples to 50 samples

i need to either fetch every 10th y-data in my JNI C++ getY (idx) access function or average over all 10 ... todo next


问:
Laravel: Get variable name from route
How can I get the name of the get variable from a route url?

```<code>http://localhost:8000/api/system/123
</code>```

Basically I want to know what the GET variable is called that holds the value of 123. For example here it is called id

```<code>http://localhost:8000/api/system?id=123
</code>```

How can this be done?

```<code>Route::get('api/system/{id}', 'ApiController@User');
</code>```

答:
The route variable is injected in your method.
Laravel takes care of the injection for you, you can read more details about IOC

```<code>class ApiController{

    public function User($id)
    {
    ...
    }
}
</code>```

Read more here

Title: Laravel: Get variable name from route

Body:
How can I get the name of the get variable from a route url?

http://localhost:8000/api/system/123

Basically I want to know what the GET variable is called that holds the value of 123. For example here it is called id

http://localhost:8000/api/system?id=123

How can this be done?

Route::get('api/system/{id}', 'ApiController@User');

Body:
The route variable is injected in your method.
Laravel takes care of the injection for you, you can read more details about IOC

class ApiController{

    public function User($id)
    {
    ...
    }
}

Read more here


问:
C++ how to reveal only one piece of code to user and let them compile
I have a system built in C++, however I only want to reveal only one piece of my source code to users so that they can modify according to their need. Thing is, they still need the rest of the code to compile. What is a good way to hide these code but still make the whole project able to compile? I have considered translating into unreadable code/ compile each file to .so and give it to them. Is there any other suggestion?</p>

答: thx for all the answers in discussion section, I ended up compiling every class into .so files, and keep only the one that was needed to be modified in .cpp. </p>


问:
Is it possible to create web application using Qt?
How to create web application using Qt?</p>

答:
The functionality you are asking for does not exist within Qt itself. However, there exists (at least) one third party library that allows some of the Qt code for a desktop app to be re-used to a certain extent for serving up a web app:

http://cutelyst.org/

However, this does not magically allow you to write a QML interface with QML Widgets and have a visual interface accessible via a web browser.

Body: How to create web application using Qt?


问:
Android Auto, desktop head unit won't start
I develop and app with Android Auto capabilities. I have two computer, one under Windows with no problems and my other under Ubuntu 16.04 (where DHU won't start).

When I start the DHU, I got this message:

```<code>./desktop-head-unit: error while loading shared libraries: libSDL2_ttf-2.0.so.0: cannot open shared object file: No such file or directory
</code>```

I don't know which package should I install to solve this problem...

Tkanks in advance!

答:
You need to install libraries, open terminal, type in the command,

sudo apt-get install libsdl2-2.0-0 libsdl2-ttf-2.0-0 libportaudio2 libpng12-0

see details at https://developer.android.com/training/auto/testing/index.html

Body:
I develop and app with Android Auto capabilities. I have two computer, one under Windows with no problems and my other under Ubuntu 16.04 (where DHU won't start).

When I start the DHU, I got this message:

./desktop-head-unit: error while loading shared libraries: libSDL2_ttf-2.0.so.0: cannot open shared object file: No such file or directory

I don't know which package should I install to solve this problem...

Tkanks in advance!


问:
Permanently change Node call stack size
I want to increase the --stack-size option for nodejs system-wide.

I know I can do this on a per invocation basis like this:

```<code>node --stack-size=10000 <app>
</code>```

But I want to set the stack size system wide to this value for all users and for cron tasks.

I'm on Ubuntu 13.

答:
You can:

Rename /usr/bin/node (or whatever you actual path to node is) to /usr/bin/node_bin

Create shell script in place of old node executable (at /usr/bin/node) with following content:

```#!/bin/bash
/usr/bin/node_bin --stack-size=10000 $@```

This way you don't have to change absolute references to node in all the cron scripts.

Title: Permanently change Node call stack size

Body:
I want to increase the --stack-size option for nodejs system-wide.

I know I can do this on a per invocation basis like this:

node --stack-size=10000 <app>

But I want to set the stack size system wide to this value for all users and for cron tasks.

I'm on Ubuntu 13.

Body:
You can:

Rename /usr/bin/node (or whatever you actual path to node is) to /usr/bin/node_bin

Create shell script in place of old node executable (at /usr/bin/node) with following content:

#!/bin/bash
/usr/bin/node_bin --stack-size=10000 $@

This way you don't have to change absolute references to node in all the cron scripts.


问:
Calculate time of flight of BLE message between 2 Android phones
Maybe to general for SO, feel free to move to any other SO clone when needed.

I would like calculate the distance between 2 android smartphones based on how long it takes for a message send over Bluetooth Low Energy to travel back and forth.

Like:

Device A connects over BLE to device B.

Device A sends message

Device A stores current nanoseconds (T0)

Device B receives message on bluetooth radio (BT0)

Device B process message

Device B raises "message received" event (BT1)

Device B stores current nanoseconds

Device B send acknowledge message back to A with value  BT1 - BTO

Device A receives message on bluetooth radio (AT0)

Device A process message

Device A raises "message received" event (AT1)

Device A stores current nanoseconds (T1)

Total travel time = distance covered = T1 - T0 - (BT1 - BT0) - (AT1 - AT0)

Is it all possible to calculate (BT1 - BT0) and (AT1 - AT0) on Android?

Thank you

答:
No. The clock inaccuracy is allowed to be as much as 50 ppm. Also, packets are allowed to be sent within a 4 microseconds window. These reasons are enough to say your proposal doesn't work.

A bigger reason is that the messages have to be processed by a Bluetooth stack in a non-realtime OS (Android) and must also be transferred over UART to the Bluetooth controller in the phone, which then schedules to transmit the message at the next connection event.

If you could program the firmware for a general microcontroller radio and time the radio with the accuracy of a 16 MHz clock, then you might be able to get some good enough results to measure longer ranges. With the introduction of BLE Long Range in BT5, the controller now have to take the distance into account when calculating the receiver window (which was +-2 microseconds in BT 4).


问:
Eclipse IDE: Add/change default filetypes?
When I create a new file in Eclipse, there's a wide selection of different alternatives appearing in Eclipse.

However I am missing a couple of file which I need to open the "file create wizard" to create - JS files included.

How can I add my own file types as a default choice to appear in the "new files" menu?

Screenshot of the menu I am referring to:

答:
Puuh - just when I had given up I accidentally found this:

Try this: Right click on Eclipse's
  toolbar and choose "Customize this
  perspective" option. You will see a
  dialog box, and on "Shortcuts" tab
  choose "New" from "Submenus:"
  droplist.

Find "PHP" in the left pane and check
  the checkbox next to it. It will
  enable both "PHP File" and "PHP
  Project" in "New" menu of your
  perspective. You can do the same to
  other file editors as well. (HTML,
  CSS,....

http://dev.eclipse.org/newslists/news.eclipse.tools.pdt/msg00228.html

ContentLicense: CC BY-SA 2.5


问:
Filebeat vs Rsyslog for forwarding logs
I am currently using filebeat to forward logs to logstash and then to elasticsearch.

Now, I am thinking about forwarding logs by rsyslog to logstash. The benefit of this would be that, I would not need to install and configure filebeat on every server, and also I can forward logs in JSON format which is easy to parse and filter.

I can use TCP/UDP to forward logs to logstash by rsyslog.

I want to know the more benefits and drawbacks of rsyslog over filebeat, in terms of performance, reliability and ease of use.

答:
When you couple Beats with Logstash you have something called "back pressure management" - Beats will stop flooding the Logstash server with messages in case something goes wrong on the network, for instance.

Another advantage of using Beats is that in Logstash you can have persisted queues, which prevents you from losing log messages in case your elasticsearch cluster goes down. So Logstash will persist messages on disk. Be careful because Logstash can't ensure you wont lose messages if you are using UDP, this link will be helpful.

Title: Filebeat vs Rsyslog for forwarding logs


问:
Template variables based on calculations using fields from Django Model
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions.

My model looks like this:

```<code>class Thing(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    start_date = models.DateTimeField(
        default=timezone.now)
    cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
</code>```

Here are my views:

```<code>def something_list(request):
    things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date')
    return render(request, 'myApp/something_list.html', {'things': things})

def thing_detail(request, pk):
    thing = get_object_or_404(Thing, pk=pk)
    return render(request, 'myApp/thing_detail.html', {'thing': thing})
</code>```

I have two template blocks for each of these views, where I am using template tags to display variables. For example:

```<code><h2 class="title"><a href="{% url 'thing_detail' pk=thing.pk %}">{{ thing.title }}</a></h2>
<p>User: {{ thing.user }}</p>
<div class="date">
    <p>Start Date: {{ thing.start_date }}</p>
</div>
<p>Cost per day: ${{ thing.cost_per_day }}</p>
</code>```

So what is happening here?

Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template.

Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here:

```<code><button type="button" class="btn btn-info">{{ thing.quit_date|timesince }}</button>
</code>```

This renders how many days and hours have elapsed - lets call it 'time elapsed' - perfectly. The problem lies in my next calculation.

Problem 2) I need to display a calculation of 'time elapsed' (shown above) multiplied by the Cost per Day variable in the current Model instance. Just for clarity, let's say the start date was 30.5 days ago, and the cost per day is $5.00. I need to multiply 30.5 by $5.00. I would love to simply multiply template tags but I understand that's not how it works. For example:

```<code>{{ thing.quit_date|timesince }} * {{ thing.cost_per_day }}
</code>```

Is there a way to capture the result of this timesince calculation... {{ thing.quit_date|timesince }}... as a variable? I may not be able to use the timesince feature for this calculation.

Once again, what I ultimately need to do here is to multiply the "time elapsed" by the cost per day, like this: (Time Now - Start Date) * (Cost Per Day).

I don't know how to do this in models.py or views.py. I'm looking for the best practice way to do this using Django and Python 3.6. I'm a newbie and I have searched all day for an answer to my particular problem.

Thanks in advance and please let me know if I need to provide more information!

UPDATE

Here is my updated model based on suggestions, albeit not working (the timesince property needs work):

```<code>from django.db import models
from django.utils import timezone
from datetime import datetime

class Thing(models.Model):
quitter = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
quit_date = models.DateTimeField(default=timezone.now)
cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
notes = models.TextField()

@property
def timesince(self):
    "Time since quit date"
    now = datetime.now()
    then = self.quit_date
    return (now - then)

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day
</code>```

Here is my updated template:

```<code><h4>Here are some calculations for this information...</h4>
    <p>Days since you quit:</p>
    <button type="button" class="btn btn-info">{{ thing.timesince }}</button>
    <hr>
    <p>How much money you have saved:</p>
    <button type="button" class="btn btn-info">{{ thing.savings }}</button>
</code>```

I'm certain the problem lies in the subtraction of the dates. Any insight into that would be very helpful. The template variables {{ }} are working, but there is a missing piece in the model.

By the way, when I concatenated "days" to any datetime variable, it game me errors saying .days it gave me errors. Perhaps there is an issue using both a DateTimeField and a datetime.now() instance?

答:
I would recommend creating a property on the model itself to calculate this. Subtracting the quit date from the current date will give you a timedelta object. From there we can get the days and take it times the cost.

```<code>from django.utils import timezone

class Thing(models.Model):
    ...

    @property
    def cost(self):
        days = (timezone.now().date() - self.quit_date).days
        return days * self.cost_per_day
</code>```

Then your template becomes very simple.

```<code>{{ thing.cost }}
</code>```

Body:
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions.

My model looks like this:

class Thing(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    start_date = models.DateTimeField(
        default=timezone.now)
    cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)

Here are my views:

def something_list(request):
    things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date')
    return render(request, 'myApp/something_list.html', {'things': things})

def thing_detail(request, pk):
    thing = get_object_or_404(Thing, pk=pk)
    return render(request, 'myApp/thing_detail.html', {'thing': thing})

I have two template blocks for each of these views, where I am using template tags to display variables. For example:

{{ thing.title }}

User: {{ thing.user }}

Start Date: {{ thing.start_date }}

Cost per day: ${{ thing.cost_per_day }}

So what is happening here?

Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template.

Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here:

<button type="button" class="btn btn-info">{{ thing.quit_date|timesince }}</button>

This renders how many days and hours have elapsed - lets call it 'time elapsed' - perfectly. The problem lies in my next calculation.

Problem 2) I need to display a calculation of 'time elapsed' (shown above) multiplied by the Cost per Day variable in the current Model instance. Just for clarity, let's say the start date was 30.5 days ago, and the cost per day is $5.00. I need to multiply 30.5 by $5.00. I would love to simply multiply template tags but I understand that's not how it works. For example:

{{ thing.quit_date|timesince }} * {{ thing.cost_per_day }}

Is there a way to capture the result of this timesince calculation... {{ thing.quit_date|timesince }}... as a variable? I may not be able to use the timesince feature for this calculation.

Once again, what I ultimately need to do here is to multiply the "time elapsed" by the cost per day, like this: (Time Now - Start Date) * (Cost Per Day).

I don't know how to do this in models.py or views.py. I'm looking for the best practice way to do this using Django and Python 3.6. I'm a newbie and I have searched all day for an answer to my particular problem.

Thanks in advance and please let me know if I need to provide more information!

UPDATE

Here is my updated model based on suggestions, albeit not working (the timesince property needs work):

from django.db import models
from django.utils import timezone
from datetime import datetime

class Thing(models.Model):
quitter = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
quit_date = models.DateTimeField(default=timezone.now)
cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
notes = models.TextField()

@property
def timesince(self):
    "Time since quit date"
    now = datetime.now()
    then = self.quit_date
    return (now - then)

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day

Here is my updated template:

Here are some calculations for this information...

Days since you quit:

    <button type="button" class="btn btn-info">{{ thing.timesince }}</button>

How much money you have saved:

    <button type="button" class="btn btn-info">{{ thing.savings }}</button>

I'm certain the problem lies in the subtraction of the dates. Any insight into that would be very helpful. The template variables {{ }} are working, but there is a missing piece in the model.

By the way, when I concatenated "days" to any datetime variable, it game me errors saying .days it gave me errors. Perhaps there is an issue using both a DateTimeField and a datetime.now() instance?

Body:
I would recommend creating a property on the model itself to calculate this. Subtracting the quit date from the current date will give you a timedelta object. From there we can get the days and take it times the cost.

from django.utils import timezone

class Thing(models.Model):
    ...

    @property
    def cost(self):
        days = (timezone.now().date() - self.quit_date).days
        return days * self.cost_per_day

Then your template becomes very simple.

{{ thing.cost }}


问:
Create a new Course with Google Apps Script - ClassRoom API
There is an error on line 11 stating:

Requested entity was not found. (line 11, file "Code")

line 11

```<code>createdCourse = Classroom.Courses.get('Bio10');
</code>```

The function:

```<code>function createA_NewCourse() {
  var courseNew,createdCourse;

  courseNew = Classroom.newCourse();

  courseNew.name = "10th Grade Biology";
  courseNew.id = "Bio10";

  Logger.log("course.name " + courseNew.name);//Verify that name was set

  createdCourse = Classroom.Courses.get('Bio10');//Try to get course by ID

  Logger.log(createdCourse)
}
</code>```

How is a new course created in Apps Script?

答:
There are specific values for the ownerId that must be used.  The ownerId specifies the owner of the course.  One of the valid ownerId strings is "me" which is the requesting user.

Other valid owner ID strings are:

the numeric identifier for the user

the email address of the user

The email address of the user is self explanatory.  I don't know where you get the numeric identifier of the user.

Without the ownerId setting being set first, or being set to an invalid string, I was getting an error message:

The caller does not have permission

Body:
There is an error on line 11 stating:

Requested entity was not found. (line 11, file "Code")

line 11

createdCourse = Classroom.Courses.get('Bio10');

The function:

function createA_NewCourse() {
  var courseNew,createdCourse;

  courseNew = Classroom.newCourse();

  courseNew.name = "10th Grade Biology";
  courseNew.id = "Bio10";

  Logger.log("course.name " + courseNew.name);//Verify that name was set

  createdCourse = Classroom.Courses.get('Bio10');//Try to get course by ID

  Logger.log(createdCourse)
}

How is a new course created in Apps Script?


问:
Google Cloud Spanner Single-Region Availability Analysis
Single-Region Spanner is advertised with a 99.99% availability SLA.  In the US-based configuration, there will be exactly three replicas per node, all in Council Bluffs, Iowa.  Can you share information that breaks down why the 99.99% (~one hour of downtime per year) is believable, especially in the case of geographically-local disasters?  I assume that Google has done a thorough analysis, or else it would not advertise the SLA, but I cannot find a detailed paper.

In the event of a regional failure, what recovery procedures will Google carry out and with what recovery time / expected data loss?

(I understand that multi-region may be available, and have seen some pricing data, but will not discuss this here).

答:
Spanner automatically replicates data for high availability. As you stated, regional instances have three full copies of data. The key is that they are replicated across three zones within the region which have independent power, cooling, networking, etc. Zones generally fail independently for each other, so your other replicas can continue serving reads and writes even if one zone goes down. Multi-region provides even greater availability by replicating across regions.

Zonal failures are very rare and would be transparent to your application; Cloud Spanner automatically reroutes requests to replicas that are able to serve the request. It would be even rarer for a region to go down with data loss. Google takes many measures against disasters.

Further out we will expose managed backups, but these would still be stored within Google data centers. We're also working on a Dataflow connector to help you import/export data should you want to manage your own backups.


问:
How to view the actual implementation of C++ headers?
Is it possible to view the under the hood implementation of certain C++ libraries and how?

For example, I would like to see how std::map is implemented. I know it is a balanced tree (red-black tree) but I would like to see the actual implementation. Is this possible?

答: You need the source. For things in glibc (or other open source libraries), that should be available.</p>


问:
Opencart default language doesn't work
I have OpenCart multi language store with Arabic and English, I set the default language to be Arabic, it works well for all devices except on Samsung where it will show the browser's language as a default language. I would like a a way to force the default language for my store to be Arabic.

my Website URL is : Qadooa.com

答:
I got the solution for second language packs for opencart.

bugissue:

not showing icons (like: myaccount, language, etc..)

not putting your default language really to default on live webshops!

solution:
.htaccess.TXT (save this document as .htaccess (no TXT! save with *all documents selected)

then add the following text after line 31 (install Notepad++ to see line numbers):

RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]```

Title: Opencart default language doesn't work


问:
Oracle APEX form based on multiple tables
Can I create a form in APEX which creates/updates records in multiple tables? For example two tables with a one-to-one relationship.</p>

答: If you are using Automated Row Fetch mechanism, you can use two different ARF for two tables. If you want to have more control, you can define your INSERT/UPDATE statements yourself usign Page Processes.


问:
Vue js not rendering a custom component
I'm using this - http://monterail.github.io/vue-multiselect/
Build a single js file with vue and that librarie, but the other code just in script tag. Component is registered. I put some data and it comes empty

It's just a code from "Getting started", nothing special. No one error in console, just empty node. The important thing: i'm using this inside another component with inline-template (upd: same even in root)

That's how file was created with webpack

```<code>window.Vue = require('vue');
window.Multiselect = require('vue-multiselect');
</code>```

Then i just include compiled file and add script

```<code><script>
    Vue.component('multiselect', Multiselect);
    new Vue({
        el: '#vue-app',
        data: {
            options: ['one', 'two'],
            model: ''
        },
        created: function () {},
        computed: {},
        methods: {}
    });
</script>
</code>```

答:
The 'vue-multiselect' module is meant to be imported like so:

```<code>import Multiselect from 'vue-multiselect'
</code>```

By using import, you assign Multiselect to be the value of the default export of the module.

But, because you use require, you are assigning Multiselect to be the module object with a default property containing the component's configuration options. The default export is not being resolved, and the value you're trying to access is in Multiselect.default.

You should either use import, or access the default property when defining the 'multiselect' component:

```<code>Vue.component('multiselect', Multiselect.default);
</code>```

Title: Vue js not rendering a custom component

Body:
I'm using this - http://monterail.github.io/vue-multiselect/
Build a single js file with vue and that librarie, but the other code just in script tag. Component is registered. I put some data and it comes empty

It's just a code from "Getting started", nothing special. No one error in console, just empty node. The important thing: i'm using this inside another component with inline-template (upd: same even in root)

That's how file was created with webpack

window.Vue = require('vue');
window.Multiselect = require('vue-multiselect');

Then i just include compiled file and add script

Body:
The 'vue-multiselect' module is meant to be imported like so:

import Multiselect from 'vue-multiselect'

By using import, you assign Multiselect to be the value of the default export of the module.

But, because you use require, you are assigning Multiselect to be the module object with a default property containing the component's configuration options. The default export is not being resolved, and the value you're trying to access is in Multiselect.default.

You should either use import, or access the default property when defining the 'multiselect' component:

Vue.component('multiselect', Multiselect.default);


问:
Using variables in the values-form in multiple-value-bind
I am trying to implement a function read-from-whole-string in lisp, where it uses the inbuilt function read-from-string.

About read-from-string

read-from-string is used to read an object from a string which can be specified using the keywords :start,:end etc. It returns two values, the object and the position of the next element, which wasn't read. I plan to use this value.

The plan

The plan is to use the second value returned from the read-from-string function, again on itself to insert the value of the keyword :start. But the problem comes with the function multiple-value-bind. We can't:

Initialize a variable in multiple-value-bind.

Use a variable just defined into the values-form.

To be specific, I want to:

```<code>(multiple-value-bind (x (y 0))
         (read-from-string str :Start y)
         y)
</code>```

Any other clean method is appreciated.

答:
```<code>CL-USER 118 > (let ((string "10 2 300 foo \"bar\""))
                (loop with pos and value
                      for start = 0 then pos
                      do (setf (values value pos)
                               (read-from-string string nil string :start start))
                      while (not (eq value string))
                      collect value))
(10 2 300 FOO "bar")

CL-USER 120 > (let ((string "10 2 300 foo \"bar\""))
                (loop for start = 0 then pos
                      for (value pos) = (multiple-value-list
                                         (read-from-string string nil string
                                                           :start start))
                      while (not (eq value string))
                      collect value))
(10 2 300 FOO "bar")
</code>```

Body:
I am trying to implement a function read-from-whole-string in lisp, where it uses the inbuilt function read-from-string.

About read-from-string

read-from-string is used to read an object from a string which can be specified using the keywords :start,:end etc. It returns two values, the object and the position of the next element, which wasn't read. I plan to use this value.

The plan

The plan is to use the second value returned from the read-from-string function, again on itself to insert the value of the keyword :start. But the problem comes with the function multiple-value-bind. We can't:

Initialize a variable in multiple-value-bind.

Use a variable just defined into the values-form.

To be specific, I want to:

(multiple-value-bind (x (y 0))
         (read-from-string str :Start y)
         y)

Any other clean method is appreciated.


问:
tableview max width constraint
I'm trying to set a max width on a tableview inside the default tableview controller in the storyboard. I'm not able to just set a <= width constraint for some reason it's greyed out in xcode.

I would just create a custom tableview inside my view but I've configured somethings that won't work that way with scroll without some work.

I'm trying to restrict the width for a scrolling feed with images so the ipad version isn't full screen. Just max say like 700 or something, any idea how to do that?

Standard xcode tableview controller

custom table view in view controller

This kind of worked, but it jumps into place and shows black bars on the side.

```<code>override func viewDidAppear(_ animated: Bool) {
    let bounds = UIScreen.main.bounds
    if bounds.width > 414 {
        tableView.frame.size.width = CGFloat(600)
        tableView.center.x = bounds.size.width / 2
    }
}
</code>```

答: I'm not sure if you can set the set the width using storyboard with special controllers, I could be wrong. But you could just do tableView.widthAnchor.constraint(equalToConstant: 200).isActive = true and pick whatever constant you want, then use some conditional logic on the view.frame.width to change the constant value for specific situations

Title: tableview max width constraint

Body:
I'm trying to set a max width on a tableview inside the default tableview controller in the storyboard. I'm not able to just set a <= width constraint for some reason it's greyed out in xcode.

I would just create a custom tableview inside my view but I've configured somethings that won't work that way with scroll without some work.

I'm trying to restrict the width for a scrolling feed with images so the ipad version isn't full screen. Just max say like 700 or something, any idea how to do that?

Standard xcode tableview controller

custom table view in view controller

This kind of worked, but it jumps into place and shows black bars on the side.

override func viewDidAppear(_ animated: Bool) {
    let bounds = UIScreen.main.bounds
    if bounds.width > 414 {
        tableView.frame.size.width = CGFloat(600)
        tableView.center.x = bounds.size.width / 2
    }
}


问:
What is the package name of the Android Market or Google Apps
I need to check if the Android Market is installed like this

```<code>    /*
     * Test for existence of Android Market
     */
    boolean androidMarketExists = false;
    try{
        ApplicationInfo info = getPackageManager()
                             .getApplicationInfo("com.google.process.gapps", 0 );
        //application exists
        androidMarketExists = true;
    } catch( PackageManager.NameNotFoundException e ){
        //application doesn't exist
        androidMarketExists = false;
    }
</code>```

But I don't know if com.google.process.gapps is the package that has android market or not.

答:
It's com.android.vending (on my Galaxy S), and here's the better way to find out... by querying for who handles market:// URIs.

```<code>    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("market://search?q=foo"));
    PackageManager pm = getPackageManager();
    List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
</code>```

If the list has at least one entry, the Market's there.

Body:
I need to check if the Android Market is installed like this

    /*
     * Test for existence of Android Market
     */
    boolean androidMarketExists = false;
    try{
        ApplicationInfo info = getPackageManager()
                             .getApplicationInfo("com.google.process.gapps", 0 );
        //application exists
        androidMarketExists = true;
    } catch( PackageManager.NameNotFoundException e ){
        //application doesn't exist
        androidMarketExists = false;
    }

But I don't know if com.google.process.gapps is the package that has android market or not.

Body:
It's com.android.vending (on my Galaxy S), and here's the better way to find out... by querying for who handles market:// URIs.

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("market://search?q=foo"));
    PackageManager pm = getPackageManager();
    List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);

If the list has at least one entry, the Market's there.


问:
Send a huge content range using streams
How to send a part of file using read stream in response on HTTP request?

I want to send an arbitrary Content-Range of a huge file.

I can't use events when I do fs.createReadStream('hugeFile.bin').pipe(response) to filter out a part of readable stream. I can create a fake writable stream, which omits (like > /dev/null) a part of data, but chunk size may be not a multiple of a first part to send.

How to solve the problem?

答:
Take a look at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_createreadstream_path_options.

In particular, the start and end options - these let you set the byte offsets in the file to start and stop reading from.

So basically you'd do:

```<code>fs.createReadStream('hugeFile.bin', { start: firstByte, end: lastByte }).pipe(response)
</code>```

or the moral equivalent and it'd do what you want.

Title: Send a huge content range using streams

Body:
Take a look at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_createreadstream_path_options.

In particular, the start and end options - these let you set the byte offsets in the file to start and stop reading from.

So basically you'd do:

fs.createReadStream('hugeFile.bin', { start: firstByte, end: lastByte }).pipe(response)

or the moral equivalent and it'd do what you want.


问:
Return int[][] array
this might be an ridiculous question, but I don`t make it. I got two arrays this Type:

String[] string{"A", "B", "C"} and
int[][] array {{1, 2, 3},{1, 2, 3}}

and wish to get this output:

A 1 1

B 2 2

C 3 3

I have almost tried every possible for loop, but it does not get in that order.
Thanks a lot for helping me!

答:
Try this:</p>

```<code>// INIT ARRAYS
String[] abcArray = {"A", "B", "C"};
int[][] otherArray = {{1, 2, 3},{1, 2, 3}};

// LOOP ABC ARRAY
for(int x = 0; x < abcArray.length; x++){

    // PRINT
    system.out.println(abcArray[x]+otherArray[0][x]+otherArray[1][x]);

}
</code>```

Title: Return int[][] array

Body:
Try this:

// INIT ARRAYS
String[] abcArray = {"A", "B", "C"};
int[][] otherArray = {{1, 2, 3},{1, 2, 3}};

// LOOP ABC ARRAY
for(int x = 0; x < abcArray.length; x++){

    // PRINT
    system.out.println(abcArray[x]+otherArray[0][x]+otherArray[1][x]);

}