问:
Nginx Reverse proxy in front of WordPress and MySQL slowness
I have the following setup:

1 server with 4 cores / 8 HT (Intel Xeon E3-1231 v3) with 32GB RAM and 2TB HDD
I've installed Proxmox on it. Then I've created a few KVMs:

Nginx Reverse proxy - Public IP 192.168.0.10, Internal IP 10.10.10.10

The IPs are set for example purposes only, the real IPs are different

Nginx which servers only static content website - Only Internal IP 10.10.10.20

Nginx + PHP-FPM which servers WordPress - Only internal IP 10.10.10.30

MySQL - Only internal IP 10.10.10.40

All servers communicates trough the internal network. The "lag" is 0.200ms - 0.350ms

I also have 2 websites:

example.com - pointed via A record to Nginx Reverse Proxy's Public IP 192.168.0.10

wp.example.com - pointed via A record to Nginx Reverse Proxy's Public IP 192.168.0.10

Nginx Reverse Proxy is configured to proxy_pass the requests based on the website entered in the browser.

When you try to load example.com NGINX reverse proxy pass the connection to internal IP 10.10.10.20 where another nginx serves the html website - example.com

So far so good. Everything works good.

However, the issue occur when someone try to enter wp.example.com, NGINX reverse proxy pass the connection to IP 10.10.10.30 where another nginx + php-fpm serves the php files.

So far so good, however I've installed WordPress and use MySQL server which is setup on another KVM with IP 10.10.10.40. Ok. Everything works, however the connection to and from MySQL server seems to be slow, as the entire wordpress website is loading too slow. If only php files are served (without any mysql queries) the website is loading super fast, however when WordPress is installed it makes connections to the databases which is on another server and the things start to work slow...

None of the machines are loading high at all. They have a lot of free CPU, disk space and RAM. However for some reason MySQL (MariaDB 10.2.6) is the bottleneck here... but I do not know why...

Here is the conf file from my NGINX reverse proxy:

```<code>server  {
    listen  80;
    server_name example.com www.example.com;
    location / {
        proxy_pass http://10.10.10.20:80/;
    }
}
server {
    listen 80;
    server_name wp.example.com www.wp.example.com;
    location / {
        proxy_pass http://10.10.10.30:80/;
    }
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
}
</code>```

Here is the nginx conf file from my KVM server who serves PHP website - WordPress:

```<code>server {
    listen       10.10.10.30:80;
    server_name  wp.example.com www.wp.example.com;
    root   /var/www;
    index index.php index.html index.htm;
    location / {
         try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
         root /usr/share/nginx/html;
    }
    location ~ \.php$ {
         try_files $uri =404;
         fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
         fastcgi_index index.php;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         include fastcgi_params;
    }
}
</code>```

How I can troubleshot why WordPress is loading too slow? There aren't packet drops between servers, also the connections are good I think... only 0.200 - 0.350 ms between servers...

I think the slowness occur because WordPress tries to make connections to external addresses but as the server where wordpress "lives" doesn't have public internet connection, this slows the things... I am not sure if this is the reason... but it could be?

答:
Here are the answers to your questions:

I am connecting to the MySQL via IP in wp-config.php

IP.

I am connecting directly to the MySQL, no proxy is used here.

No, I am not using SSL as the MySQL server "lives" in isolated KVM with only private network

No I am not... It is possible to refer me to a guide?

MySQL use HDD, however it has only 1 default WordPress database in it with only a few connections, as I am the only one opening my website...

I am using the default values in my.cnf for now

The MySQL server and the WordPress server is on the same Proxmox node, they are KVM machines inside same Proxmox Node

I've performed some tests, and it seems ONLY a few parts from WP are slow:
navigating to plugins menu from the admin area
navigating to theme menu from the admin area

Also when I login to the admin area.. its slow...

I think this is some how related to the lack of Internet connection... only private network...

Body:
I have the following setup:

1 server with 4 cores / 8 HT (Intel Xeon E3-1231 v3) with 32GB RAM and 2TB HDD
I've installed Proxmox on it. Then I've created a few KVMs:

Nginx Reverse proxy - Public IP 192.168.0.10, Internal IP 10.10.10.10

The IPs are set for example purposes only, the real IPs are different

Nginx which servers only static content website - Only Internal IP 10.10.10.20

Nginx + PHP-FPM which servers WordPress - Only internal IP 10.10.10.30

MySQL - Only internal IP 10.10.10.40

All servers communicates trough the internal network. The "lag" is 0.200ms - 0.350ms

I also have 2 websites:

example.com - pointed via A record to Nginx Reverse Proxy's Public IP 192.168.0.10

wp.example.com - pointed via A record to Nginx Reverse Proxy's Public IP 192.168.0.10

Nginx Reverse Proxy is configured to proxy_pass the requests based on the website entered in the browser.

When you try to load example.com NGINX reverse proxy pass the connection to internal IP 10.10.10.20 where another nginx serves the html website - example.com

So far so good. Everything works good.

However, the issue occur when someone try to enter wp.example.com, NGINX reverse proxy pass the connection to IP 10.10.10.30 where another nginx + php-fpm serves the php files.

So far so good, however I've installed WordPress and use MySQL server which is setup on another KVM with IP 10.10.10.40. Ok. Everything works, however the connection to and from MySQL server seems to be slow, as the entire wordpress website is loading too slow. If only php files are served (without any mysql queries) the website is loading super fast, however when WordPress is installed it makes connections to the databases which is on another server and the things start to work slow...

None of the machines are loading high at all. They have a lot of free CPU, disk space and RAM. However for some reason MySQL (MariaDB 10.2.6) is the bottleneck here... but I do not know why...

Here is the conf file from my NGINX reverse proxy:

server  {
    listen  80;
    server_name example.com www.example.com;
    location / {
        proxy_pass http://10.10.10.20:80/;
    }
}
server {
    listen 80;
    server_name wp.example.com www.wp.example.com;
    location / {
        proxy_pass http://10.10.10.30:80/;
    }
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $host;
}

Here is the nginx conf file from my KVM server who serves PHP website - WordPress:

server {
    listen       10.10.10.30:80;
    server_name  wp.example.com www.wp.example.com;
    root   /var/www;
    index index.php index.html index.htm;
    location / {
         try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
         root /usr/share/nginx/html;
    }
    location ~ \.php$ {
         try_files $uri =404;
         fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
         fastcgi_index index.php;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         include fastcgi_params;
    }
}

How I can troubleshot why WordPress is loading too slow? There aren't packet drops between servers, also the connections are good I think... only 0.200 - 0.350 ms between servers...

I think the slowness occur because WordPress tries to make connections to external addresses but as the server where wordpress "lives" doesn't have public internet connection, this slows the things... I am not sure if this is the reason... but it could be?


来源: stackexchange

问:
Is there any way to know the size of what will be printed to standard output in C++?
For example, if I use the following:

```<code>cout << "hello world";
</code>```

Is there any way to know the size of what's being printed to stdout?

答:
Here's an old school C style way that is still valid C++ as well as modern C++:

```<code>#include <iostream>

int main() {
    // C style but still valid c++
    std::cout << "C style but still valid C++\n";
    char phrase[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
    char phrase2[] = { "hello world" };

    // Adding 1 for the new line character.
    std::cout << "size of phrase[] in bytes = "
              << sizeof(phrase)
              << " + 1 for newline giving total of "
              << sizeof(phrase) + 1
              << " total bytes\n"; // Not Null terminated

    std::cout << "size of phrase2[] in bytes = "
              << sizeof(phrase2)
              << " + 1 for newline giving total of "
              << sizeof(phrase2) + 1
              << " total bytes\n";  // Null terminated

    // Or you can do it more c++ style
    std::cout << "\nC++ style\n";
    // Also adding one for newline character and this string is not null terminated
    std::cout << "size of string in bytes = "
              << std::string("hello world").size()
              << " + 1 for newline giving a total of "
              << std::string("hello world").size() + 1
              << " total bytes\n";

    std::cout << "Press any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}
</code>```

Since each character in C/C++ is 1 byte; all you need is the count of characters including special characters such as space, null terminator, newline etc. That is why there is a sizeof( Type ) operator in C/C++.

Output

```<code>C style but still valid C++
size of phrase[] in bytes = 11 + 1 for newline giving total of 12 total bytes
size of phrase2[] in bytes = 12 + 1 for newline giving total of 13 total bytes

C++ style
size of string in bytes = 11 + 1 for newline giving a total of 12 total bytes
Press any key and enter to quit.
</code>```

Now this will only give you the size of the output before you send it to the ostream's cout object. This also doesn't reflect the added characters of text that is describing this output.

As others have stated you can use stringstream to concatenate a bunch of strings, characters and other data types into the stringstream object with the insertion operator << and then have the stream's member function give you the size in bytes.

It works in the same manner as std::string( ... ).size().

ContentLicense: CC BY-SA 3.0

Body:
For example, if I use the following:

cout << "hello world";

Is there any way to know the size of what's being printed to stdout?

Body:
Here's an old school C style way that is still valid C++ as well as modern C++:

#include <iostream>

int main() {
    // C style but still valid c++
    std::cout << "C style but still valid C++\n";
    char phrase[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
    char phrase2[] = { "hello world" };

    // Adding 1 for the new line character.
    std::cout << "size of phrase[] in bytes = "
              << sizeof(phrase)
              << " + 1 for newline giving total of "
              << sizeof(phrase) + 1
              << " total bytes\n"; // Not Null terminated

    std::cout << "size of phrase2[] in bytes = "
              << sizeof(phrase2)
              << " + 1 for newline giving total of "
              << sizeof(phrase2) + 1
              << " total bytes\n";  // Null terminated

    // Or you can do it more c++ style
    std::cout << "\nC++ style\n";
    // Also adding one for newline character and this string is not null terminated
    std::cout << "size of string in bytes = "
              << std::string("hello world").size()
              << " + 1 for newline giving a total of "
              << std::string("hello world").size() + 1
              << " total bytes\n";

    std::cout << "Press any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}

Since each character in C/C++ is 1 byte; all you need is the count of characters including special characters such as space, null terminator, newline etc. That is why there is a sizeof( Type ) operator in C/C++.

Output

C style but still valid C++
size of phrase[] in bytes = 11 + 1 for newline giving total of 12 total bytes
size of phrase2[] in bytes = 12 + 1 for newline giving total of 13 total bytes

C++ style
size of string in bytes = 11 + 1 for newline giving a total of 12 total bytes
Press any key and enter to quit.

Now this will only give you the size of the output before you send it to the ostream's cout object. This also doesn't reflect the added characters of text that is describing this output.

As others have stated you can use stringstream to concatenate a bunch of strings, characters and other data types into the stringstream object with the insertion operator << and then have the stream's member function give you the size in bytes.

It works in the same manner as std::string( ... ).size().


问:
Convert iOS UISegmentControl to type CFTimeInterval
Using Swift 3, I had a hard-coded value in this statement:

```<code>var lastDisplayLinkTimeStamp: CFTimeInterval!

 if self.lastDisplayLinkTimeStamp >= 30
 {
    totalTimes += 1
  }
</code>```

But now I've set up a segment control to let the user select 30.0, 45.0, or 60.0 as the value instead of the hardcoded value.

I know I can get the text of the title of the selected segment using this:

```<code>durationSegment.titleForSegment(at: durationSegment.selectedSegmentIndex
</code>```

which I think produces a String? (optional String)

But how do I convert the durationSegment.titleForSegment of the text to be accepted in the if statement as a CFTimeInterval or I think Double is also accepted?

I've tried several variations of this using a CFTimeInterval or Double or Float cast

```<code> if self.lastDisplayLinkTimeStamp >= Double(durationSegment.titleForSegment(at: durationSegment.selectedSegmentIndex)
 {
    totalTimes += 1
  }
</code>```

but still get an error like:

Binary operator '>=' cannot be applied to operands of type
  'CFTimeInterval!' and 'Double?'

答:
Don't use the title of the segments. The titles are for display purposes and should not represent your data.

One solution is to create an array of time intervals:

```<code>let possibleTimeIntervals: [CFTimeInterval] = [ 30.0, 45.0, 60.0 ]
</code>```

Then get the value based on the selected segment:

```<code>let selectedSegment = durationSegment.selectedSegmentIndex
if selectedSegment != UISegmentedControlNoSegment {
    let timeInterval = possibleTimeIntervals[selectedSegment]
    if self.lastDisplayLinkTimeStamp >= timeInterval {
        totalTimes += 1
    }
}
</code>```

BTW - you can even use the possibleTimeIntervals array to create the segment titles using a number formatter.

Body:
Using Swift 3, I had a hard-coded value in this statement:

var lastDisplayLinkTimeStamp: CFTimeInterval!

 if self.lastDisplayLinkTimeStamp >= 30
 {
    totalTimes += 1
  }

But now I've set up a segment control to let the user select 30.0, 45.0, or 60.0 as the value instead of the hardcoded value.

I know I can get the text of the title of the selected segment using this:

durationSegment.titleForSegment(at: durationSegment.selectedSegmentIndex

which I think produces a String? (optional String)

But how do I convert the durationSegment.titleForSegment of the text to be accepted in the if statement as a CFTimeInterval or I think Double is also accepted?

I've tried several variations of this using a CFTimeInterval or Double or Float cast

 if self.lastDisplayLinkTimeStamp >= Double(durationSegment.titleForSegment(at: durationSegment.selectedSegmentIndex)
 {
    totalTimes += 1
  }

but still get an error like:

Binary operator '>=' cannot be applied to operands of type
  'CFTimeInterval!' and 'Double?'

Body:
Don't use the title of the segments. The titles are for display purposes and should not represent your data.

One solution is to create an array of time intervals:

let possibleTimeIntervals: [CFTimeInterval] = [ 30.0, 45.0, 60.0 ]

Then get the value based on the selected segment:

let selectedSegment = durationSegment.selectedSegmentIndex
if selectedSegment != UISegmentedControlNoSegment {
    let timeInterval = possibleTimeIntervals[selectedSegment]
    if self.lastDisplayLinkTimeStamp >= timeInterval {
        totalTimes += 1
    }
}

BTW - you can even use the possibleTimeIntervals array to create the segment titles using a number formatter.


问:
Best WPF open source projects
I have programmed with WPF for more than a year. When I started there weren't so many examples and guidelines to follow, now the situation is much more better.

I would like to ask you some help in listing the best WPF (open) source code examples or projects that you suggest to study in order to learn more about project structure, best practices, etc.

Thank you,
Marco

答: If for you it is enough to have the source available (but not really open regarding the license) I still consider very useful FamilyShow (http://www.vertigo.com/FamilyShow.aspx) and Prism (http://www.codeplex.com/CompositeWPF) for an approach at a different "scale".

ContentLicense: CC BY-SA 2.5

Title: Best WPF open source projects

OwnerDisplayName: Fabrizio C.


问:
identifying left recursion in antlr4
A grammar (copied from its manual) reports the following left recursions when
I un-commented the following production: casting_type->constant_primary

```<code>error(119): The following sets of rules are mutually left-recursive [primary, method_call_root, method_call, cast]
  and [casting_type, constant_cast, cast, constant_primary, constant_function_call, function_subroutine_call, primary]
  and [subroutine_call, function_subroutine_call, constant_function_call, constant_primary, method_call, method_call_root, casting_type, primary, constant_cast, cast]
</code>```

The above error report has 3 sets of rules. The third set has 2 left-recursions in it:

casting_type,constant_primary,constant_cast,casting_type

casting_type,constant_primary,constant_function_call,function_subroutine_call,subroutine_call,method_call,method_call_root,primary,cast,casting_type

Since this error was reported after I un-commented one production, I
think it is reasonable to expect to see at least its names in each set (casting_type,constant_primary). Clearly the first set
lacks both these names, so it cannot contain a recursion. And the second set (I cannot give the full
grammar here because it is too long) has recursion-1 and some extra names
which seem not relevant.

My question is: why is Antlr printing the first and the second sets of rules?
Is this a bug in antlr (I tried 4.6 and 4.7, same result), or is this hinting at a problem that I am missing something in these sets?

I saw a similar post elsewhere, where the reported names did not indicate a recursion, but on deeper analysis recursion was found somewhere else.

答: Probably nobody can really answer your question, not even the authors of ANTLR. To me it looks like you get follow-up errors which make not much sense, because a real error made analysis impossible (or at least can lead to wrong conclusions). Of course there can also be a bug in ANTLR, but I recommend to focus on one of the sets and fix that (if you can see what makes them mutually left recursive). Maybe the other errors disappear then or you have to analyze again.</p>

Title: identifying left recursion in antlr4

Body:
A grammar (copied from its manual) reports the following left recursions when
I un-commented the following production: casting_type->constant_primary

error(119): The following sets of rules are mutually left-recursive [primary, method_call_root, method_call, cast]
  and [casting_type, constant_cast, cast, constant_primary, constant_function_call, function_subroutine_call, primary]
  and [subroutine_call, function_subroutine_call, constant_function_call, constant_primary, method_call, method_call_root, casting_type, primary, constant_cast, cast]

The above error report has 3 sets of rules. The third set has 2 left-recursions in it:

casting_type,constant_primary,constant_cast,casting_type

casting_type,constant_primary,constant_function_call,function_subroutine_call,subroutine_call,method_call,method_call_root,primary,cast,casting_type

Since this error was reported after I un-commented one production, I
think it is reasonable to expect to see at least its names in each set (casting_type,constant_primary). Clearly the first set
lacks both these names, so it cannot contain a recursion. And the second set (I cannot give the full
grammar here because it is too long) has recursion-1 and some extra names
which seem not relevant.

My question is: why is Antlr printing the first and the second sets of rules?
Is this a bug in antlr (I tried 4.6 and 4.7, same result), or is this hinting at a problem that I am missing something in these sets?

I saw a similar post elsewhere, where the reported names did not indicate a recursion, but on deeper analysis recursion was found somewhere else.


问:
Retrofit2, getting an array but parsing as object in recyclerview
I'm new to Retrofit2, trying to parse an URL with an array, but it tries to parse it as an object so I get this message. Don't really know where exactly the problem lies.

```<code>java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
</code>```

I've been following this tutorial https://www.learn2crack.com/2016/02/recyclerview-json-parsing.html

Here is my Activity

```<code>public class WordActivity extends AppCompatActivity {
private ListView listView;
private TextView textView;
private RecyclerView recyclerView;
private ArrayList<WordRepo> data;
private WordRecyclerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_info_layout);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    myToolbar.setTitle(Html.fromHtml("<font color='#272d85'>Svenska slangord </font>"));

    //textView = (TextView) findViewById(R.id.textView);
    //listView = (ListView) findViewById(R.id.listView);

    Bundle bundle = this.getIntent().getExtras();
    if (bundle != null) {

        if (bundle.containsKey("posID")) {
            int posid = bundle.getInt("posID");
            getRetro(posid + 1);
        }
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
}

public void getRetro(int categoryID) {

    WordInterface client = ApiClient.getClient().create(WordInterface.class);
    Call<JSONResponse> call = client.getJSON(categoryID);
    call.enqueue(new Callback<JSONResponse>() {

        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            recyclerView = (RecyclerView) findViewById(R.id.recycler_view_words);
            recyclerView.setHasFixedSize(true);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
            recyclerView.setLayoutManager(layoutManager);

            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getList()));
            adapter = new WordRecyclerAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Toast.makeText(WordActivity.this, "error" + t, Toast.LENGTH_LONG).show();
        }

    });
}
</code>```

my Recycleradapter

```<code>public class WordRecyclerAdapter extends
RecyclerView.Adapter<WordRecyclerAdapter.ViewHolder> {
private ArrayList<WordRepo> values;

public WordRecyclerAdapter(ArrayList<WordRepo> values) {
    this.values = values;
}

@Override
public WordRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.recyclerview_words, viewGroup, false);
            return new ViewHolder(view);
}

@Override
public void onBindViewHolder(WordRecyclerAdapter.ViewHolder viewholder, int i) {
    viewholder.word.setText(values.get(i).getWords());
    viewholder.description.setText(values.get(i).getDescription());
}

@Override
public int getItemCount() {
    return values.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView word, description;

    public ViewHolder(View view) {
        super(view);
        word = (TextView) view.findViewById(R.id.word);
        description = (TextView) view.findViewById(R.id.word_description);

    }
}
</code>```

}

Interface

```<code>public interface WordInterface {
@GET("categories/{categoryID}/words")
Call<JSONResponse> getJSON(@Path("categoryID") int categoryID);
}
</code>```

Getter/Setter

```<code>public class WordRepo {
private String name;
private String description;

public String getDescription() {
    return description;
}

public String getWords() {
    return name;
}

}
</code>```

JSONResponse class

```<code>public class JSONResponse {

private WordRepo[] words;

public WordRepo[] getList() {
    return words;
}
</code>```

答:
You just need to set response to your own ArrayList of your Object.
I strongly recommend you define your class to get data.

In my case,

```<code>@Override
public void onResponse(Call<ResponseRidingLogs> call, Response<ResponseRidingLogs> response) {
    if(response.body().header.result_code != 0) {
        // Error handling
    } else {
        ResponseRidingLogs responseRidingLogs = response.body();
        // I have my own header and body: inside body there is arraylist
       List<yourClass> = responseRidingLogs.body();
       //...
    }
    //...
}

public class ResponseRidingLogs {
    public HKRheader header;
    public List<RidingLog> body;
}
</code>```

It's not important whether you add your own header and body in your own protocols or not.
If you use your class definition for JSON communication, you don't need to look inside JSON protocol. You just define "the same class" with server developer.

Body:
I'm new to Retrofit2, trying to parse an URL with an array, but it tries to parse it as an object so I get this message. Don't really know where exactly the problem lies.

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

I've been following this tutorial https://www.learn2crack.com/2016/02/recyclerview-json-parsing.html

Here is my Activity

public class WordActivity extends AppCompatActivity {
private ListView listView;
private TextView textView;
private RecyclerView recyclerView;
private ArrayList<WordRepo> data;
private WordRecyclerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_info_layout);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    getSupportActionBar().setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    myToolbar.setTitle(Html.fromHtml("Svenska slangord "));

    //textView = (TextView) findViewById(R.id.textView);
    //listView = (ListView) findViewById(R.id.listView);

    Bundle bundle = this.getIntent().getExtras();
    if (bundle != null) {

        if (bundle.containsKey("posID")) {
            int posid = bundle.getInt("posID");
            getRetro(posid + 1);
        }
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
}

public void getRetro(int categoryID) {

    WordInterface client = ApiClient.getClient().create(WordInterface.class);
    Call<JSONResponse> call = client.getJSON(categoryID);
    call.enqueue(new Callback<JSONResponse>() {

        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            recyclerView = (RecyclerView) findViewById(R.id.recycler_view_words);
            recyclerView.setHasFixedSize(true);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
            recyclerView.setLayoutManager(layoutManager);

            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getList()));
            adapter = new WordRecyclerAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Toast.makeText(WordActivity.this, "error" + t, Toast.LENGTH_LONG).show();
        }

    });
}

my Recycleradapter

public class WordRecyclerAdapter extends
RecyclerView.Adapter<WordRecyclerAdapter.ViewHolder> {
private ArrayList<WordRepo> values;

public WordRecyclerAdapter(ArrayList<WordRepo> values) {
    this.values = values;
}

@Override
public WordRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.recyclerview_words, viewGroup, false);
            return new ViewHolder(view);
}

@Override
public void onBindViewHolder(WordRecyclerAdapter.ViewHolder viewholder, int i) {
    viewholder.word.setText(values.get(i).getWords());
    viewholder.description.setText(values.get(i).getDescription());
}

@Override
public int getItemCount() {
    return values.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView word, description;

    public ViewHolder(View view) {
        super(view);
        word = (TextView) view.findViewById(R.id.word);
        description = (TextView) view.findViewById(R.id.word_description);

    }
}

}

Interface

public interface WordInterface {
@GET("categories/{categoryID}/words")
Call<JSONResponse> getJSON(@Path("categoryID") int categoryID);
}

Getter/Setter

public class WordRepo {
private String name;
private String description;

public String getDescription() {
    return description;
}

public String getWords() {
    return name;
}

}

JSONResponse class

public class JSONResponse {

private WordRepo[] words;

public WordRepo[] getList() {
    return words;
}

Body:
You just need to set response to your own ArrayList of your Object.
I strongly recommend you define your class to get data.

In my case,

@Override
public void onResponse(Call<ResponseRidingLogs> call, Response<ResponseRidingLogs> response) {
    if(response.body().header.result_code != 0) {
        // Error handling
    } else {
        ResponseRidingLogs responseRidingLogs = response.body();
        // I have my own header and body: inside body there is arraylist
       List<yourClass> = responseRidingLogs.body();
       //...
    }
    //...
}

public class ResponseRidingLogs {
    public HKRheader header;
    public List<RidingLog> body;
}

It's not important whether you add your own header and body in your own protocols or not.
If you use your class definition for JSON communication, you don't need to look inside JSON protocol. You just define "the same class" with server developer.


问:
Node Create Server
I'm new to node Js - I tried to create server with node , this is my code
Node Create Server

it is throwing following error , can anyone guide me to create Server or fix this issue ?
Create Server Error

答: It is syntax error. You wrote on 4. line funtion it is not true. Write function

Title: Node Create Server


问:
Please explain the output of the given code
The code is given below:

```<code>  function a() {
    function makeWorker() {
        this.ename = "Pete";
        return function() {
            console.log(this);
            console.log(this.ename);
        };
    }

    var work = makeWorker();
    work();
}
 var ename = "John";
a();
</code>```

this.name outputs to "Pete".but i have defined another variable ename in the global scope.So why is "Pete" printing instead of "John"?.The  program is running in non-strict mode.

答:
There are several different scopes, in JavaScript. The variable ename is created within the scope of the function. To access the global scoped variables you have to call them a different way.

https://www.w3schools.com/js/js_scope.asp

Body:
The code is given below:

  function a() {
    function makeWorker() {
        this.ename = "Pete";
        return function() {
            console.log(this);
            console.log(this.ename);
        };
    }

    var work = makeWorker();
    work();
}
 var ename = "John";
a();

this.name outputs to "Pete".but i have defined another variable ename in the global scope.So why is "Pete" printing instead of "John"?.The  program is running in non-strict mode.


问:
Importing banner ads (adsense) in chrome extension (external JS required)
I am trying to implement the mobile banner in my chrome extension and I need to have the JS in a separate file as I cannot use internal javascript. How is this done?

The HTML code is as follows:

```<code><script async
src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- meme -->
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:100px"
data-ad-client="ca-pub-1312075280725715"
data-ad-slot="5364641987"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</code>```

Any help would be appreciated. I have been trying to implement ads for months and have a limited understanding of how to.

答:
Don't. It's a violation of the AdSense policies -- if you succeed, your AdSense account will probably be disabled.

Currently, AdSense may not be used to serve ads in Chrome Extensions or Chrome Apps, per AdSense policies.

-- https://developer.chrome.com/webstore/program_policies#ads

(I'm not sure exactly what part of the AdSense policies apply here, but if Google says it's against their own policies, I'm inclined to believe them!)

Body:
I am trying to implement the mobile banner in my chrome extension and I need to have the JS in a separate file as I cannot use internal javascript. How is this done?

The HTML code is as follows:

Any help would be appreciated. I have been trying to implement ads for months and have a limited understanding of how to.


问:
Adding a group of numeric value in a column based on another criteria from another column
I have table in Sheet1.  I can sum up all numeric data of a certain Country.
However I wanted only to sum-up to numbers with the same date.
I have ComboBox for the date.  So for example If I choose July 1, it will only add those numbers in July 1.

My desired result if I choose July 1 is the following:
America     24
Brazil      56
Canada      68

screenshot

My code:

```<code>Private Sub ComboBox1_Change()

Dim a As Long
Dim b As Long
Dim c As Long
Dim lastrow As Long

a = 0
b = 0
c = 0

lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
If Cells(i, 3) = "America" Then
a = Cells(i, 4) + a

ElseIf Cells(i, 3) = "Brazil" Then
b = Cells(i, 4) + b

ElseIf Cells(i, 3) = "Canada" Then
c = Cells(i, 4) + c
End If
Next i

'Range("A16") = a

txtAmerica.Value = a
txtBrazil.Value = b
txtCanada.Value = c

End Sub

Private Sub UserForm_Initialize()

ComboBox1.List = Sheets("Sheet1").Range("G1:G10").Value

End Sub
</code>```

答:
Assuming the values in column A are dates, and also assuming your locale is using a mm/dd/yyyy date format, this is as simple as just wrapping your summation code in an If statement that checks the date:

```<code>For i = 2 To lastrow
    If Cells(i, "A").Value = CDate(ComboBox1.Value) Then
        If Cells(i, 3) = "America" Then
            a = Cells(i, 4) + a
        ElseIf Cells(i, 3) = "Brazil" Then
            b = Cells(i, 4) + b
        ElseIf Cells(i, 3) = "Canada" Then
            c = Cells(i, 4) + c
        End If
    End If
Next i
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have table in Sheet1.  I can sum up all numeric data of a certain Country.
However I wanted only to sum-up to numbers with the same date.
I have ComboBox for the date.  So for example If I choose July 1, it will only add those numbers in July 1.

My desired result if I choose July 1 is the following:
America     24
Brazil      56
Canada      68

screenshot

My code:

Private Sub ComboBox1_Change()

Dim a As Long
Dim b As Long
Dim c As Long
Dim lastrow As Long

a = 0
b = 0
c = 0

lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
If Cells(i, 3) = "America" Then
a = Cells(i, 4) + a

ElseIf Cells(i, 3) = "Brazil" Then
b = Cells(i, 4) + b

ElseIf Cells(i, 3) = "Canada" Then
c = Cells(i, 4) + c
End If
Next i

'Range("A16") = a

txtAmerica.Value = a
txtBrazil.Value = b
txtCanada.Value = c

End Sub

Private Sub UserForm_Initialize()

ComboBox1.List = Sheets("Sheet1").Range("G1:G10").Value

End Sub

Body:
Assuming the values in column A are dates, and also assuming your locale is using a mm/dd/yyyy date format, this is as simple as just wrapping your summation code in an If statement that checks the date:

For i = 2 To lastrow
    If Cells(i, "A").Value = CDate(ComboBox1.Value) Then
        If Cells(i, 3) = "America" Then
            a = Cells(i, 4) + a
        ElseIf Cells(i, 3) = "Brazil" Then
            b = Cells(i, 4) + b
        ElseIf Cells(i, 3) = "Canada" Then
            c = Cells(i, 4) + c
        End If
    End If
Next i


问:
Numpy addition to an element of an array
I am coding a neural network in python, and need to adjust my weights. In order to do so, I need to add my change variable to an element of my weights array. However, I don't know how to do this. The code would look like:

```<code>weights = numpy.array([1, 2, 3])
change = 1
weights[0]+= change
print(weights)
-- [2, 2, 3]
</code>```

I have tried this, but it does not seem to work. Thanks in advance for any answers.

答:
If you're trying to add your variable 'change' to just the first element of the weights array, then your code works fine. if you are trying to add 'change' to all elements of the weights array, simply put

```<code>weights=numpy.array([1,2,3])
change=1
weights+=change
print(weights)
</code>```

this code will add the change to all the elements. I'm assuming that this is what you're trying to do because that would make the most sense in the context of a neural network. if this is not your problem, be more specific on what you are trying to do.

Body:
I am coding a neural network in python, and need to adjust my weights. In order to do so, I need to add my change variable to an element of my weights array. However, I don't know how to do this. The code would look like:

weights = numpy.array([1, 2, 3])
change = 1
weights[0]+= change
print(weights)
-- [2, 2, 3]

I have tried this, but it does not seem to work. Thanks in advance for any answers.

Body:
If you're trying to add your variable 'change' to just the first element of the weights array, then your code works fine. if you are trying to add 'change' to all elements of the weights array, simply put

weights=numpy.array([1,2,3])
change=1
weights+=change
print(weights)

this code will add the change to all the elements. I'm assuming that this is what you're trying to do because that would make the most sense in the context of a neural network. if this is not your problem, be more specific on what you are trying to do.


问:
How to create the equivalent of an SQL Server's identity column in Postgres
There is an application which uses MSSQL as its back end. Now I am developing code so that it may use PostgreSQL. I have almost completed it except there is this one difference when executing:

When saving a new Application,

SQL Server code:

```<code>create table tower
(
  npages integer,
  ifnds integer,
  ifnid integer,
  name varchar(20),
  towid integer not null IDENTITY
)
</code>```

PostgreSQL code :

```<code>create table tower
(
  npages integer,
  ifnds integer,
  ifnid integer,
  name varchar(20)
)
</code>```

Why doesn't the towid field (which is a default field) not get generated automatically when executing through PostgreSQL ?

Any possible reason? Triggers? Procedures?

答:
tl;dr

Now in Postgres 10, specify GENERATED BY DEFAULT AS IDENTITY per the SQL standard.

```<code>create table tower
(
  npages integer,
  ifnds integer,
  ifnid integer,
  name varchar(20),
  towid integer GENERATED BY DEFAULT AS IDENTITY    -- per SQL standard
)
</code>```

Identity column

Postgres 10 now supports the concept of identity column, and uses standard SQL syntax. While I am no expert on MS SQL Server, I believe this new standard support is equivalent.

GENERATED … AS IDENTITY

The GENERATED … AS IDENTITY command used during CREATE TABLE creates an implicit sequence. The creation, naming, permissions, and dropping of that sequence is transparent to you, unlike with SERIAL. Very intuitive now. If you grant a use permission to the table, they get permission for the sequence. If you drop the table, the sequence is dropped automatically.

Two flavors of the standard syntax. The difference matters only if you pass a value rather than let a value be generated. Typically, people always rely on the generated value, so normally you would simply use the first version, GENERATED BY DEFAULT AS IDENTITY.

GENERATED BY DEFAULT AS IDENTITY

Generates a value unless the INSERT command provides a value.

GENERATED ALWAYS AS IDENTITY

Ignores any value provided by INSERT unless specifying OVERRIDING SYSTEM VALUE

See the CREATE TABLE page for documentation.

Read this interesting page by Peter Eisentraut. He explains some weird issues with SERIAL. No such issues with the new identity column feature. So there is no reason to use SERIAL anymore, no downsides, only upsides; SERIAL is supplanted by GENERATED … AS IDENTITY.

Note that an identity column is not necessarily a primary key, and is not automatically indexed. So you still need to specify PRIMARY KEY explicitly if that is your intention (as would be the case typically).

CREATE TABLE person_ (

    id_
        INTEGER
        GENERATED BY DEFAULT AS IDENTITY   -- Replaces SERIAL. Implicitly creates a SEQUENCE, specified as DEFAULT.
        PRIMARY KEY                        -- Creates index. Specifies UNIQUE. Marks column for relationships.
        ,

    name_
        VARCHAR( 80 )

) ;
```

<p>The intention is for the internal implementation details to be hidden from you. No need for you to know the name of the sequence being generated under-the-covers. For example, you can reset the counter via the column without knowing the underlying sequence.</p>

```ALTER TABLE person_
    ALTER COLUMN id_
    RESTART WITH 1000      -- Reset sequence implicitly, without a name.
;
```

<p>Specifying identity implicitly:</p>

<ul>
<li>Marks column <code>NOT NULL</code></li>
<li>Creates a sequence

<ul>
<li>Type of sequence matches the column ( 32-bit 64-bit etc. )</li>
</ul></li>
<li>Ties the sequence to the column

<ul>
<li>Inherits permissions</li>
<li>Cascades dropping</li>
<li>Remains tied to the column even if column renamed</li>
</ul></li>
<li>Specifies the sequence as source of default values for that column</li>
</ul>

<p>The identity column can take the same options as <code>CREATE SEQUENCE</code>:</p>

<ul>
<li><code>START WITH start</code></li>
<li><code>MINVALUE minvalue</code> | <code>NO MINVALUE</code> </li>
<li><code>MAXVALUE maxvalue</code> | <code>NO MAXVALUE</code></li>
<li><code>INCREMENT [ BY ] increment</code></li>
<li><code>CYCLE</code> | <code>NO CYCLE</code></li>
<li><code>CACHE</code> cache</li>
<li><code>OWNED BY NONE</code><br />( specifying ownership for identity column makes no sense to me as ownership is managed automatically )</li>
</ul>

<p>Silly example of options:</p>

```id_ INTEGER
GENERATED BY DEFAULT AS IDENTITY (
    START WITH 200
    MINVALUE 100
    MAXVALUE 205
    CYCLE
    INCREMENT BY 3
) PRIMARY KEY
```

Adding 4 rows:

200

203

100

103

Body:
There is an application which uses MSSQL as its back end. Now I am developing code so that it may use PostgreSQL. I have almost completed it except there is this one difference when executing:

When saving a new Application,

SQL Server code:

create table tower
(
  npages integer,
  ifnds integer,
  ifnid integer,
  name varchar(20),
  towid integer not null IDENTITY
)

PostgreSQL code :

create table tower
(
  npages integer,
  ifnds integer,
  ifnid integer,
  name varchar(20)
)

Why doesn't the towid field (which is a default field) not get generated automatically when executing through PostgreSQL ?

Any possible reason? Triggers? Procedures?

Body:
tl;dr

Now in Postgres 10, specify GENERATED BY DEFAULT AS IDENTITY per the SQL standard.

create table tower
(
  npages integer,
  ifnds integer,
  ifnid integer,
  name varchar(20),
  towid integer GENERATED BY DEFAULT AS IDENTITY    -- per SQL standard
)

Identity column

Postgres 10 now supports the concept of identity column, and uses standard SQL syntax. While I am no expert on MS SQL Server, I believe this new standard support is equivalent.

GENERATED … AS IDENTITY

The GENERATED … AS IDENTITY command used during CREATE TABLE creates an implicit sequence. The creation, naming, permissions, and dropping of that sequence is transparent to you, unlike with SERIAL. Very intuitive now. If you grant a use permission to the table, they get permission for the sequence. If you drop the table, the sequence is dropped automatically.

Two flavors of the standard syntax. The difference matters only if you pass a value rather than let a value be generated. Typically, people always rely on the generated value, so normally you would simply use the first version, GENERATED BY DEFAULT AS IDENTITY.

GENERATED BY DEFAULT AS IDENTITY

Generates a value unless the INSERT command provides a value.

GENERATED ALWAYS AS IDENTITY

Ignores any value provided by INSERT unless specifying OVERRIDING SYSTEM VALUE

See the CREATE TABLE page for documentation.

Read this interesting page by Peter Eisentraut. He explains some weird issues with SERIAL. No such issues with the new identity column feature. So there is no reason to use SERIAL anymore, no downsides, only upsides; SERIAL is supplanted by GENERATED … AS IDENTITY.

Note that an identity column is not necessarily a primary key, and is not automatically indexed. So you still need to specify PRIMARY KEY explicitly if that is your intention (as would be the case typically).

CREATE TABLE person_ (

    id_
        INTEGER
        GENERATED BY DEFAULT AS IDENTITY   -- Replaces SERIAL. Implicitly creates a SEQUENCE, specified as DEFAULT.
        PRIMARY KEY                        -- Creates index. Specifies UNIQUE. Marks column for relationships.
        ,

    name_
        VARCHAR( 80 )

) ;

The intention is for the internal implementation details to be hidden from you. No need for you to know the name of the sequence being generated under-the-covers. For example, you can reset the counter via the column without knowing the underlying sequence.

ALTER TABLE person_
    ALTER COLUMN id_
    RESTART WITH 1000      -- Reset sequence implicitly, without a name.
;

Specifying identity implicitly:

Marks column NOT NULL

Creates a sequence

Type of sequence matches the column ( 32-bit 64-bit etc. )

Ties the sequence to the column

Inherits permissions

Cascades dropping

Remains tied to the column even if column renamed

Specifies the sequence as source of default values for that column

The identity column can take the same options as CREATE SEQUENCE:

START WITH start

MINVALUE minvalue | NO MINVALUE

MAXVALUE maxvalue | NO MAXVALUE

INCREMENT [ BY ] increment

CYCLE | NO CYCLE

CACHE cache

OWNED BY NONE
( specifying ownership for identity column makes no sense to me as ownership is managed automatically )

Silly example of options:

id_ INTEGER
GENERATED BY DEFAULT AS IDENTITY (
    START WITH 200
    MINVALUE 100
    MAXVALUE 205
    CYCLE
    INCREMENT BY 3
) PRIMARY KEY

Adding 4 rows:

200

203

100

103


问:
How to perform animation listview scroll or limit the speed of scroll
How can I bring the item in front off the screen on stop scrolling automatically with animation.Currently it works with following code but it perform very fast with scroll.

So my requirement is to perform this with animation so user can see sliding of listview.

Below is my code,but I did not get expected result.

```<code>listview.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    View child = layout.getChildAt(0);    // first visible child
                    Rect r = new Rect(0, 0, child.getWidth(), child.getHeight());     // set this initially, as required by the docs
                    double height = child.getHeight() * 1.0;
                    layout.getChildVisibleRect(child, r, null);
                    if (Math.abs(r.height()) != height)
                    {
                        //only smooth scroll when not scroll to correct position
                        if (Math.abs(r.height()) < height / 2.0)
                        {
                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(), 10000);
                                }
                            }, 500);
                        } else if (Math.abs(r.height()) > height / 2.0)
                        {
                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(), 10000);
                                }
                            }, 500);
                        } else
                        {

                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(),10000);
                                }
                            },500);

                        }

                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
</code>```

答:
Old question but just for reference, this worked for me:

```<code>    if (condition) {
        // add stuff to begining of ListView and scroll up
        arrayList.add(0, stuff);
        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(0);
            }
        });
    } else {
        // add stuff to end of ListView and scroll down
        arrayList.add(index, stuff);
        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(adapter.getCount() - 1);
            }
        });
    }
</code>```

Basically just smoothScrollToPosition instead of smoothScrollBy.

Body:
How can I bring the item in front off the screen on stop scrolling automatically with animation.Currently it works with following code but it perform very fast with scroll.

So my requirement is to perform this with animation so user can see sliding of listview.

Below is my code,but I did not get expected result.

listview.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    View child = layout.getChildAt(0);    // first visible child
                    Rect r = new Rect(0, 0, child.getWidth(), child.getHeight());     // set this initially, as required by the docs
                    double height = child.getHeight() * 1.0;
                    layout.getChildVisibleRect(child, r, null);
                    if (Math.abs(r.height()) != height)
                    {
                        //only smooth scroll when not scroll to correct position
                        if (Math.abs(r.height()) < height / 2.0)
                        {
                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(), 10000);
                                }
                            }, 500);
                        } else if (Math.abs(r.height()) > height / 2.0)
                        {
                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(), 10000);
                                }
                            }, 500);
                        } else
                        {

                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(),10000);
                                }
                            },500);

                        }

                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

Body:
Old question but just for reference, this worked for me:

    if (condition) {
        // add stuff to begining of ListView and scroll up
        arrayList.add(0, stuff);
        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(0);
            }
        });
    } else {
        // add stuff to end of ListView and scroll down
        arrayList.add(index, stuff);
        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(adapter.getCount() - 1);
            }
        });
    }

Basically just smoothScrollToPosition instead of smoothScrollBy.


问:
How to redirect from axios interceptor with react Router V4?
I want to make a redirection in axios interceptors when receiving a 403 error. But how can I access the history outside React components ?

In Navigating Programatically in React-Router v4, it's in the context of a React Component, but here i'm trying in axios context

```<code>axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    if(error.response.status === 403) { console.log("Redirection needed !"); }

    // Trow errr again (may be need for some other catch)
    return Promise.reject(error);
});
</code>```

答:
I solved that by accessing my Redux Store from outside the Component tree and sending it my same action from the logout button, since my interceptors are created in a separated file and loaded before any Component is loaded.

So, basically, I did the following:

At index.js file:

```<code>//....lots of imports ommited for brevity
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import { UNAUTH_USER } from './actions/types'; //this is just a constants file for action types.

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);

//Here is the guy where I set up the interceptors!
NetworkService.setupInterceptors(store);

//lots of code ommited again...
//Please pay attention to the "RequireAuth" below, we'll talk about it later

ReactDOM.render(
  <Provider store={store}>
      <BrowserRouter>
          <div>
              <Header />
              <main className="plan-container">
                  <Switch>
                      <Route exact path="/" component={Landing} />
                      <Route exact path="/login" component={Login} />
                      <Route exact path="/signup" component={Signup} />
                      <Route exact path="/calendar" component={RequireAuth(Calendar)} />
                      <Route exact path="/profile" component={RequireAuth(Profile)} />
                  </Switch>
              </main>
          </div>
      </BrowserRouter>
  </Provider>
  , document.querySelector('.main-container'));
</code>```

And at the network-service.js file:

```<code>import axios        from 'axios';
import { UNAUTH_USER } from '../actions/types';

export default {
  setupInterceptors: (store) => {

    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        //catches if the session ended!
        if ( error.response.data.token.KEY == 'ERR_EXPIRED_TOKEN') {
            console.log("EXPIRED TOKEN!");
            localStorage.clear();
            store.dispatch({ type: UNAUTH_USER });
        }
        return Promise.reject(error);
    });

  }
};
</code>```

Last, but not least, I have a HOC (Higher Order Component) that I wrap my protected components where I do the actual redirect when the session is out. That way, when I trigger the action type UNAUTH_USER, it sets my isLogged property at my session reducer to false and therefore this component gets notified and does the redirect for me, at any time.

The file for require-auth.js component:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';

export default function(ComposedComponent) {

    class RequireAuth extends Component {

        componentWillMount() {
            if(!this.props.session.isLogged) {
                this.props.history.push('/login');
            }
        };

        componentWillUpdate(nextProps) {
            if(!nextProps.session.isLogged) {
                this.props.history.push('/login');
            }
        };

        render() {
            return <ComposedComponent {...this.props} />
        }
    }

    function mapStateToProps(state) {
        return { session: state.session };
    }

    return connect(mapStateToProps)(RequireAuth);
}
</code>```

Hope that helps!

Body:
I want to make a redirection in axios interceptors when receiving a 403 error. But how can I access the history outside React components ?

In Navigating Programatically in React-Router v4, it's in the context of a React Component, but here i'm trying in axios context

axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    if(error.response.status === 403) { console.log("Redirection needed !"); }

    // Trow errr again (may be need for some other catch)
    return Promise.reject(error);
});

Body:
I solved that by accessing my Redux Store from outside the Component tree and sending it my same action from the logout button, since my interceptors are created in a separated file and loaded before any Component is loaded.

So, basically, I did the following:

At index.js file:

//....lots of imports ommited for brevity
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import { UNAUTH_USER } from './actions/types'; //this is just a constants file for action types.

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);

//Here is the guy where I set up the interceptors!
NetworkService.setupInterceptors(store);

//lots of code ommited again...
//Please pay attention to the "RequireAuth" below, we'll talk about it later

ReactDOM.render(
  <Provider store={store}>
      <BrowserRouter>
          <div>
              <Header />
              <main className="plan-container">
                  <Switch>
                      <Route exact path="/" component={Landing} />
                      <Route exact path="/login" component={Login} />
                      <Route exact path="/signup" component={Signup} />
                      <Route exact path="/calendar" component={RequireAuth(Calendar)} />
                      <Route exact path="/profile" component={RequireAuth(Profile)} />
                  </Switch>
              </main>
          </div>
      </BrowserRouter>
  </Provider>
  , document.querySelector('.main-container'));

And at the network-service.js file:

import axios        from 'axios';
import { UNAUTH_USER } from '../actions/types';

export default {
  setupInterceptors: (store) => {

    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        //catches if the session ended!
        if ( error.response.data.token.KEY == 'ERR_EXPIRED_TOKEN') {
            console.log("EXPIRED TOKEN!");
            localStorage.clear();
            store.dispatch({ type: UNAUTH_USER });
        }
        return Promise.reject(error);
    });

  }
};

Last, but not least, I have a HOC (Higher Order Component) that I wrap my protected components where I do the actual redirect when the session is out. That way, when I trigger the action type UNAUTH_USER, it sets my isLogged property at my session reducer to false and therefore this component gets notified and does the redirect for me, at any time.

The file for require-auth.js component:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default function(ComposedComponent) {

    class RequireAuth extends Component {

        componentWillMount() {
            if(!this.props.session.isLogged) {
                this.props.history.push('/login');
            }
        };

        componentWillUpdate(nextProps) {
            if(!nextProps.session.isLogged) {
                this.props.history.push('/login');
            }
        };

        render() {
            return <ComposedComponent {...this.props} />
        }
    }

    function mapStateToProps(state) {
        return { session: state.session };
    }

    return connect(mapStateToProps)(RequireAuth);
}

Hope that helps!


问:
Angular - Child routing not working
EDIT SOLUTION:

I ended up having to navigate by using something like this (which differs slightly from the code below)

```<code>  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if (menuItem == 'Upload') {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:adminupload)');
    }
    else if (menuItem == "Download") {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:admindownload)');
    }
  }
</code>```

I'm not sure why it has to be done this way, or why if there is another way to do it, but this gives me the expected behavior.

I'm using Angular and I'm trying to have a named router-outlet in one of my views.  Unfortunately, nothing seems to be working at all.  My goal is to get the router-outlet named 'admin-viewport' found on the 'http://localhost:4200/adminhome' page to show the 'AdminUploadComponent' and it's related view.

As of now, the parent html, http://localhost:4200/adminhome, which I can successfully navigate to looks like this:

```<code><div class="home-root">
  <ul class="home-menu"  ng-controller="AdminHomeComponent">
    <li *ngFor="let menuString of menuStrings"
        [class.selected]="menuString === selectedMenuItem"
        (click)="onSelect(menuString)">
      <span class="badge">*</span>{{menuString}}
    </li>
  </ul>
  <router-outlet name="admin-viewport"></router-outlet>
</div>
</code>```

And the routes in my app.module.ts looks like this:

```<code>RouterModule.forRoot([
{
  path: 'adminlogin',
  component: AdminLoginComponent
},
{
  path: 'search',
  component: SearchQueryComponent
},
{
  path: 'adminhome',
  component: AdminHomeComponent,
  children : [
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport'
    },
  ]
}
</code>```

],
  { enableTracing: true }
)

On a button click, I attempt to navigate my outlet using this code.:

```<code>  constructor( private router: Router,public route: ActivatedRoute) {
  }

  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if( menuItem == 'Upload' )
    {
      this.router.navigate(['/adminhome/adminupload', {outlet : 'admin-viewport'}]);
    }
  }
</code>```

Which of course throws the following error:

```<code>error_handler.ts:1 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'
Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'
</code>```

Any help on how to navigate my child router-outlet would be greatly appreciated.

EDIT: When I list my routes after implementing @Seejatheran's suggestion, it still doesn't work and I get this this when I list my paths.

答:
You need to define another path under children,</p>

```<code>{
  path: 'adminhome',
  component: AdminHomeComponent,
  children : [
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport'
    },
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport/:type'
    },
  ]
}
</code>```

Title: Angular - Child routing not working

Body:
EDIT SOLUTION:

I ended up having to navigate by using something like this (which differs slightly from the code below)

  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if (menuItem == 'Upload') {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:adminupload)');
    }
    else if (menuItem == "Download") {
      this.router.navigateByUrl('/adminhome/(adminhomeviewport:admindownload)');
    }
  }

I'm not sure why it has to be done this way, or why if there is another way to do it, but this gives me the expected behavior.

I'm using Angular and I'm trying to have a named router-outlet in one of my views.  Unfortunately, nothing seems to be working at all.  My goal is to get the router-outlet named 'admin-viewport' found on the 'http://localhost:4200/adminhome' page to show the 'AdminUploadComponent' and it's related view.

As of now, the parent html, http://localhost:4200/adminhome, which I can successfully navigate to looks like this:

      *{{menuString}}

  <router-outlet name="admin-viewport"></router-outlet>

And the routes in my app.module.ts looks like this:

RouterModule.forRoot([
{
  path: 'adminlogin',
  component: AdminLoginComponent
},
{
  path: 'search',
  component: SearchQueryComponent
},
{
  path: 'adminhome',
  component: AdminHomeComponent,
  children : [
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport'
    },
  ]
}

],
  { enableTracing: true }
)

On a button click, I attempt to navigate my outlet using this code.:

  constructor( private router: Router,public route: ActivatedRoute) {
  }

  onSelect(menuItem: string): void {
    this.selectedMenuItem = menuItem;
    if( menuItem == 'Upload' )
    {
      this.router.navigate(['/adminhome/adminupload', {outlet : 'admin-viewport'}]);
    }
  }

Which of course throws the following error:

error_handler.ts:1 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'
Error: Cannot match any routes. URL Segment: 'adminhome/adminupload;outlet=admin-viewport'

Any help on how to navigate my child router-outlet would be greatly appreciated.

EDIT: When I list my routes after implementing @Seejatheran's suggestion, it still doesn't work and I get this this when I list my paths.

Body:
You need to define another path under children,

{
  path: 'adminhome',
  component: AdminHomeComponent,
  children : [
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport'
    },
    {
      path: 'adminupload',
      component: AdminUploadComponent,
      outlet: 'admin-viewport/:type'
    },
  ]
}


答:
makeWorker is kind of redundant here if a() is called without a this anyway, so let’s replace the call to makeWorker with what it does:

```<code>function a() {
    this.ename = "Pete";
    var work = function() {
        console.log(this);
        console.log(this.ename);
    };
    work();
}

var ename = "John";
a();
</code>```

and replace the call to work with what it does:

```<code>function a() {
    this.ename = "Pete";
    console.log(this);
    console.log(this.ename);
}

var ename = "John";
a();
</code>```

and replace the call to a with what it does, assuming again that this is the global object:

```<code>var ename = "John";
this.ename = "Pete";
console.log(this);
console.log(this.ename);
</code>```

So you set the global ename to "John", then set it to "Pete", then print it and the result is "Pete". Nothing weird. It might help you to log something when each assignment happens in the original code:

function a() {
    function makeWorker() {
        console.log("Setting ename to Pete");
        this.ename = "Pete";
        return function() {
            console.log(this.ename);
        };
    }

    var work = makeWorker();
    work();
}

console.log("Setting ename to John");
var ename = "John";
a();```

Title: Please explain the output of the given code

Body:
makeWorker is kind of redundant here if a() is called without a this anyway, so let’s replace the call to makeWorker with what it does:

function a() {
    this.ename = "Pete";
    var work = function() {
        console.log(this);
        console.log(this.ename);
    };
    work();
}

var ename = "John";
a();

and replace the call to work with what it does:

function a() {
    this.ename = "Pete";
    console.log(this);
    console.log(this.ename);
}

var ename = "John";
a();

and replace the call to a with what it does, assuming again that this is the global object:

var ename = "John";
this.ename = "Pete";
console.log(this);
console.log(this.ename);

So you set the global ename to "John", then set it to "Pete", then print it and the result is "Pete". Nothing weird. It might help you to log something when each assignment happens in the original code:

function a() {
    function makeWorker() {
        console.log("Setting ename to Pete");
        this.ename = "Pete";
        return function() {
            console.log(this.ename);
        };
    }

    var work = makeWorker();
    work();
}

console.log("Setting ename to John");
var ename = "John";
a();


问:
How does this C++ unordered_map have four values? I thought it was a key value pair
I came across the following code: unordered_map<id, id, hashid, eqid> map

All the unordered maps I've seen only have two "params", the key and value types, what do the other two do?

答:
Read the docs. The template takes up to five parameters, but the last three are defaulted:

```<code>template<
    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;
</code>```

It still stores key and value, but it's using a custom hash and equality testing function.

Body:
Read the docs. The template takes up to five parameters, but the last three are defaulted:

template<
    class Key,
    class T,
    class Hash = std::hash<Key>,
    class KeyEqual = std::equal_to<Key>,
    class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;

It still stores key and value, but it's using a custom hash and equality testing function.


问:
Domain index in materialized view return zero rows
I have problem with Oracle DB - domain index returns zero rows after search by CONTAINS() on materialized view. I see that materialized view is filled with data and I also used procedure ctx_ddl.sync_index() for domain index synchronization.

What works good:

CREATE TABLE

INSERT DATA

CREATE DOMAIN INDEX

SYNC DOMAIN INDEX

FIND ROWS BY CONTAINS - RETURN ROWS

What is not working:

CREATE TABLE

INSERT DATA

CREATE MATERIALIZED VIEW

REFRESH MATERIALIZED VIEW

CREATE DOMAIN INDEX IN MATERIALIZED VIEW

SYNC DOMAIN INDEX IN MATERIALIZED VIEW

FIND ROWS BY CONTAINS IN MATERIALIZED VIEW - RETURN ZERO ROWS (LIKE %TERM% WORKS)

Why everything works fine without materialized view?
Here is my queries (you can copy-paste and try it in your oracle db):

--create table
CREATE TABLE "PCOUNTERPARTY" ( "ID_COUNTERPARTY" NUMBER(10,0), "TXT_SEARCH_FULL_NAME" NVARCHAR2(260), CONSTRAINT "PCOUNTERPARTY_PK" PRIMARY KEY ("ID_COUNTERPARTY"));

--INSERT DATA.
Insert into PCOUNTERPARTY (ID_COUNTERPARTY,TXT_SEARCH_FULL_NAME) values (1184,'MARTINKO3');

--create materialized view
CREATE MATERIALIZED VIEW m_pcounterparty
AS
SELECT c.ID_COUNTERPARTY, CAST( c.TXT_SEARCH_FULL_NAME AS varchar2(260 CHAR) ) as txt_search_full_name_all
FROM PCOUNTERPARTY c;

--create domain index
create index IDXM_1_pcounterparty on m_pcounterparty(TXT_SEARCH_FULL_NAME_ALL) indextype is ctxsys.context PARAMETERS ('SYNC ( ON COMMIT)');

--refresh of materialized view
EXECUTE DBMS_MVIEW.REFRESH('M_PCOUNTERPARTY');
--refresh of index
exec ctx_ddl.sync_index('IDXM_1_pcounterparty');

--search in materialized view
SELECT
    TXT_SEARCH_FULL_NAME_ALL
from
   M_PCOUNTERPARTY c
WHERE
   CONTAINS(c.TXT_SEARCH_FULL_NAME_ALL, 'martin', 1) > 0; --return ZERO and THIS IS PROBLEM
   --c.TXT_SEARCH_FULL_NAME_ALL LIKE '%MARTIN%'; -- return rows but we want search thru CONTAINS

答:
Oracle Text indexes normally search words, not strings.

A wildcard is not necessary to search for "martin" in "Martin Luther King Jr."  But a wildcard is necessary to search for "martin" in "MARTINKO3".

Change the CONTAINS predicate to this:

```<code>CONTAINS(c.TXT_SEARCH_FULL_NAME_ALL, 'martin%', 1) > 0;
</code>```

I ran tests on Oracle 12.2 and could not find any differences in behavior between using a table or a materialized view.  Perhaps there was a test mistake or a very specific bug that caused the text indexes to act differently on your system.

Body:
Oracle Text indexes normally search words, not strings.

A wildcard is not necessary to search for "martin" in "Martin Luther King Jr."  But a wildcard is necessary to search for "martin" in "MARTINKO3".

Change the CONTAINS predicate to this:

CONTAINS(c.TXT_SEARCH_FULL_NAME_ALL, 'martin%', 1) > 0;

I ran tests on Oracle 12.2 and could not find any differences in behavior between using a table or a materialized view.  Perhaps there was a test mistake or a very specific bug that caused the text indexes to act differently on your system.


答:
It looks like you are executing the makeWorker and it is simple overriding the variable ename, and you are wanting to access a global variable.

Check out this article.
How to access global variable in function hook in javascript?

Body:
The code is given below:

  function a() {
    function makeWorker() {
        this.ename = "Pete";
        return function() {
            console.log(this);
            console.log(this.ename);
        };
    }

    var work = makeWorker();
    work();
}
 var ename = "John";
a();

this.name outputs to "Pete".but i have defined another variable ename in the global scope.So why is "Pete" printing instead of "John"?.The  program is running in non-strict mode.


答:
It doesn't have four values: it has four template parameters (five, actually, it needs an allocator). The hashid is the hash function used, and the eqid is the predicate to check for item equality.

To efficiently look up items, it uses the hash of the key to find the correct bucket. This defaults to std::hash<key_type>.

Since you might have multiple values with the same hash  due to collisions, you also need a predicate to check for item equality. This defaults to std::equal_to<key_type>.

Title: How does this C++ unordered_map have four values? I thought it was a key value pair

Body:
I came across the following code: unordered_map<id, id, hashid, eqid> map

All the unordered maps I've seen only have two "params", the key and value types, what do the other two do?


问:
Encoding float constants as extremely long binary strings
Recently, I've been trying to implement the 15 tests for randomness described in NIST SP800-22.  As a check of my function implementation, I have been running the examples that the NIST document provides for each of it's tests.  Some of these tests require bit strings that are very long (up to a million bits).  For example, on one of the examples, the input is "the first 100,000 bits of e."  That brings up the question:  how do I generate a bit representation of a float value that exceeds the precision available for floating point numbers in Python?

I have found articles converting integers to binary strings (the bin() function), and converting floating point fractions to binary (repeated division by 2 (slow!) and limited by floating point precision).  I've considered constructing it iteratively in some way using $e=\sum_{n=0}^{\infty}\frac{2n+2}{(2n+1)!}$, calculating the next portion value, converting it to a binary representation, and somehow adding it to the cumulative representation (still thinking through how to do this).  However, I've hit the same wall going down this path:  the precision of the floating point values as I go farther out on this sum.

Does anyone have some suggestions on creating arbitrarily long bit strings from arbitrarily precise floating point values?

PS - Also, is there any way to get my Markdown math equation above to render properly here? :-)

答:
I maintain the gmpy2 library and its supports arbitrary-precision binary arithmetic. Here is an example of generating the first 100 bits of e.

```<code>>>> import gmpy2
>>> gmpy2.get_context().precision=100
>>> gmpy2.exp(1).digits(2)[0]
'101011011111100001010100010110001010001010111011010010101001101010101
1111101110001010110001000000010'
</code>```

Body:
I maintain the gmpy2 library and its supports arbitrary-precision binary arithmetic. Here is an example of generating the first 100 bits of e.

>>> import gmpy2
>>> gmpy2.get_context().precision=100
>>> gmpy2.exp(1).digits(2)[0]
'101011011111100001010100010110001010001010111011010010101001101010101
1111101110001010110001000000010'


问:
Creating and populating a dictionary in jinja2
```<code>import jinja2
from jinja2 import Template

records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]

t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key =  str(item['a'])+str(item['b'])+str(item['c']) %}
{% if key in record_info %}
{% set record_info.key += 1 %}
{% else %}
{% set record_info.key = 1 %}
{% endif %}
{% endfor %}
{{record_info}}""")
</code>```

This gives me:

```<code>Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 945, in __new__
    return env.from_string(source, template_class=cls)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 880, in from_string
    return cls.from_code(self, self.compile(source), globals, None)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 591, in compile
    self.handle_exception(exc_info, source_hint=source_hint)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<unknown>", line 6, in template
jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got '.'
</code>```

What am I doing wrong ?

答:
I was able to do it like this, any improvements?</p>

```<code>records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]
t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key =  item['a'] ~ ':' ~ item['b'] ~ ':' ~ item['c'] %}
{% if key in record_info %}
{% set _dummy = record_info.update( {key: record_info[key]+1 })  %}
{% else %}
{% set _dummy = record_info.update({ key:1 }) %}
{% endif %}
{% endfor %}
{{record_info}}""")
print t.render(records=records)

{u'1:1:1': 2, u'3:1:1': 1, u'2:1:1': 1}
</code>```

Body:
import jinja2
from jinja2 import Template

records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]

t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key =  str(item['a'])+str(item['b'])+str(item['c']) %}
{% if key in record_info %}
{% set record_info.key += 1 %}
{% else %}
{% set record_info.key = 1 %}
{% endif %}
{% endfor %}
{{record_info}}""")

This gives me:

Traceback (most recent call last):
  File "<stdin>", line 11, in <module>
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 945, in __new__
    return env.from_string(source, template_class=cls)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 880, in from_string
    return cls.from_code(self, self.compile(source), globals, None)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 591, in compile
    self.handle_exception(exc_info, source_hint=source_hint)
  File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<unknown>", line 6, in template
jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got '.'

What am I doing wrong ?

Body:
I was able to do it like this, any improvements?

records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]
t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key =  item['a'] ~ ':' ~ item['b'] ~ ':' ~ item['c'] %}
{% if key in record_info %}
{% set _dummy = record_info.update( {key: record_info[key]+1 })  %}
{% else %}
{% set _dummy = record_info.update({ key:1 }) %}
{% endif %}
{% endfor %}
{{record_info}}""")
print t.render(records=records)

{u'1:1:1': 2, u'3:1:1': 1, u'2:1:1': 1}


问:
How to access mysql server within a server?
I am running mysql on a linux server. I have the linux server IP and mysql runs on localhost on that linux server. Now how do I access mysql running on localhost server remotely?

I can do this by ssh into linux server then running mysql, but how would I do it with in a php script? For example...

```<code><?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
   $conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
           $password);

   // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
}
catch(PDOException $e)
{
  echo "Connection failed: " . $e->getMessage();
}
?>
</code>```

(this script only connects to mysql directly which is not possible remotely)

In my script I would need to access linux server then mysql server unless there is a way to access mysql directly (remotely). How is this achievable?

答:
In order to access your mysql instance from your server; you need to install workbench (or some other mySql explorer) on your development machine. </p>

<p>Create a connection to mysql instance using server ip address as host name and provide username and password to open connection. If every thing goes well you will see your databases in explorer. </p>

Body:
I am running mysql on a linux server. I have the linux server IP and mysql runs on localhost on that linux server. Now how do I access mysql running on localhost server remotely?

I can do this by ssh into linux server then running mysql, but how would I do it with in a php script? For example...

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
   $conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
           $password);

   // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
}
catch(PDOException $e)
{
  echo "Connection failed: " . $e->getMessage();
}
?>

(this script only connects to mysql directly which is not possible remotely)

In my script I would need to access linux server then mysql server unless there is a way to access mysql directly (remotely). How is this achievable?

Body:
In order to access your mysql instance from your server; you need to install workbench (or some other mySql explorer) on your development machine.

Create a connection to mysql instance using server ip address as host name and provide username and password to open connection. If every thing goes well you will see your databases in explorer.


问:
onClick event - Run a javascript AFTER previous one has finished in the same onClick event
Code looks like this (My PHP server generates this line replacing the %% variables):

```<code><button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;
</code>```

I want THIS

```<code>ShowFieldTotal('inv_items','iprice','sub-total',2);
</code>```

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:

```<code>ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')
</code>```

答:
Modify your ServInfo function like this.</p>

```<code>function ServInfo (args...) {
    --- your code ---
    ....
    ....

    //call ShowFieldTotal when ServInfo() is finished.
    ShowFieldTotal(args...);
}
</code>```

Body:
Code looks like this (My PHP server generates this line replacing the %% variables):

<button type="submit" id="buttons" name="add_to_inv" onclick="ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y');ShowFieldTotal('inv_items','iprice','sub-total',2);">+</button>;

I want THIS

ShowFieldTotal('inv_items','iprice','sub-total',2);

to run ONLY when the elements of the first script have been added on my webpage. Basically, it adds an item line in a table and, what I actually want it to do that I can't do, calculate the total of each items once their lines have been added to the table from the first script:

ServInfo('inv_items','/magagest/index.php','req=add_item&item=%icode% - %idesc%&iqty=%iqty%&iprice=%iprice%&itnum='+trCount('inv_items',false),'','y')

Body:
Modify your ServInfo function like this.

function ServInfo (args...) {
    --- your code ---
    ....
    ....

    //call ShowFieldTotal when ServInfo() is finished.
    ShowFieldTotal(args...);
}


问:
How to check address (category city:mtm) and get particular user details from json using typescript in my .ts file?
I have give below my json.

I need to check the address category type city. but i am able to get
  the output. I have given below is my json object.

```<code>[
  {
    "username": "ramu",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "654654",
        "personal": [
          {
            "age": "26",
            "color": "white"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "76755624",
        "personal": [
          {
            "age": "26",
            "color": "green"
          }
        ]
      }
    ]
  },
  {
    "username": "raju",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "521001",
        "personal": [
          {
            "age": "26",
            "color": "red"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "600024",
        "personal": [
          {
            "age": "26",
            "color": "blue"
          }
        ]
      }
    ]
  }
]
</code>```

Any body help me to check(address category city:mtm) and get particular user details only?

答:
With your json even if you filter by city="mtm" it will return all the values from the current json. Assuming you have a different json and you can do as follows.

DEMO

var myArray = [
  {
    "username": "ramu",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "654654",
        "personal": [
          {
            "age": "26",
            "color": "white"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "76755624",
        "personal": [
          {
            "age": "26",
            "color": "green"
          }
        ]
      }
    ]
  },
  {
    "username": "raju",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "521001",
        "personal": [
          {
            "age": "26",
            "color": "red"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "600024",
        "personal": [
          {
            "age": "26",
            "color": "blue"
          }
        ]
      }
    ]
  }
];

let filteredArray = myArray
  .filter((element) =>
    element.address.some((address) => address.city === 'mtm'));

console.log(filteredArray);```

Body:
I have give below my json.

I need to check the address category type city. but i am able to get
  the output. I have given below is my json object.

[
  {
    "username": "ramu",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "654654",
        "personal": [
          {
            "age": "26",
            "color": "white"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "76755624",
        "personal": [
          {
            "age": "26",
            "color": "green"
          }
        ]
      }
    ]
  },
  {
    "username": "raju",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "521001",
        "personal": [
          {
            "age": "26",
            "color": "red"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "600024",
        "personal": [
          {
            "age": "26",
            "color": "blue"
          }
        ]
      }
    ]
  }
]

Any body help me to check(address category city:mtm) and get particular user details only?


问:
use cx_Oracle to handle .sql script
```<code># -*-coding: UTF-8 -*-
import cx_Oracle
conn = cx_Oracle.connect('test/test01@10.10.2.3/test')
cursor =conn.cursor()
f = open('test001.txt','r',encoding='gbk')
full_sql = f.read()
sql_commands = full_sql.split(';')

for sql_command in sql_commands:
    cursor.execute(sql_command)}
</code>```

systems error:UnicodeEncodeError: 'ascii' codec can't encode characters in position 353-357: ordinal not in range(128)

答:
There was an issue with cx_Oracle 6.0rc1 where mixed text encodings on an Windows OS error caused the import of cx_Oracle to display various UnicodeEncodeError messages.  Posts like this have the issue.  The cx_Oracle bug has been fixed on GitHub but a release to PyPi has not yet been made (it'll come soon). If you can install cx_Oracle from GitHub you will see the actual OS error - which you then will have to fix.

The actual root of the problem causing the OS to generate an error may be that you don't have Oracle client libraries in your path, that the libraries are not the same architecture (32-bit or 64-bit) as Python, or that you don't have the correct VS Redistributable for your version of the Oracle client libraries.  The required VS Redistributables are listed on the Instant Client download pages (32-bit and 64-bit).

Title: use cx_Oracle to handle .sql script

Body:
# -*-coding: UTF-8 -*-
import cx_Oracle
conn = cx_Oracle.connect('test/test01@10.10.2.3/test')
cursor =conn.cursor()
f = open('test001.txt','r',encoding='gbk')
full_sql = f.read()
sql_commands = full_sql.split(';')

for sql_command in sql_commands:
    cursor.execute(sql_command)}

systems error:UnicodeEncodeError: 'ascii' codec can't encode characters in position 353-357: ordinal not in range(128)


问:
Qt Custom3DItem setMeshFile not working with Wavefront obj generated by Blender
I'm trying to use a different 3D object in Qt for this example:
https://doc.qt.io/qt-5/qtdatavisualization-rotations-example.html
I've tried to download obj files or to generate new ones using Blender.
The example works with any other object present in the other Qt example, but not with Wavefront objects generate by Blender.
I also tried a simple cube:

```<code># Blender v2.78 (sub 0) OBJ File: ''
# www.blender.org
mtllib untitled.mtl
o Cube
v 0.910983 -0.851291 -0.981756
v 0.910983 -0.851291 1.018244
v -1.089017 -0.851291 1.018244
v -1.089016 -0.851291 -0.981756
v 0.910984 1.148709 -0.981755
v 0.910983 1.148709 1.018245
v -1.089017 1.148709 1.018244
v -1.089017 1.148709 -0.981756
vn 0.0000 -1.0000 0.0000
vn 0.0000 1.0000 -0.0000
vn 1.0000 -0.0000 0.0000
vn 0.0000 -0.0000 1.0000
vn -1.0000 -0.0000 -0.0000
vn 0.0000 0.0000 -1.0000
usemtl Material
s off
f 2//1 4//1 1//1
f 8//2 6//2 5//2
f 5//3 2//3 1//3
f 6//4 3//4 2//4
f 7//5 4//5 3//5
f 1//6 8//6 5//6
f 2//1 3//1 4//1
f 8//2 7//2 6//2
f 5//3 6//3 2//3
f 6//4 7//4 3//4
f 7//5 8//5 4//5
f 1//6 4//6 8//6
</code>```

but even the cube  is not working.
I got the following error in the debug console:

```<code>> Debugging starts [07:22:56:07:900][ 1352] IGIESW
> c:\qt\examples\qt-5.9.1\datavisualization\build-rotations-desktop_qt_5_9_1_mingw_32bit-debug\debug\rotations.exe
> found in whitelist: NO [07:22:56:07:957][ 1352] IGIWHW Game
> c:\qt\examples\qt-5.9.1\datavisualization\build-rotations-desktop_qt_5_9_1_mingw_32bit-debug\debug\rotations.exe
> found in whitelist: NO OpenGL version: 4.5.0 NVIDIA 382.05 GLSL
> version: 4.50 NVIDIA ASSERT failure in QVector<T>::operator[]: "index
> out of range", file c:\Users\qt\work\install\include/QtCore/qvector.h,
> line 438 Debugging has finished
</code>```

anyone knows how to correctly generate obj for Qt?
Thanks

答:
The lines at the end of your sample, which start with f are listing the face data. I expect the missing number between the two slashes are the cause of the "index out of range error". As that is probably handled by Qt code you could suggest a bug fix to better handle that situation as it seems to be valid to have two out of three numbers there.

The second number in the face data is for uv coordinates. I expect unwrapping or at least creating a default uvmap will solve your issue.

Body:
I'm trying to use a different 3D object in Qt for this example:
https://doc.qt.io/qt-5/qtdatavisualization-rotations-example.html
I've tried to download obj files or to generate new ones using Blender.
The example works with any other object present in the other Qt example, but not with Wavefront objects generate by Blender.
I also tried a simple cube:

# Blender v2.78 (sub 0) OBJ File: ''
# www.blender.org
mtllib untitled.mtl
o Cube
v 0.910983 -0.851291 -0.981756
v 0.910983 -0.851291 1.018244
v -1.089017 -0.851291 1.018244
v -1.089016 -0.851291 -0.981756
v 0.910984 1.148709 -0.981755
v 0.910983 1.148709 1.018245
v -1.089017 1.148709 1.018244
v -1.089017 1.148709 -0.981756
vn 0.0000 -1.0000 0.0000
vn 0.0000 1.0000 -0.0000
vn 1.0000 -0.0000 0.0000
vn 0.0000 -0.0000 1.0000
vn -1.0000 -0.0000 -0.0000
vn 0.0000 0.0000 -1.0000
usemtl Material
s off
f 2//1 4//1 1//1
f 8//2 6//2 5//2
f 5//3 2//3 1//3
f 6//4 3//4 2//4
f 7//5 4//5 3//5
f 1//6 8//6 5//6
f 2//1 3//1 4//1
f 8//2 7//2 6//2
f 5//3 6//3 2//3
f 6//4 7//4 3//4
f 7//5 8//5 4//5
f 1//6 4//6 8//6

but even the cube  is not working.
I got the following error in the debug console:

> Debugging starts [07:22:56:07:900][ 1352] IGIESW
> c:\qt\examples\qt-5.9.1\datavisualization\build-rotations-desktop_qt_5_9_1_mingw_32bit-debug\debug\rotations.exe
> found in whitelist: NO [07:22:56:07:957][ 1352] IGIWHW Game
> c:\qt\examples\qt-5.9.1\datavisualization\build-rotations-desktop_qt_5_9_1_mingw_32bit-debug\debug\rotations.exe
> found in whitelist: NO OpenGL version: 4.5.0 NVIDIA 382.05 GLSL
> version: 4.50 NVIDIA ASSERT failure in QVector<T>::operator[]: "index
> out of range", file c:\Users\qt\work\install\include/QtCore/qvector.h,
> line 438 Debugging has finished

anyone knows how to correctly generate obj for Qt?
Thanks