问:
Updating imageview declared in parent class(which includes Navigation view) from derived class in android
Scenario:

Base class which includes Navigation drawer layout having header section as in usual apps. Header includes an imageview and textview. There's another activity lets say Profile which is extending from Base class in my case and I don't want to change this parent/child behaviour at this point.

Problem:

Profile activity has api call which updates the profile image on server. On getting success in response, I just want to update the navigation drawer ImageView regardless of user goes back to other activity or remains at Profile activity.

What I have tried so far are:

Declare ImageView in Base Activity as static and try to use Picasso to update image in Profile activity api response.

Declare ImageView in Base Activity as static and tried imageview.setBitmap() method.

Tried to use instance of Base class in Volley success method and use method of base class where I am trying to update ImageView.

Tried to use runOnUiThread() in api success response but of no success.
This doesn't make sense in my case as the user might not land on base activity while pressing back button. Below is the piece of code in Profile Activity where I am trying to update image in Base Activity

```<code>   private void uploadImage() {

    if (bm == null) {
        uploadProfile();
    }
    else {
        String REGISTER_URL = new SharedPreferenceManager(getApplicationContext()).getKeyFromSharedPrefFile("MySharedPrefs", "globalURL") + "users/mobileupload";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        navBarImage.setImageBitmap(bitmap); // where navBarImage is declared in BaseActivity Layout Navigation drawer in header layout
                     }
                },
                ....

        requestQueue.add(stringRequest);
    }
}
</code>```

Api call is working fine , image is uploading and updating smoothly if I logout and login again.

Now my question is whether there is a way to be able to update the view of parent class instantly ... and if yes, can you provide some example.

答:
As far as I understand the SecondActivity sets the information including adding an Image. So the goal of the task is to automatically update the FirstActivity's Drawer's ImageView. We cannot just call the view in the SecondActivity because the activity should work independently (which means -- they must not know each other).

I believe it is a great usecase for onActivityResult() since we want to pass back a result from the SecondActivity. The information we need to pass is a Uri-- the uri represents the Image location in the device.

SecondActivity

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
     if (requestCode == SELECT_FILE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            // We will pass the value at the previous activity using this code
            Intent responseValue = new Intent();
            responseValue.putExtra(PROFILE_URI_KEY, filePath);
            setResult(Activity.RESULT_OK, responseValue);
     }
}
</code>```

The SecondActivity recieves a Uri from the CameraActivity, that Uri must also be pass back to the prev. Activity so that it can perform the invalidation of Drawer'a Image.

MainActivity

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.e(TAG, "We receive someting " + requestCode + " " + (resultCode == Activity.RESULT_OK));
    if (requestCode == RESUL_KEY_FOR_EDIT && resultCode == Activity.RESULT_OK) {

        Uri uri = (Uri) data.getParcelableExtra(EditProfile.PROFILE_URI_KEY);
        Picasso.with(getApplicationContext())
                .load(uri)
                .fit().
                centerCrop()
                .noFade()
                .error(R.drawable.placeholder)
                .into(navBarImage);
    }
}
</code>```

In our MainActivity we are using Picasso for image loading due to improvements in performance.

Body:
Scenario:

Base class which includes Navigation drawer layout having header section as in usual apps. Header includes an imageview and textview. There's another activity lets say Profile which is extending from Base class in my case and I don't want to change this parent/child behaviour at this point.

Problem:

Profile activity has api call which updates the profile image on server. On getting success in response, I just want to update the navigation drawer ImageView regardless of user goes back to other activity or remains at Profile activity.

What I have tried so far are:

Declare ImageView in Base Activity as static and try to use Picasso to update image in Profile activity api response.

Declare ImageView in Base Activity as static and tried imageview.setBitmap() method.

Tried to use instance of Base class in Volley success method and use method of base class where I am trying to update ImageView.

Tried to use runOnUiThread() in api success response but of no success.
This doesn't make sense in my case as the user might not land on base activity while pressing back button. Below is the piece of code in Profile Activity where I am trying to update image in Base Activity

   private void uploadImage() {

    if (bm == null) {
        uploadProfile();
    }
    else {
        String REGISTER_URL = new SharedPreferenceManager(getApplicationContext()).getKeyFromSharedPrefFile("MySharedPrefs", "globalURL") + "users/mobileupload";

        StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        navBarImage.setImageBitmap(bitmap); // where navBarImage is declared in BaseActivity Layout Navigation drawer in header layout
                     }
                },
                ....

        requestQueue.add(stringRequest);
    }
}

Api call is working fine , image is uploading and updating smoothly if I logout and login again.

Now my question is whether there is a way to be able to update the view of parent class instantly ... and if yes, can you provide some example.

Body:
As far as I understand the SecondActivity sets the information including adding an Image. So the goal of the task is to automatically update the FirstActivity's Drawer's ImageView. We cannot just call the view in the SecondActivity because the activity should work independently (which means -- they must not know each other).

I believe it is a great usecase for onActivityResult() since we want to pass back a result from the SecondActivity. The information we need to pass is a Uri-- the uri represents the Image location in the device.

SecondActivity

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
     if (requestCode == SELECT_FILE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            // We will pass the value at the previous activity using this code
            Intent responseValue = new Intent();
            responseValue.putExtra(PROFILE_URI_KEY, filePath);
            setResult(Activity.RESULT_OK, responseValue);
     }
}

The SecondActivity recieves a Uri from the CameraActivity, that Uri must also be pass back to the prev. Activity so that it can perform the invalidation of Drawer'a Image.

MainActivity

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.e(TAG, "We receive someting " + requestCode + " " + (resultCode == Activity.RESULT_OK));
    if (requestCode == RESUL_KEY_FOR_EDIT && resultCode == Activity.RESULT_OK) {

        Uri uri = (Uri) data.getParcelableExtra(EditProfile.PROFILE_URI_KEY);
        Picasso.with(getApplicationContext())
                .load(uri)
                .fit().
                centerCrop()
                .noFade()
                .error(R.drawable.placeholder)
                .into(navBarImage);
    }
}

In our MainActivity we are using Picasso for image loading due to improvements in performance.


来源: stackexchange

问:
Codeigniter file upload code not working
Controller Code:

```<code>if(isset($_FILES['imageupload']) && $_FILES['imageupload']['size'] > 0){
    echo 'inside if';
    if ( ! $this->upload->do_upload('imageupload'))
    {
    echo 'inside if';
    $error = array('error' => $this->upload->display_errors());
    }
    else
    {
    echo 'inside else';
    $upload_data = $this->upload->data();
    $file_name[] = $upload_data['file_name'];
    }
}
</code>```

View Code:

```<code><input type="file" class="default" id="imageupload" name="imageupload">
</code>```

ERROR: Call to a member function do_upload() on a non-object

Hoow can I resolve this error please help me.

答: Did you load the library upload on your controller? I guess the problem of your code is lacking of this code $this->load->library('upload', $config); try to check this documentation hope it will help you. https://www.codeigniter.com/userguide3/libraries/file_uploading.html

ContentLicense: CC BY-SA 3.0

Body:
Controller Code:

if(isset($_FILES['imageupload']) && $_FILES['imageupload']['size'] > 0){
    echo 'inside if';
    if ( ! $this->upload->do_upload('imageupload'))
    {
    echo 'inside if';
    $error = array('error' => $this->upload->display_errors());
    }
    else
    {
    echo 'inside else';
    $upload_data = $this->upload->data();
    $file_name[] = $upload_data['file_name'];
    }
}

View Code:

<input type="file" class="default" id="imageupload" name="imageupload">

ERROR: Call to a member function do_upload() on a non-object

Hoow can I resolve this error please help me.


问:
What does the following form do in the code?
```<code><%= form_for [@blog,@blog.comments.build] do |f| %>
    <p><%= f.text_area :text, :size => '40x10' %> </p>
    <p><%= f.submit "Post Comment" %> </p>
<% end %>
</code>```

This is handler by comments_controller, but I would like to know the reason, especially for form_for

答:
The form_for creates a form for creation or update of passed object. If the object is not persisted, the associated url will target the creation action. Otherwise the targeted action will the update. form_for can receive many different kinds of parameter to generate the form.

If you check out the Rails url_helpers documentation, you will see that you can do something like:

```<code><%= link_to 'First comment', blog_comment_path([@blog, @blog.comments.first]) %>
</code>```

This will generate a link to the first comment of the blog with a path like /posts/@post.id/comments/@post.comments.first.id. This also assumes that you have the correct setup on your routes.rb:

```<code>resources :blogs do
    resources :comments
end
</code>```

With this, you generate a bunch of paths that you can use to build, for instance, links and forms. Thus, the form_for in your code works similarly. Think of it as a url_helper. You have a @blog and a comment associated to the post(@blog.comments.build). As the comment is not persisted yet, the will generate a form for the creation of comments targetting CommentsController#create. The associated path will be something like /blogs/@blog.id/comments and the HTTP method will be POST.

Also, check these links to get more info:

Rails Routing

Rails Form Helpers

Body:
<%= form_for [@blog,@blog.comments.build] do |f| %>

<%= f.text_area :text, :size => '40x10' %>

<%= f.submit "Post Comment" %>

<% end %>

This is handler by comments_controller, but I would like to know the reason, especially for form_for

Body:
The form_for creates a form for creation or update of passed object. If the object is not persisted, the associated url will target the creation action. Otherwise the targeted action will the update. form_for can receive many different kinds of parameter to generate the form.

If you check out the Rails url_helpers documentation, you will see that you can do something like:

<%= link_to 'First comment', blog_comment_path([@blog, @blog.comments.first]) %>

This will generate a link to the first comment of the blog with a path like /posts/@post.id/comments/@post.comments.first.id. This also assumes that you have the correct setup on your routes.rb:

resources :blogs do
    resources :comments
end

With this, you generate a bunch of paths that you can use to build, for instance, links and forms. Thus, the form_for in your code works similarly. Think of it as a url_helper. You have a @blog and a comment associated to the post(@blog.comments.build). As the comment is not persisted yet, the will generate a form for the creation of comments targetting CommentsController#create. The associated path will be something like /blogs/@blog.id/comments and the HTTP method will be POST.

Also, check these links to get more info:

Rails Routing

Rails Form Helpers


问:
Incompatible types: Mainactivity cannot be converted to OnClickListener
Click here. This is link to image error I'm getting

I have started with most basic calculator app that adds and subtracts two numbers.

I'm getting this incompatible error for SetOnClickListener().
Before this I got an error saying "ActivityBar is deprecated", later I changed it to
AppCompactActivity and the error cleared.

I'm really new to this and have almost no clue to what the code means I just got it online.

答:
try to make your activity implement the "View.OnClickListener".<br>
thats will help </p>

Body:
try to make your activity implement the "View.OnClickListener".

thats will help


问:
sqlite select minimum function value of grouped result
I have a table with gps locations of restaurants chains and would like to return the addresses of the restaurants closest to point (A) within a certain radius

```<code>SELECT *
    , MIN(distance($lat, $lon, lat, lon)) as miles
FROM all_restaurants
WHERE lat between $lat1 and $lat2
    AND lon between $lon1 and $lon2
    AND miles < $miles
GROUP BY restaurant_id
ORDER BY miles ASC
    , company_name ASC
LIMIT 500
</code>```

returns error

misuse of aggregate: MIN()

答:
I think that your problem is that you only are grouping by restaurant_id. When you use an aggregation function as MIN, MAX, SUM, AVG, etc, you need to include every column in the SELECT statement that are not in any aggregation function. In this case you have two options, either in the SELECT you only put restaurant_id as the following:

```<code>SELECT restaurant_id
        , MIN(distance($lat, $lon, lat, lon)) as miles
    FROM all_restaurants
    WHERE lat between $lat1 and $lat2
        AND lon between $lon1 and $lon2
        AND miles < $miles
    GROUP BY restaurant_id
    ORDER BY miles ASC
        , company_name ASC
    LIMIT 500
</code>```

Or you put every other column included in the '*' on the grouping (because you can't use GROUP BY *).

Body:
I have a table with gps locations of restaurants chains and would like to return the addresses of the restaurants closest to point (A) within a certain radius

SELECT *
    , MIN(distance($lat, $lon, lat, lon)) as miles
FROM all_restaurants
WHERE lat between $lat1 and $lat2
    AND lon between $lon1 and $lon2
    AND miles < $miles
GROUP BY restaurant_id
ORDER BY miles ASC
    , company_name ASC
LIMIT 500

returns error

misuse of aggregate: MIN()

Body:
I think that your problem is that you only are grouping by restaurant_id. When you use an aggregation function as MIN, MAX, SUM, AVG, etc, you need to include every column in the SELECT statement that are not in any aggregation function. In this case you have two options, either in the SELECT you only put restaurant_id as the following:

SELECT restaurant_id
        , MIN(distance($lat, $lon, lat, lon)) as miles
    FROM all_restaurants
    WHERE lat between $lat1 and $lat2
        AND lon between $lon1 and $lon2
        AND miles < $miles
    GROUP BY restaurant_id
    ORDER BY miles ASC
        , company_name ASC
    LIMIT 500

Or you put every other column included in the '*' on the grouping (because you can't use GROUP BY *).


问:
given a range X, N intervals and an overlap O, calculate interval size
I have a range X.
I want to divide this range in N intervals.
I also want the intervals to overlap.
Which algorithm allows me to find the size of my intervals?

Example:

```<code>Range   = 1;  % the data ranges between 0 and 1
N       = 5;  % the range is divided in 5 intervals.
Overlap = .5; % Two neighbouring intervals overlap by 50%

StepSize = ?;
</code>```

Thank you very much

答:
The formula is</p>

```<code>s = x / (n + o - n * o)
</code>```

Body:
I have a range X.
I want to divide this range in N intervals.
I also want the intervals to overlap.
Which algorithm allows me to find the size of my intervals?

Example:

Range   = 1;  % the data ranges between 0 and 1
N       = 5;  % the range is divided in 5 intervals.
Overlap = .5; % Two neighbouring intervals overlap by 50%

StepSize = ?;

Thank you very much

Body:
The formula is

s = x / (n + o - n * o)


问:
SAS - Find and print first non-zero value from a dataset in columns
I have a data set with ID in rows and months in columns, as the one shown below.

I want to create an auxiliary column that records the first value that is not zero of each line.

```<code>ID  M1  M2  M3  M4  M5      Auxiliary column
1   0   0   8   8   7       8
2   7   7   7   .   .       7
3   0   0   0   0   9       9
4   0   9   9   9   8       9
5   1   1   1   1   1       1
6   0   2   2   1   1       2
</code>```

Currently l am using this code, but I haven't been able to get the results I am looking for. Any ideas?

```<code>data new_ops04;
set new_ops03;

array MONTHS (24) M1-M24;

RETAIN AUXILIARY_COLUMN 0;
    do i=1 to 24;
    IF MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
               AUXILIARY_COLUMN = MONTHS(i);
    end;
        drop i;
run;
</code>```

Thanks a lot!

答:
I would do this use case in proc sql.  But your problem is that you are not stopping when you reach the first value.  So:

```<code>flag = 0;
do i=1 to 24 until (flag)
    if MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
            AUXILIARY_COLUMN = MONTHS(i);
            flag = 1;
     end;
drop i, flag;
</code>```

Body:
I have a data set with ID in rows and months in columns, as the one shown below.

I want to create an auxiliary column that records the first value that is not zero of each line.

ID  M1  M2  M3  M4  M5      Auxiliary column
1   0   0   8   8   7       8
2   7   7   7   .   .       7
3   0   0   0   0   9       9
4   0   9   9   9   8       9
5   1   1   1   1   1       1
6   0   2   2   1   1       2

Currently l am using this code, but I haven't been able to get the results I am looking for. Any ideas?

data new_ops04;
set new_ops03;

array MONTHS (24) M1-M24;

RETAIN AUXILIARY_COLUMN 0;
    do i=1 to 24;
    IF MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
               AUXILIARY_COLUMN = MONTHS(i);
    end;
        drop i;
run;

Thanks a lot!

Body:
I would do this use case in proc sql.  But your problem is that you are not stopping when you reach the first value.  So:

flag = 0;
do i=1 to 24 until (flag)
    if MONTHS(i) ne 0 and AUXILIARY_COLUMN = 0 THEN
            AUXILIARY_COLUMN = MONTHS(i);
            flag = 1;
     end;
drop i, flag;


问:
32-bit registers in real mode and dereferencing
I'm writing some assembly for MBR (real mode). I know that in real mode you can't use the 32-bit registers, only the 16-bit ones.

I wrote this code which relies on a print_char function.

```<code>    mov ecx, MSG
write:
    mov al, [ecx]
    cmp al, 0x0
    je end_print
    call print_char
    inc cx
    jmp write
end_print:
    ret
MSG: db 'Hi!', 0xd, 0xa, 0x0
</code>```

This code doesn't compile due to the reason:

```<code>error: invalid effective address
</code>```

I use

```<code>nasm -f bin -o out src.s
</code>```

When I change the register name to ecx, the code starts to compile, and surprisingly, works.

Why does my code using 32-bit registers work in real mode and why does using 16-bit registers not?

答:
The x86 ISA supports a number of addressing modes. There are two sets of addressing modes, one for 16 bit mode and one for 32 bit mode.

In 32 bit mode, you can use indexed addressing with any register and the three-part SIB addressing.

In 16 bit mode, only the following addressing modes exist (each with optional displacement):

```<code>BX + disp
BX + SI + disp
BX + DI + disp
BP + disp
BP + SI + disp
BP + DI + disp
SI + disp
DI + disp
disp
</code>```

Note how cx isn't available as an index register.

What you can do to get around this problem is to use a 32 bit addressing mode in 16 bit mode. This is done by specifying ecx as an index register as you did.

Body:
I'm writing some assembly for MBR (real mode). I know that in real mode you can't use the 32-bit registers, only the 16-bit ones.

I wrote this code which relies on a print_char function.

    mov ecx, MSG
write:
    mov al, [ecx]
    cmp al, 0x0
    je end_print
    call print_char
    inc cx
    jmp write
end_print:
    ret
MSG: db 'Hi!', 0xd, 0xa, 0x0

This code doesn't compile due to the reason:

error: invalid effective address

I use

nasm -f bin -o out src.s

When I change the register name to ecx, the code starts to compile, and surprisingly, works.

Why does my code using 32-bit registers work in real mode and why does using 16-bit registers not?

Body:
The x86 ISA supports a number of addressing modes. There are two sets of addressing modes, one for 16 bit mode and one for 32 bit mode.

In 32 bit mode, you can use indexed addressing with any register and the three-part SIB addressing.

In 16 bit mode, only the following addressing modes exist (each with optional displacement):

BX + disp
BX + SI + disp
BX + DI + disp
BP + disp
BP + SI + disp
BP + DI + disp
SI + disp
DI + disp
disp

Note how cx isn't available as an index register.

What you can do to get around this problem is to use a 32 bit addressing mode in 16 bit mode. This is done by specifying ecx as an index register as you did.


问:
CollapsingToolbarLayout - Dim/Blur the background image
I've got a collapsing toolbar with an imageview. When extended, it looks like this:

When collapsed, it looks like this:

I know that according to the guidelines, the toolbar should be of the primary color while collapsed, but i like the way i've set it up, and would like to keep it like that.

However, obviously, the toolbar title won't be visible if the image has a lot of white in it. So, is there a way i can blur/dim the background so that the toolbar title is visible at all times?

Edit: The image in question, is loaded from the internet using Picasso.

答:
You could use Blurry library

Blurry is an easy blur library for Android

```<code>// from Bitmap
Blurry.with(context).from(bitmap).into(imageView);
</code>```

//use with Picasso

```<code> Blurry.with(MainActivity.this)
                .radius(10)
                .sampling(8)
                .async()
                .capture(findViewById(R.id.image_veiw))
                .into((ImageView) findViewById(R.id.image_veiw));
</code>```

Body:
You could use Blurry library

Blurry is an easy blur library for Android

// from Bitmap
Blurry.with(context).from(bitmap).into(imageView);

//use with Picasso

 Blurry.with(MainActivity.this)
                .radius(10)
                .sampling(8)
                .async()
                .capture(findViewById(R.id.image_veiw))
                .into((ImageView) findViewById(R.id.image_veiw));


问:
Reading files with nested while loops
This function is part of a larger class, this functions purpose is to make a dictionary using the first lines last element as key and s_d as value. The c is supposed to be used for something else. When i print new_dict i get the desired result but the loop keeps running

```<code>def extract(filename):
f = open(filename)
new_dict={}
c = ''
l = f.readline().strip()
while l :
    first = f.readline().strip()[-1]
    s_d = f.readline().strip()
    l = f.readline().strip()
    new_line= f.readline().strip()
    while new_line != 'FIN' :
        c = c + new_line
        new_line = f.readline().strip()
    new_dict[first]= s_d
    print(new_dict)
</code>```

This function has to be done this way, with two while loops.How can i make the function stop running after it runs out of lines

BTW
the text file looks like:

```<code>IDS
ID 0
text(small description of item)
text(long description)
text(long desc second line)
FIN
ID 1
same as before
</code>```

答: After adding s_d to dict update l as l = new_line . This will make sure that while l: always checks with the last line read from the file.

Title: Reading files with nested while loops

Body:
This function is part of a larger class, this functions purpose is to make a dictionary using the first lines last element as key and s_d as value. The c is supposed to be used for something else. When i print new_dict i get the desired result but the loop keeps running

def extract(filename):
f = open(filename)
new_dict={}
c = ''
l = f.readline().strip()
while l :
    first = f.readline().strip()[-1]
    s_d = f.readline().strip()
    l = f.readline().strip()
    new_line= f.readline().strip()
    while new_line != 'FIN' :
        c = c + new_line
        new_line = f.readline().strip()
    new_dict[first]= s_d
    print(new_dict)

This function has to be done this way, with two while loops.How can i make the function stop running after it runs out of lines

BTW
the text file looks like:

IDS
ID 0
text(small description of item)
text(long description)
text(long desc second line)
FIN
ID 1
same as before


问:
Count IF with Date and Time in single Cell (EXCEL)
I have a spreadsheet that lists the date and time of an event in the same cell (mm/dd/yy h:mm). I need to find a way to count how many events took place between a certain time range in a Hourly Basis.

I could sum if the cell contains dates only however the cell contains with date which i am unable to get the values.

Basically, all datas are in cell A, so i need to count how many events happened at 6am, 7am , and so on... as on hourly basis.

答:
If the times spanned different dates and you still wanted to see how many events happened in a particular hour of the day, you would need an array-type formula, e.g. if the start time in hours (entered as a normal number) is in C2

```<code>=SUMPRODUCT(--(HOUR($A$2:$A$10)=C2))
</code>```

or if the start hour is entered as a time

```<code>=SUMPRODUCT(--(HOUR($A$2:$A$10)=HOUR(C2)))
</code>```

Body:
If the times spanned different dates and you still wanted to see how many events happened in a particular hour of the day, you would need an array-type formula, e.g. if the start time in hours (entered as a normal number) is in C2

=SUMPRODUCT(--(HOUR($A$2:$A$10)=C2))

or if the start hour is entered as a time

=SUMPRODUCT(--(HOUR($A$2:$A$10)=HOUR(C2)))


问:
Android MainActivity to pass intent to another activity
I am having problem in trying to call another class called FetchData which in turn contains the AsyncTask Method .

My Main Activity code is:

```<code>public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

    private Button btn;
    private EditText edit;
    private Spinner spinner;
    //private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button);
        edit = (EditText) findViewById(R.id.edit_message);
        spinner = (Spinner) findViewById(R.id.spinner);
        //textView = (TextView) findViewById(R.id.textView1);

        btn.setOnClickListener(
                new View.OnClickListener()
                {
                    public void onClick(View view)
                    {
                        //Log.v("EditText", edit.getText().toString());
                       // Log.v("Spinner", spinner.getSelectedItem().toString());
                        //if(spinner.getSelectedItem().toString()=="All Types")
                         String[] customarr = {"feature,tv_series,game","feature","tv_series","game"};
                         String selecteditem = customarr[spinner.getSelectedItemPosition()];

                        String url="http://cs-server.usc.edu:23405/examples/servlet/HelloWorldExample?title="+edit.getText().toString()+"&type="+selecteditem;
                        Log.v("url",url);

                        Intent intent=new Intent(this,FetchData.class);
                        String message=url;
                        intent.putExtra(EXTRA_MESSAGE, message);
                        startActivity(intent);
                    }
                });

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.title_type,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    //String url="http://cs-server.usc.edu:23405/examples/servlet/HelloWorldExample?title="+edit.getText().toString()+"&type="+spinner.getSelectedItem().toString();
     // Log.v("url",url);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            //Object item = parent.getItemAtPosition(pos);

        }
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    }
}
</code>```

I am having the error

```<code>The constructor Intent(new View.OnClickListener(){}, Class<FetchData>) is undefined
</code>```

Any ideas.? I think i am doing a silly mistake somewhere.

答:
```<code>Intent intent=new Intent(MainActivity.this,FetchData.class);
</code>```

You forgot to mention the MainActivity

Body:
I am having problem in trying to call another class called FetchData which in turn contains the AsyncTask Method .

My Main Activity code is:

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

    private Button btn;
    private EditText edit;
    private Spinner spinner;
    //private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button);
        edit = (EditText) findViewById(R.id.edit_message);
        spinner = (Spinner) findViewById(R.id.spinner);
        //textView = (TextView) findViewById(R.id.textView1);

        btn.setOnClickListener(
                new View.OnClickListener()
                {
                    public void onClick(View view)
                    {
                        //Log.v("EditText", edit.getText().toString());
                       // Log.v("Spinner", spinner.getSelectedItem().toString());
                        //if(spinner.getSelectedItem().toString()=="All Types")
                         String[] customarr = {"feature,tv_series,game","feature","tv_series","game"};
                         String selecteditem = customarr[spinner.getSelectedItemPosition()];

                        String url="http://cs-server.usc.edu:23405/examples/servlet/HelloWorldExample?title="+edit.getText().toString()+"&type="+selecteditem;
                        Log.v("url",url);

                        Intent intent=new Intent(this,FetchData.class);
                        String message=url;
                        intent.putExtra(EXTRA_MESSAGE, message);
                        startActivity(intent);
                    }
                });

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.title_type,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    //String url="http://cs-server.usc.edu:23405/examples/servlet/HelloWorldExample?title="+edit.getText().toString()+"&type="+spinner.getSelectedItem().toString();
     // Log.v("url",url);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            //Object item = parent.getItemAtPosition(pos);

        }
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    }
}

I am having the error

The constructor Intent(new View.OnClickListener(){}, Class<FetchData>) is undefined

Any ideas.? I think i am doing a silly mistake somewhere.

Body:
Intent intent=new Intent(MainActivity.this,FetchData.class);

You forgot to mention the MainActivity


问:
custom tableviewcell button event firing multiple times
I have a tableview which makes use of custom tableview cell.

When we click the button the event gets fired up multiple times but not all the times.

I have observed that cell is never null in below code in my tableview

```<code>var cell = (MyCustomCell)tableView.DequeueReusableCell (MyCustomCell.Key);
</code>```

I am using dynamic prototypes for my tableview

I think there is a problem with cell reusability and button even binding but I am not able to figure out why it happens and how to fix it ?

Update

```<code> public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
 {
//Getting the value from arrary as data source here
var cell = (MyCustomCell)tableView.DequeueReusableCell (MyCustomCell.Key);

if (cell == null) {
    cell = MyCustomCell.Create ();
}
button.TouchUpInside -= yourHandler;
button.TouchUpInside += yourHandler;

//assigning the values to labels
return cell;
 }
</code>```

Whatsoever it is I am removing the button event and adding it then it shouldn't fire the event multiple times

答:
As cells are reused, your button event handler may be subscribed more than once for the same cell. An easy workaround is to unsubscribe before you subscribe:

```<code>button.TouchUpInside -= yourHandler;
button.TouchUpInside += yourHandler;
</code>```

If you are using a lambda as a delegate, change it to a method delegate

Body:
I have a tableview which makes use of custom tableview cell.

When we click the button the event gets fired up multiple times but not all the times.

I have observed that cell is never null in below code in my tableview

var cell = (MyCustomCell)tableView.DequeueReusableCell (MyCustomCell.Key);

I am using dynamic prototypes for my tableview

I think there is a problem with cell reusability and button even binding but I am not able to figure out why it happens and how to fix it ?

Update

 public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
 {
//Getting the value from arrary as data source here
var cell = (MyCustomCell)tableView.DequeueReusableCell (MyCustomCell.Key);

if (cell == null) {
    cell = MyCustomCell.Create ();
}
button.TouchUpInside -= yourHandler;
button.TouchUpInside += yourHandler;

//assigning the values to labels
return cell;
 }

Whatsoever it is I am removing the button event and adding it then it shouldn't fire the event multiple times

Body:
As cells are reused, your button event handler may be subscribed more than once for the same cell. An easy workaround is to unsubscribe before you subscribe:

button.TouchUpInside -= yourHandler;
button.TouchUpInside += yourHandler;

If you are using a lambda as a delegate, change it to a method delegate


问:
Listen all IP packets including ICMP, TCP and UDP?
Specially in golang, there are interfaces like net.ListenIP and net.ListenTCP.

I'm wondering that, if process p1 ListenIP(192.168.1.1) and process p2 ListenTCP(192.168.1.1:80), will all packets dest to 192.168.1.1 (no matter TCP or UDP) are intercepted by p1, and p2 will never accept a TCP connection?

答:
Here is the source code of net.ListenIP():

```<code>// ListenIP listens for incoming IP packets addressed to the local
// address laddr.  The returned connection's ReadFrom and WriteTo
// methods can be used to receive and send IP packets with per-packet
// addressing.
func ListenIP(netProto string, laddr *IPAddr) (*IPConn, error) {
    net, proto, err := parseNetwork(netProto)
    if err != nil {
        return nil, &OpError{Op: "listen", Net: netProto, Source: nil, Addr: laddr.opAddr(), Err: err}
    }
    switch net {
    case "ip", "ip4", "ip6":
    default:
        return nil, &OpError{Op: "listen", Net: netProto, Source: nil, Addr: laddr.opAddr(), Err: UnknownNetworkError(netProto)}
    }
    fd, err := internetSocket(net, laddr, nil, noDeadline, syscall.SOCK_RAW, proto, "listen", noCancel)
    if err != nil {
        return nil, &OpError{Op: "listen", Net: netProto, Source: nil, Addr: laddr.opAddr(), Err: err}
    }
    return newIPConn(fd), nil
}
</code>```

it creates a raw socket, on linux, an IPPROTO_RAW socket is send only. TCP and UDP packets are never delivered to raw sockets, they are always handled by the kernel protocol stack. Copies of ICMP packets are delivered to a matching raw socket. All other packets destined for protocols that are not processed by a kernel subsystem are delivered to raw sockets.

Body:
Here is the source code of net.ListenIP():

// ListenIP listens for incoming IP packets addressed to the local
// address laddr.  The returned connection's ReadFrom and WriteTo
// methods can be used to receive and send IP packets with per-packet
// addressing.
func ListenIP(netProto string, laddr *IPAddr) (*IPConn, error) {
    net, proto, err := parseNetwork(netProto)
    if err != nil {
        return nil, &OpError{Op: "listen", Net: netProto, Source: nil, Addr: laddr.opAddr(), Err: err}
    }
    switch net {
    case "ip", "ip4", "ip6":
    default:
        return nil, &OpError{Op: "listen", Net: netProto, Source: nil, Addr: laddr.opAddr(), Err: UnknownNetworkError(netProto)}
    }
    fd, err := internetSocket(net, laddr, nil, noDeadline, syscall.SOCK_RAW, proto, "listen", noCancel)
    if err != nil {
        return nil, &OpError{Op: "listen", Net: netProto, Source: nil, Addr: laddr.opAddr(), Err: err}
    }
    return newIPConn(fd), nil
}

it creates a raw socket, on linux, an IPPROTO_RAW socket is send only. TCP and UDP packets are never delivered to raw sockets, they are always handled by the kernel protocol stack. Copies of ICMP packets are delivered to a matching raw socket. All other packets destined for protocols that are not processed by a kernel subsystem are delivered to raw sockets.


问:
Three.js - Apply anisotropy to a texture in a loaded js model
I'm loading a *.js model which has a texture. The texture itself is a separate file located in the same directory as the model, so the loader adds this texture to the *.js model.

```<code>var loader = new THREE.JSONLoader();
        var aMesh;
        loader.load("models/mesh.js", function (geometry, materials) {
            aMesh = new THREE.Mesh(geometry, materials[0]);
            scene.add(aMesh);
        });
</code>```

The texture gets blurred when viewed at some angle so I need to apply anisotropy filtering to it.

I can only guess that I need to create a var Texture, load the texture into it, apply anisotropy and then add this texture variable to the mesh or to its material[0].

Or can I access the texture in the aMesh material directly somehow?

答:
This may work, untested.

```<code>var loader = new THREE.JSONLoader();
var aMesh;
loader.load("models/mesh.js", function (geometry, materials) {
  var maxAnisotropy = renderer.getMaxAnisotropy();
  materials[0].map.anisotropy = maxAnisotropy;
  aMesh = new THREE.Mesh(geometry, materials[0]);
  scene.add(aMesh);
});
</code>```

If not, you could always override the load function of the JSONLoader class.

Or load the model and texture separately.

ContentLicense: CC BY-SA 4.0

Body:
I'm loading a *.js model which has a texture. The texture itself is a separate file located in the same directory as the model, so the loader adds this texture to the *.js model.

var loader = new THREE.JSONLoader();
        var aMesh;
        loader.load("models/mesh.js", function (geometry, materials) {
            aMesh = new THREE.Mesh(geometry, materials[0]);
            scene.add(aMesh);
        });

The texture gets blurred when viewed at some angle so I need to apply anisotropy filtering to it.

I can only guess that I need to create a var Texture, load the texture into it, apply anisotropy and then add this texture variable to the mesh or to its material[0].

Or can I access the texture in the aMesh material directly somehow?

Body:
This may work, untested.

var loader = new THREE.JSONLoader();
var aMesh;
loader.load("models/mesh.js", function (geometry, materials) {
  var maxAnisotropy = renderer.getMaxAnisotropy();
  materials[0].map.anisotropy = maxAnisotropy;
  aMesh = new THREE.Mesh(geometry, materials[0]);
  scene.add(aMesh);
});

If not, you could always override the load function of the JSONLoader class.

Or load the model and texture separately.


问:
How to make my spider's leg move in XNA
I've done a 3D spider model in Blender, and currently I can export it as a .x(direct X) file and import this .x file into XNA gamestudio and make it shown there as a static model.

Now this project is coming to the final stage, that is, we need to make one of its legs move back and forth in the XNA, however,it only needs to move back and forth, so no keyboard response is required.

We already successfully made one leg of the spider in the Blender has bones and armature and ik constraint, so in Blender, I can drag the leg to move. But now we are really stuck on how to get this move automatically in XNA, we tried exporting it as .x file the same way as before, but this time it won't even show in XNA.

It would be really great if you could give us a little help here, or maybe refer us to some tutorials on how to animate Blender model in XNA, thanks in advance!

答:
here is a pretty good thread in the XNA forums that talks about animating models
http://forums.create.msdn.com/forums/p/53155/322140.aspx</p>

ContentLicense: CC BY-SA 2.5

Title: How to make my spider's leg move in XNA


问:
Python Matplotlib Basemap - how to set zoom level
I have a dataframe with locations given as longitude and latitude coordinates (in degrees). Those locations are around New York. Therefore I setup a Basemap in Python that nicely shows all those locations. Works fine!

But: the map is drawn inline and it's very tiny. How can I force that figure to be let's say 3 times larger (zoom=3).

Here's the code. The data is from the Kaggle Two Sigma Rental Listing challenge.

```<code>%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# New York Central Park
# Longitude: -73.968285
# Latitude: 40.785091

m = Basemap(projection='merc',llcrnrlat=40,urcrnrlat=42,\
            llcrnrlon=-75, urcrnrlon=-72, resolution='i', area_thresh=50, lat_0=40.78, lon_0=-73.96)

m.drawmapboundary()
m.drawcoastlines(color='black', linewidth=0.4)
m.drawrivers(color='blue')
m.fillcontinents(color='lightgray')

lons = df['longitude'].values
lats = df['latitude'].values
x,y = m(lons, lats)

# r = red; o = circle marker (see: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot)
m.plot(x, y, 'ro', markersize=4)

plt.show()
</code>```

答:
normally it would be as simple as:

```<code>plt.figure(figsize=(20,10))
</code>```

How do you change the size of figures drawn with matplotlib?

but there are some other options too, see:

How to maximize a plt.show() window using Python

also to get the current size (for the purpose of "zoom")

How to get matplotlib figure size

regarding the specific issue:

the figure is inline inside a Jupyter notebook

before creating or plotting the map/figure:

```<code>import matplotlib
matplotlib.rcParams['figure.figsize'] = (30,30)
</code>```

Body:
I have a dataframe with locations given as longitude and latitude coordinates (in degrees). Those locations are around New York. Therefore I setup a Basemap in Python that nicely shows all those locations. Works fine!

But: the map is drawn inline and it's very tiny. How can I force that figure to be let's say 3 times larger (zoom=3).

Here's the code. The data is from the Kaggle Two Sigma Rental Listing challenge.

%matplotlib inline
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# New York Central Park
# Longitude: -73.968285
# Latitude: 40.785091

m = Basemap(projection='merc',llcrnrlat=40,urcrnrlat=42,\
            llcrnrlon=-75, urcrnrlon=-72, resolution='i', area_thresh=50, lat_0=40.78, lon_0=-73.96)

m.drawmapboundary()
m.drawcoastlines(color='black', linewidth=0.4)
m.drawrivers(color='blue')
m.fillcontinents(color='lightgray')

lons = df['longitude'].values
lats = df['latitude'].values
x,y = m(lons, lats)

# r = red; o = circle marker (see: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot)
m.plot(x, y, 'ro', markersize=4)

plt.show()

Body:
normally it would be as simple as:

plt.figure(figsize=(20,10))

How do you change the size of figures drawn with matplotlib?

but there are some other options too, see:

How to maximize a plt.show() window using Python

also to get the current size (for the purpose of "zoom")

How to get matplotlib figure size

regarding the specific issue:

the figure is inline inside a Jupyter notebook

before creating or plotting the map/figure:

import matplotlib
matplotlib.rcParams['figure.figsize'] = (30,30)


问:
Echo current Timestamp from mySQL Server
I try to get the current timestamp from my mysql Server. I know the Command SELECT CURRENT_TIMESTAMP. But i need to echo it as a String. Does someone know how I can do this?</p>

```<code><?php

include_once("../DatenbankVerbindungen/dbconnect.php");

$query = mysqli_query($connection, "SELECT CURRENT_TIMESTAMP;");

echo gmdate("Y-m-d\TH:i:s\Z", $query);

mysqli_close($connection);

?>
</code>```

答:
Alias the current timestamp and then access it in your PHP code:

```<code>$query = "SELECT CURRENT_TIMESTAMP AS ct;";
$rlt = mysqli_query($connection, $query);
$r = mysqli_fetch_assoc($rlt);
echo gmdate("Y-m-d\TH:i:s\Z", $r['ct']);
</code>```

Or, as @Gordon suggested, you do the formatting in MySQL directly and just return a formatted timestamp string:

```<code>$query = "SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') AS ct;";
$rlt = mysqli_query($connection, $query);
$r = mysqli_fetch_assoc($rlt);
echo $r['ct'];
</code>```

Body:
I try to get the current timestamp from my mysql Server. I know the Command SELECT CURRENT_TIMESTAMP. But i need to echo it as a String. Does someone know how I can do this?

<?php

include_once("../DatenbankVerbindungen/dbconnect.php");

$query = mysqli_query($connection, "SELECT CURRENT_TIMESTAMP;");

echo gmdate("Y-m-d\TH:i:s\Z", $query);

mysqli_close($connection);

?>

Body:
Alias the current timestamp and then access it in your PHP code:

$query = "SELECT CURRENT_TIMESTAMP AS ct;";
$rlt = mysqli_query($connection, $query);
$r = mysqli_fetch_assoc($rlt);
echo gmdate("Y-m-d\TH:i:s\Z", $r['ct']);

Or, as @Gordon suggested, you do the formatting in MySQL directly and just return a formatted timestamp string:

$query = "SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s') AS ct;";
$rlt = mysqli_query($connection, $query);
$r = mysqli_fetch_assoc($rlt);
echo $r['ct'];


问:
Picking a number from a contact but removing the country code
I am able to get the contact phone number on button click then transfer it to an EditText, but I want only to get the result without the country code. Exemple : +33 xx xx xx xxx becomes xx xx xx xxx

Is there  a way I can achieve this?
The following code I use to get the number and put it in an EditText:

Button click:

```<code>Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                editText.setText(phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

答: Use the libphonenumber library from Google. Don't try to create your own logic, as format varies from location to location.</p>

Body:
I am able to get the contact phone number on button click then transfer it to an EditText, but I want only to get the result without the country code. Exemple : +33 xx xx xx xxx becomes xx xx xx xxx

Is there  a way I can achieve this?
The following code I use to get the number and put it in an EditText:

Button click:

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                editText.setText(phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
Rails 5 Simpleform not updating nested attributes
Sorry I've looked at similar questions to this but still can't figure it out for some reason...

I'm using Devise and I'm trying to update my User model and a City model at the same time (through the edit registrations page) using a nested form.

I'm updating the users city based on a set of predefined values that are in the database. So all the user has to do is select a city they are living in from a list and then it save.

All that happens at the moment is the form submits but the city isn't changed.

Thanks in advance!

```<code>#user.rb
class User < ApplicationRecord
  belongs_to :city
end

#city.rb
class City < ApplicationRecord
  has_many :users
end
</code>```

My Controller:

```<code>class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

    if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(city_attributes: [:id, :name, :user_id])
  end
end
</code>```

And my form:

```<code><%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

      <%= f.simple_fields_for :city do |c| %>

      <%= c.input :city_id, collection: City.all.order(name: :asc), label_method: :name, value_method: :id, label: "City", include_blank: false, selected: @user.city_id %>

      <% end %>
<% end %>
</code>```

答:
Try this out:</p>

```<code>def user_params
    params.require(:user).permit(:city_id)
end
</code>```

Body:
Sorry I've looked at similar questions to this but still can't figure it out for some reason...

I'm using Devise and I'm trying to update my User model and a City model at the same time (through the edit registrations page) using a nested form.

I'm updating the users city based on a set of predefined values that are in the database. So all the user has to do is select a city they are living in from a list and then it save.

All that happens at the moment is the form submits but the city isn't changed.

Thanks in advance!

#user.rb
class User < ApplicationRecord
  belongs_to :city
end

#city.rb
class City < ApplicationRecord
  has_many :users
end

My Controller:

class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])

    if @user.update(user_params)
      redirect_to @user
    else
      render 'edit'
    end
  end

  def show
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(city_attributes: [:id, :name, :user_id])
  end
end

And my form:

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

      <%= f.simple_fields_for :city do |c| %>

      <%= c.input :city_id, collection: City.all.order(name: :asc), label_method: :name, value_method: :id, label: "City", include_blank: false, selected: @user.city_id %>

      <% end %>
<% end %>

Body:
Try this out:

def user_params
    params.require(:user).permit(:city_id)
end


问:
How do I access individual words after splitting a string?
```<code>std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";
</code>```

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

```<code>if (word[0] == "something")
   do_this();
else
   do_that();
</code>```

答: Just print token, and do the getline again.</p>

Body:
std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

if (word[0] == "something")
   do_this();
else
   do_that();


问:
How to get the next row value in another column
I have Table called Opp Table

```<code>   OppID         actualclosedate
--------------------------------------
    1            10-March
</code>```

I have a Table called stagechange

```<code>--------------------------------------
   OppID      Stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    1         Qualify     9-Feb
    1         Develop     7-March
    1         Prospect    9-April
</code>```

How Can I create a new column and get the next row value that is in createdon column; to have something like this. If there is no more next values, we get the date from other table like actual close date in Opp Table

```<code>--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       9-Feb
    1         Qualify     9-Feb        7-March
    1         Develop     7-March      9-April
    1         Prospect    9-April     10-March ----(actualclosedate)
</code>```

答:
This will replace the final/missing date with actualclosedate

```<code>Select A.*
      ,NewColumn = IsNull(Lead(creaton) over (Partition By A.OppID Order By A.CreateOn),B.actualclosedate)
 From  stagechange A
 Join  Opp         B on A.OppID=B.OppID
</code>```

Body:
I have Table called Opp Table

   OppID         actualclosedate
--------------------------------------
    1            10-March

I have a Table called stagechange

--------------------------------------
   OppID      Stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    1         Qualify     9-Feb
    1         Develop     7-March
    1         Prospect    9-April

How Can I create a new column and get the next row value that is in createdon column; to have something like this. If there is no more next values, we get the date from other table like actual close date in Opp Table

--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       9-Feb
    1         Qualify     9-Feb        7-March
    1         Develop     7-March      9-April
    1         Prospect    9-April     10-March ----(actualclosedate)

Body:
This will replace the final/missing date with actualclosedate

Select A.*
      ,NewColumn = IsNull(Lead(creaton) over (Partition By A.OppID Order By A.CreateOn),B.actualclosedate)
 From  stagechange A
 Join  Opp         B on A.OppID=B.OppID


问:
Javascript string object to array
I want to pass some data from html to jquery using data-attribute like this:

```<code><div data-frames="[
    { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
    { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
    { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
    { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
    { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
    { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' }
]"></div>
</code>```

I don't know a way how could I use this structure in jquery so it keeps the same format (array with objects). Is there a way to do this?

Using string.split(',') doesn't help me here.

答:
<s>JSON.stringify(your_data) before assigning it to data-frames. And while fetching, JSON.parse(your_data) before using.</s>

EDIT: Since the data is not in the correct JSON format, there are two ways of accessing it using javascript.

As pointed out by @trincot, put formatted JSON to your data-frames, and then access it using .data method. Note: If the data is not in proper JSON format (just like it is seen in the question) the 2nd way (point #2 below) will work.

Using eval("("+your_data+")") will evaluate your data string into a javascript object. You can only then use JSON methods on it (i.e. after evaluation).

After using both the ways (fiddle here with lots of console logs), I think the 1st one would be a better solution (as pointed out by @trincot)

Title: Javascript string object to array

Body:
I want to pass some data from html to jquery using data-attribute like this:

I don't know a way how could I use this structure in jquery so it keeps the same format (array with objects). Is there a way to do this?

Using string.split(',') doesn't help me here.


问:
Avoid sending full table with MongoDB and Pymongo
I'm trying to get the min and max value from some fields inside a collection. I'm not sure if this:

```<code>result = collection.find(date_filter, expected_projection).sort({'attribute': -1}).limit(1)
</code>```

is equivalent to this:

```<code>result_a = collection.find(date_filter, expected_projection)
result_b = result_a.sort({'attribute': -1}).limit(1)
</code>```

I don't want the server to query all the data in result_a from the database. Is the first line of code actually fetching every document in my collection and THEN sorting it, or just fetching the max element in the attribute field?

答:
No, they aren't equivalent; and MongoDB will not return the entire collection to the client - whether or not the attribute field is indexed.

When you chain operators together in a MongoDB command (e.g. find().sort().limit()), it is not treated by the MongoDB server as a set of separate functions to be called sequentially; it is treated as a single query which should be optimised as a whole and executed as a whole on the MongoDB server.

See the documentation on Combining Cursor Methods for another example of how the chaining is not taken as a sequence of independent operations:

The following statements chain cursor methods limit() and sort():

  db.bios.find().sort( { name: 1 } ).limit( 5 )
  db.bios.find().limit( 5 ).sort( { name: 1 } )
```

The two statements are equivalent; i.e. the order in which you chain the limit() and the sort() methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on ‘name’.

Body:
I'm trying to get the min and max value from some fields inside a collection. I'm not sure if this:

result = collection.find(date_filter, expected_projection).sort({'attribute': -1}).limit(1)

is equivalent to this:

result_a = collection.find(date_filter, expected_projection)
result_b = result_a.sort({'attribute': -1}).limit(1)

I don't want the server to query all the data in result_a from the database. Is the first line of code actually fetching every document in my collection and THEN sorting it, or just fetching the max element in the attribute field?

Body:
No, they aren't equivalent; and MongoDB will not return the entire collection to the client - whether or not the attribute field is indexed.

When you chain operators together in a MongoDB command (e.g. find().sort().limit()), it is not treated by the MongoDB server as a set of separate functions to be called sequentially; it is treated as a single query which should be optimised as a whole and executed as a whole on the MongoDB server.

See the documentation on Combining Cursor Methods for another example of how the chaining is not taken as a sequence of independent operations:

The following statements chain cursor methods limit() and sort():

  db.bios.find().sort( { name: 1 } ).limit( 5 )
  db.bios.find().limit( 5 ).sort( { name: 1 } )

The two statements are equivalent; i.e. the order in which you chain the limit() and the sort() methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on ‘name’.


问:
Referencing jars in jnlp file
I have the below JNLP file. I have created the appropriate folders, when the jnlp file downloads, message the system cannot find the specified path is seen at the console.
```<code>
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.5" codebase="http://localhost:8080/myapp/jars">
    <information>
        <title>MyApp</title>
        <vendor>MyApp</vendor><br>
    </information>
    <resources>
    <jar href="main.jar"/>
    <jar href="jcalendar.jar"/>
    <jar href="apps/jdi.jar"/>
    <jar href="JGo.jar"/>
 </resources>
    <security>
        <all-permissions/>
    </security>
    <application-desc main-class="com.myapp.jars.Main"><br>
    </application-desc><br>
</jnlp><br>
```
```<code>
Java Web Start 1.6.0_22
Using JRE version 1.6.0_22-b04 Java HotSpot(TM) Client VM
User home directory = C:\Documents and Settings\
<----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
m:   print memory usage
o:   trigger logging
p:   reload proxy configuration
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack</p>

<h2>0-5: set trace level to </h2>

<p>/myapps/jars/main.jar
/myapps/jars/jcalendar.jar
\myapps\jars\apps\jdi.jar(The system cannot find the path specified)
/myapps/jars/jGo.jar
```

I have the jars signed, and placed them under the folder jars/apps/jdo.jar

Could some one help me.

Thanks,
Karthik

When I include along with other jars within jars folder, the console throws Unable to load the resource file (jdi.jar)
```<code>
com.sun.deploy.net.FailedDownloadException: Unable to load resource: <a href="http://localhost:8080/myapp/jars/jdi.jar" rel="nofollow">http://localhost:8080/myapp/jars/jdi.jar</a>
    at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
    at com.sun.javaws.LaunchDownload$DownloadTask.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
```

答:
Is the missing jar really in a folder called apps at http://localhost:8080/myapp/jars/apps/jdi.jar ?   If jdi.jar is in same place as other jars, try:

```<code><jar href="jdi.jar"/>
</code>```

Title: Referencing jars in jnlp file

Body:
I have the below JNLP file. I have created the appropriate folders, when the jnlp file downloads, message the system cannot find the specified path is seen at the console.

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.5" codebase="http://localhost:8080/myapp/jars">
    <information>
        <title>MyApp</title>
        <vendor>MyApp</vendor>

    </information>
    <resources>
    <jar href="main.jar"/>
    <jar href="jcalendar.jar"/>
    <jar href="apps/jdi.jar"/>
    <jar href="JGo.jar"/>
 </resources>
    <security>
        <all-permissions/>
    </security>
    <application-desc main-class="com.myapp.jars.Main">

    </application-desc>

</jnlp>

Java Web Start 1.6.0_22
Using JRE version 1.6.0_22-b04 Java HotSpot(TM) Client VM
User home directory = C:\Documents and Settings\
<----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
m:   print memory usage
o:   trigger logging
p:   reload proxy configuration
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack

0-5: set trace level to

/myapps/jars/main.jar
/myapps/jars/jcalendar.jar
\myapps\jars\apps\jdi.jar(The system cannot find the path specified)
/myapps/jars/jGo.jar

I have the jars signed, and placed them under the folder jars/apps/jdo.jar

Could some one help me.

Thanks,
Karthik

When I include along with other jars within jars folder, the console throws Unable to load the resource file (jdi.jar)

com.sun.deploy.net.FailedDownloadException: Unable to load resource: http://localhost:8080/myapp/jars/jdi.jar
    at com.sun.deploy.net.DownloadEngine.actionDownload(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
    at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
    at com.sun.javaws.LaunchDownload$DownloadTask.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Body:
Is the missing jar really in a folder called apps at http://localhost:8080/myapp/jars/apps/jdi.jar ?   If jdi.jar is in same place as other jars, try:

<jar href="jdi.jar"/>


问:
Separating a String from a CSV file
Currently I'm letting users import a CSV-file created from Excel or Numbers. The sheet has multiple fields and I can import these without problem.

However, one of the fields looks like this:

```<code>"[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"
</code>```

How should I separate this field into a dictionary looking like this:

```<code>//[String: [[Int: String]]]

[
    "Title1": [[100: "S11"], [100: "S12"], [100:   "10"], [100:   "2"], [100:   "3"]],
    "Title2": [[300:  "50"], [300:  "90"], [300: "100a"], [300:   "D"], [300:   "E"]],
    "Title3": [[500:   "2"], [500: "112"], [500:    "6"], [500: "110"], [500: "113"]]
]
</code>```

This field is created by the user itself and this already seems to be a bit too complicated and prone to error's. Perhaps a better question would be how to format this better instead of splitting this field into the dictionary I want?

Perhaps a simplified version:

```<code>//[String: [Int: [String]]]

[
    "Title1": [100: ["S11", "S12",   "10",   "2",   "3"]],
    "Title2": [300:  ["50",  "90", "100a",   "D",   "E"]],
    "Title3": [500:   ["2", "112",    "6", "110", "113"]]
]
</code>```

Some explanation about this field:

Title: can be anything, it's the title of the nested dictionary

The key in the nested dictionary can be 100, 200, 300, 400, 500 or 600

The value in the nested dictionary is a String which forms a unique key together with they key in this nested dictionary.

This means:

```<code>100: "S11" and 200: "S11" // valid
100: "S11" and 100: "S11" // not valid
</code>```

```<code>extension String {

    // Separate alphanumeric characters
    func split(_ number: Int = 1) -> [String] {
        let number = max(number, 1)

        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { $0.characters.count > number - 1 }
    }
}

let string = "Appetizer: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3) * Main: (300: 50), (300: 90), (300: 100a), (300: D), (300: E) * Dessert: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)"

let values = string.components(separatedBy: "*").map { $0.split() }

var result: [String: [Int: [String]]] = [:]

values.forEach {
    guard let key = $0.first else { return }

    result[key] = result[key] ?? [:]

    let values = $0.dropFirst()

    let name = values.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 }
    let code = values.enumerated().filter { $0.0 % 2 != 0 }.map { $0.1 }

    zip(name, code).forEach {
        guard let category = Int($0.0) else { return }

        result[key]?[category] = (result[key]?[category] ?? []) + [$0.1]
    }
}
</code>```

This code produces the result I wanted, but it seems very ugly and it's too much dependant on the location of the values (instead of checking the values).

Any suggestion on how to do this using a much simpler and more elegant way?

答:
I assume that you settled on the first export format, i.e.

```<code>[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]
</code>```

You can use RegEx to parse that string. The answer below does not handle errors. Also it will not work if you title contains a semicolon (:)

```<code>extension String {
    subscript(_ range: NSRange) -> String {
        let startIndex = self.utf16.index(self.utf16.startIndex, offsetBy: range.location)
        let endIndex = self.utf16.index(startIndex, offsetBy: range.length)

        return String(describing: self.utf16[startIndex..<endIndex])
    }
}

let str = "[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"
let regex1 = try! NSRegularExpression(pattern: "\\[(.+?): (.+?)\\]", options: [])
let regex2 = try! NSRegularExpression(pattern: "\\((\\d+?): (.+?)\\)", options: [])

var result = [String: [Int: [String]]]()

regex1.enumerateMatches(in: str, options: [], range: NSMakeRange(0, str.utf16.count)) { match1, _, _ in
    guard let match1 = match1 else { return }

    let title = str[match1.rangeAt(1)]
    let categoriesStr = str[match1.rangeAt(2)]
    var categories = [Int: [String]]()

    regex2.enumerateMatches(in: categoriesStr, options: [], range: NSMakeRange(0, categoriesStr.utf16.count)) { match2, _, _ in
        guard let match2 = match2 else { return }

        let number = Int(categoriesStr[match2.rangeAt(1)])!
        let identifier = categoriesStr[match2.rangeAt(2)]

        if categories[number] == nil {
            categories[number] = [String]()
        }
        categories[number]!.append(identifier)
    }

    result[title] = categories
}

print(result)
</code>```

Title: Separating a String from a CSV file

Body:
Currently I'm letting users import a CSV-file created from Excel or Numbers. The sheet has multiple fields and I can import these without problem.

However, one of the fields looks like this:

"[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"

How should I separate this field into a dictionary looking like this:

//[String: [[Int: String]]]

[
    "Title1": [[100: "S11"], [100: "S12"], [100:   "10"], [100:   "2"], [100:   "3"]],
    "Title2": [[300:  "50"], [300:  "90"], [300: "100a"], [300:   "D"], [300:   "E"]],
    "Title3": [[500:   "2"], [500: "112"], [500:    "6"], [500: "110"], [500: "113"]]
]

This field is created by the user itself and this already seems to be a bit too complicated and prone to error's. Perhaps a better question would be how to format this better instead of splitting this field into the dictionary I want?

Perhaps a simplified version:

//[String: [Int: [String]]]

[
    "Title1": [100: ["S11", "S12",   "10",   "2",   "3"]],
    "Title2": [300:  ["50",  "90", "100a",   "D",   "E"]],
    "Title3": [500:   ["2", "112",    "6", "110", "113"]]
]

Some explanation about this field:

Title: can be anything, it's the title of the nested dictionary

The key in the nested dictionary can be 100, 200, 300, 400, 500 or 600

The value in the nested dictionary is a String which forms a unique key together with they key in this nested dictionary.

This means:

100: "S11" and 200: "S11" // valid
100: "S11" and 100: "S11" // not valid

extension String {

    // Separate alphanumeric characters
    func split(_ number: Int = 1) -> [String] {
        let number = max(number, 1)

        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { $0.characters.count > number - 1 }
    }
}

let string = "Appetizer: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3) * Main: (300: 50), (300: 90), (300: 100a), (300: D), (300: E) * Dessert: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)"

let values = string.components(separatedBy: "*").map { $0.split() }

var result: [String: [Int: [String]]] = [:]

values.forEach {
    guard let key = $0.first else { return }

    result[key] = result[key] ?? [:]

    let values = $0.dropFirst()

    let name = values.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 }
    let code = values.enumerated().filter { $0.0 % 2 != 0 }.map { $0.1 }

    zip(name, code).forEach {
        guard let category = Int($0.0) else { return }

        result[key]?[category] = (result[key]?[category] ?? []) + [$0.1]
    }
}

This code produces the result I wanted, but it seems very ugly and it's too much dependant on the location of the values (instead of checking the values).

Any suggestion on how to do this using a much simpler and more elegant way?

Body:
I assume that you settled on the first export format, i.e.

[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]

You can use RegEx to parse that string. The answer below does not handle errors. Also it will not work if you title contains a semicolon (:)

extension String {
    subscript(_ range: NSRange) -> String {
        let startIndex = self.utf16.index(self.utf16.startIndex, offsetBy: range.location)
        let endIndex = self.utf16.index(startIndex, offsetBy: range.length)

        return String(describing: self.utf16[startIndex..<endIndex])
    }
}

let str = "[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"
let regex1 = try! NSRegularExpression(pattern: "\\[(.+?): (.+?)\\]", options: [])
let regex2 = try! NSRegularExpression(pattern: "\\((\\d+?): (.+?)\\)", options: [])

var result = [String: [Int: [String]]]()

regex1.enumerateMatches(in: str, options: [], range: NSMakeRange(0, str.utf16.count)) { match1, _, _ in
    guard let match1 = match1 else { return }

    let title = str[match1.rangeAt(1)]
    let categoriesStr = str[match1.rangeAt(2)]
    var categories = [Int: [String]]()

    regex2.enumerateMatches(in: categoriesStr, options: [], range: NSMakeRange(0, categoriesStr.utf16.count)) { match2, _, _ in
        guard let match2 = match2 else { return }

        let number = Int(categoriesStr[match2.rangeAt(1)])!
        let identifier = categoriesStr[match2.rangeAt(2)]

        if categories[number] == nil {
            categories[number] = [String]()
        }
        categories[number]!.append(identifier)
    }

    result[title] = categories
}

print(result)


答:
You can use the parseJSON() function of jQuery.

https://api.jquery.com/jQuery.parseJSON/

Title: Javascript string object to array


问:
How to calculate Intersection over Union for 2 rectangles with the different orientation in python?
My ground truth is oriented rectangle. How can I calculate IoU between my output rectangle and ground truth?
Ground truth has these parameters: x_centre,y_centre,height,width,angle of orientation.</p>

答:
The simplest way is using some library providing boolean operations over polygons. Choose one that has Python bindings.

Clipper library  features:

Line and polygon clipping - intersection, union, difference & xor

  The library is written in Delphi, C++, C# and Python

  Third-party modules for Perl, Ruby and Python languages

If you want to make calculations 'by hands', consider O'Rourke algorithm (free code for his book is here) or Plante's approach to get intersection, and do some research to extend these methods and find union.


问:
Route without parameter value; Angular route redirect - Can I use redirectTo to parameter path?
I'm wandering if it is possible to redirect path: ' ' to path: ':id' ? Is there a way I can achieve this?

Thank you.

```<code>{
  path: 'folder',
  children: [
    {
      path: '',
      redirectTo: ':id',
      pathMatch: 'full',
    },
    {
      path: ':id',
      canActivate: [AuthGuard],
      component: DocumentsComponent,
    },
  ]
}
</code>```

答:
I found a way to redirect 'folder' route to 'folder/:id' with empty 'id' parameter: </p>

```<code>{
    path: 'folder',
    redirectTo: 'folder/',
    pathMatch: 'full',
},
{
    path: 'folder',
    children: [
        {
            path: ':id',
            canActivate: [AuthGuard],
            component: DocumentsComponent,
        },
    ]
}
</code>```

<p>*Note that the redirect must be first.</p>

Body:
I'm wandering if it is possible to redirect path: ' ' to path: ':id' ? Is there a way I can achieve this?

Thank you.

{
  path: 'folder',
  children: [
    {
      path: '',
      redirectTo: ':id',
      pathMatch: 'full',
    },
    {
      path: ':id',
      canActivate: [AuthGuard],
      component: DocumentsComponent,
    },
  ]
}

Body:
I found a way to redirect 'folder' route to 'folder/:id' with empty 'id' parameter:

{
    path: 'folder',
    redirectTo: 'folder/',
    pathMatch: 'full',
},
{
    path: 'folder',
    children: [
        {
            path: ':id',
            canActivate: [AuthGuard],
            component: DocumentsComponent,
        },
    ]
}

*Note that the redirect must be first.


问:
Building an NSstring out of an NSMutableArray
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?</p>

```<code>  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: %@ ", ans);
    }
</code>```

答:
the method stringByAppendingString: returns a new string made by appending the given string to the receiver.

so you want ans = [ans stringByAppendingString:obj];

Body:
My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?

  NSString *ans = @"";
    for (id obj in anExpression)
    {
        if ([obj isKindOfClass:[NSString class]])
            [ans stringByAppendingString:(NSString *)obj];
        if ([obj isKindOfClass:[NSNumber class]])
            [ans stringByAppendingString:(NSString *)[obj stringValue]];

        NSLog(@"String so far: %@ ", ans);
    }


问:
Connection error with mongodb using Rmongo
I am running meteor application in a localhost on port 3000 and I can't connect R with my MongoDB. ( I checked this code for MongoDB running on port 27017 without meteor - just pure database and it's working properly). Meteor create an own database which is calling meteor and inside are my collections ( including images in this sample).

```<code> library(RMongo)
 mongo<- mongoDbConnect("meteor", host="127.0.0.1", port=3000) #error
 #mongo<- mongoDbConnect("meteor", host="127.0.0.1", port=27017)# - that's work

 output <- dbGetQuery(mongo, 'images', '{}')
 print(output)
</code>```

I have this error:

error in '.jcall(rmongo.object@javaMongo, "S", "dbGetQuery", collection, ':

com.mongodb.MongoException$Network: Read operation to server /127.0.0.1:3000 failed on database meteor

dbGetQuery ... dbGetQueryForKeys -> dbGetQueryForKeys -> .jcall -> .jcheck -> .Call

EDIT:
the same problem with any other R packages like mongolite

No suitable servers found (serverSelectionTryOnce set): [connection closed calling ismaster on 'localhost:3000']

答:
In case that somebody else will have this problem:
type:

```<code> meteor mongo -U
</code>```

to get URL address of your db, and now copy paste to host:""

Body:
I am running meteor application in a localhost on port 3000 and I can't connect R with my MongoDB. ( I checked this code for MongoDB running on port 27017 without meteor - just pure database and it's working properly). Meteor create an own database which is calling meteor and inside are my collections ( including images in this sample).

 library(RMongo)
 mongo<- mongoDbConnect("meteor", host="127.0.0.1", port=3000) #error
 #mongo<- mongoDbConnect("meteor", host="127.0.0.1", port=27017)# - that's work

 output <- dbGetQuery(mongo, 'images', '{}')
 print(output)

I have this error:

error in '.jcall(rmongo.object@javaMongo, "S", "dbGetQuery", collection, ':

com.mongodb.MongoException$Network: Read operation to server /127.0.0.1:3000 failed on database meteor

dbGetQuery ... dbGetQueryForKeys -> dbGetQueryForKeys -> .jcall -> .jcheck -> .Call

EDIT:
the same problem with any other R packages like mongolite

No suitable servers found (serverSelectionTryOnce set): [connection closed calling ismaster on 'localhost:3000']

Body:
In case that somebody else will have this problem:
type:

 meteor mongo -U

to get URL address of your db, and now copy paste to host:""


问:
division in php
```<code> $voltage = '0.4000';
                    $newValue = str_replace('0.','',$voltage);
                    echo 'newvalue'.$newValue;
                    $newValue = $voltage/0.0125;
                    echo 'newvalue'.$newValue;
</code>```

when i do like this i get 32 after division where as i should get 320000. any problem in wht i am doing ?

答:
You said $newValue = $voltage/0.0125. You probably meant to say $newValue = $newValue/0.0125

You never changed $voltage so it's still 0.4000, not 4000.

Title: division in php

Body:
 $voltage = '0.4000';
                    $newValue = str_replace('0.','',$voltage);
                    echo 'newvalue'.$newValue;
                    $newValue = $voltage/0.0125;
                    echo 'newvalue'.$newValue;

when i do like this i get 32 after division where as i should get 320000. any problem in wht i am doing ?


答:
If you swap the use of single and double quotes (to make it JSON compliant), the jQuery data method does the JSON parsing on-the-fly:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). [ ... ]

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

Demo:

// jQuery recognises JSON:
console.log($('div').data('frames'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Title: Javascript string object to array

Body:
If you swap the use of single and double quotes (to make it JSON compliant), the jQuery data method does the JSON parsing on-the-fly:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). [ ... ]

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

Demo:

// jQuery recognises JSON:
console.log($('div').data('frames'));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-frames='[
    { "src": "artwork-96.png",  "sizes": "96x96",   "type": "image/png" },
    { "src": "artwork-128.png", "sizes": "128x128", "type": "image/png" },
    { "src": "artwork-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "artwork-256.png", "sizes": "256x256", "type": "image/png" },
    { "src": "artwork-384.png", "sizes": "384x384", "type": "image/png" },
    { "src": "artwork-512.png", "sizes": "512x512", "type": "image/png" }
]'></div>


问:
How to delete quotation marks from a text file using batch file?
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

```<code>echo %name%>./User_Records/%username%.txt
</code>```

in the text file it is saving as

```<code>"Firstname Lastname"
</code>```

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

```<code>Firstname Lastname
</code>```

答:
Try replacing all instances of " in the %name% variable by using Environment variable substitution (see set /? for more)

```<code>@echo off
set "name=%name:"=%"
echo %name%>./User_Records/%username%.txt
</code>```

If you are trying to replace the quotation marks after the text file has been saved, then refer to this previous question

Body:
I am trying to edit out the quotation marks that have been inputed into a text file using .bat.

echo %name%>./User_Records/%username%.txt

in the text file it is saving as

"Firstname Lastname"

I am trying to add to the batch file so that it will edit the *.txt file and delete the quotation marks if they are saved in that text file.

Can anyone help me?

I have been trying to do this for weeks. I want the output to look like

Firstname Lastname

Body:
Try replacing all instances of " in the %name% variable by using Environment variable substitution (see set /? for more)

@echo off
set "name=%name:"=%"
echo %name%>./User_Records/%username%.txt

If you are trying to replace the quotation marks after the text file has been saved, then refer to this previous question


问:
Input field not returning the expected value
I am trying to return the file path of an image via an input field with type file, where the user selects the image from the window that appears when the user clicks the browse button. I need to use this path so that after the user selects an image it is placed in the webpage. The file structure is shown below:

```<code>-Local Disk (C)
  -Users
    -f
      -Desktop
        -001.jpg <-- the image
        -index.html <-- the webpage
</code>```

I am expecting the input field to return the absolute path of the image, that is C:/Users/f/Desktop/001.jpg, while it is just returning C:\fakepath\001.jpg. Here is the code:

function myFunction() {
  var image = document.createElement('img');
  image.src = document.getElementById('image').value;
  console.log(document.getElementById('image').value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="image" type="file" onchange="myFunction()"></code>```

答:
That's not possible. It is a browser limitation.

Browsers hide the real path when uploading files to ensure security.

Body:
I am trying to return the file path of an image via an input field with type file, where the user selects the image from the window that appears when the user clicks the browse button. I need to use this path so that after the user selects an image it is placed in the webpage. The file structure is shown below:

-Local Disk (C)
  -Users
    -f
      -Desktop
        -001.jpg <-- the image
        -index.html <-- the webpage

I am expecting the input field to return the absolute path of the image, that is C:/Users/f/Desktop/001.jpg, while it is just returning C:\fakepath\001.jpg. Here is the code:

function myFunction() {
  var image = document.createElement('img');
  image.src = document.getElementById('image').value;
  console.log(document.getElementById('image').value);
}

<input id="image" type="file" onchange="myFunction()">


问:
HttpClient is not found in .NET 4.5
I am trying to use the new HttpClient in .NET 4.5, but Visual Studio complains that it doesn't exist. I have System.Net, but when I type System.Net.Http, it complains for that too.

Am I supposed to download a new distributable for this class?

答: Start using vs2017, and encounter same problem, when creating Native + PCL, couldn't find the HttpClient, going to Nuget and get Microsoft.Net.Http solve my problems.

Title: HttpClient is not found in .NET 4.5


问:
Creating a small struct in C - have some errors
```<code>#include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}
</code>```

There is the code.
Errors:

'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.
```

What am I doing wrong?

答: use getchar() instead of _getch(). also, you don't need to include "stdafx.h". remove it.avoid including headers you don't need.</p>

Body:
#include "stdio.h"
#include "stdafx.h"
#define _CRT_SECURE_NO_WARNINGS
#define getch() _getch()

struct Clicker {
    int toggle;
    int average;
};

int main()
{
    struct Clicker *clicker;
    printf("Enter your toggle key: ");
    (*clicker).toggle = _getch();
    printf("Enter your average cps: ");
    scanf_s("%d", (*clicker).average);
    printf("\nCurrent settings: \nToggle: %i \nAverage:%i\n", clicker->toggle, clicker->average);
    getchar();
    return 1;
}

There is the code.
Errors:

'_getch' undefined, assuming extern returning int
'scanf_s' format string '%d' requires an argument of type 'int *' but variadic arguemnt 1 has type int.
uninitialized local variable 'clicker' used.

What am I doing wrong?


答:
Err... I'm sure it's typo, but I think you meant</p>

```<code>$newValue = $newValue / 0.0125
</code>```

Title: division in php

Body:
Err... I'm sure it's typo, but I think you meant

$newValue = $newValue / 0.0125


问:
Python class inheritance __init__
So, here's the problem..

if you do this:

```<code>class x(object):
  def __init__(self):
    pass
</code>```

why would you explicitly call init in child class to access parent class attribute? (class y has class x attribute anyway.)

```<code>class y(x):
  def __init__(self):
    x.__init__(self)
</code>```

Cheers.

Edit:

I read this article https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/, it says "In real life we tend to run the initializer for every parent class. This is simply because of how program designs tend to be. In our simple example a way to solve this is to explicitly call the initializer of A:" Could someone please explain?

答:
Because the child class inherits from the parent class, of course, that means everything: methods, attributes and the constructor.
So instead of rewrite all the __init__ code, you just use what is already written in the parent class.
Hope it makes sense to you.

Title: Python class inheritance __init__

Body:
So, here's the problem..

if you do this:

class x(object):
  def __init__(self):
    pass

why would you explicitly call init in child class to access parent class attribute? (class y has class x attribute anyway.)

class y(x):
  def __init__(self):
    x.__init__(self)

Cheers.

Edit:

I read this article https://linuxmeerkat.wordpress.com/2015/04/28/why-you-should-use-super-in-python/, it says "In real life we tend to run the initializer for every parent class. This is simply because of how program designs tend to be. In our simple example a way to solve this is to explicitly call the initializer of A:" Could someone please explain?


问:
Which Python version is installed in another conda env
How can I find out which Python version is installed in a conda environment where I know the name, but do not want to activate that environment?

Background: I have chosen the lazy way to get python3.6 on my Ubuntu 14.04 machine and installed conda. But I would like to add certain directories to my PYTHONPATH depending on whether the environment has python2.x or python3.x and I plan to do this by wrapping conda's activate like so:

```<code>PYMAJOR=$(a_miracle_occurs $CONDAENV)
BASHRC=$(cat <<EOF
source ~/.bashrc
source activate $CONDAENV
export PATH=...
export PYTHONPATH=".../modules$PYMAJOR"
"
EOF
)
bash --rcfile <(echo "${BASHRC}")
</code>```

I have no compatibility issues with subversions of python and I do not want to setup.py develop the modules in the PYTHONPATH-to-be because there are still too many changes, also on structural level.

Remark: I am aware of conda list -n ENVNAME but this would involve parsing human readable output and I would feel better off to have something retrieving the info in machine readable form.

答:
I am not at all familiar with anaconda and everything that follows is a wild guess. If anaconda uses virtualenv internally, the virtualenv should be installed into some directory (maybe something like $ANACONDA_HOME/envs/$CONDAENV?).

If that's the case, then the Python version should be retrievable by simply running $ANACONDA_HOME/envs/$CONDAENV/bin/python --version.

EDIT to address OPs comment:

To only return the version string try:

```<code>$ANACONDA_HOME/envs/$CONDAENV/bin/python -c 'import platform; print(platform.python_version())'
>>> 3.6.0
</code>```

Body:
How can I find out which Python version is installed in a conda environment where I know the name, but do not want to activate that environment?

Background: I have chosen the lazy way to get python3.6 on my Ubuntu 14.04 machine and installed conda. But I would like to add certain directories to my PYTHONPATH depending on whether the environment has python2.x or python3.x and I plan to do this by wrapping conda's activate like so:

PYMAJOR=$(a_miracle_occurs $CONDAENV)
BASHRC=$(cat <<EOF
source ~/.bashrc
source activate $CONDAENV
export PATH=...
export PYTHONPATH=".../modules$PYMAJOR"
"
EOF
)
bash --rcfile <(echo "${BASHRC}")

I have no compatibility issues with subversions of python and I do not want to setup.py develop the modules in the PYTHONPATH-to-be because there are still too many changes, also on structural level.

Remark: I am aware of conda list -n ENVNAME but this would involve parsing human readable output and I would feel better off to have something retrieving the info in machine readable form.

Body:
I am not at all familiar with anaconda and everything that follows is a wild guess. If anaconda uses virtualenv internally, the virtualenv should be installed into some directory (maybe something like $ANACONDA_HOME/envs/$CONDAENV?).

If that's the case, then the Python version should be retrievable by simply running $ANACONDA_HOME/envs/$CONDAENV/bin/python --version.

EDIT to address OPs comment:

To only return the version string try:

$ANACONDA_HOME/envs/$CONDAENV/bin/python -c 'import platform; print(platform.python_version())'
>>> 3.6.0