问:
Status function bar - C
I have this function:

```<code>void choiceTwo(void){

    system("clear");
    printf("================ RUN ALL FUNCTION ================\n\n");

    printf("\nTest case 'create/destroy'... ");
    fflush(stdout);
    test_create_destroy();
    printf("OK\n");

    printf("Test case 'add/remove edge'... ");
    fflush(stdout);
    test_add_remove_edge();
    printf("OK\n");

    printf("Test case 'print graph'... ");
    fflush(stdout);
    test_print_graph();
    printf("OK\n");

    printf("Test case 'null'... ");
    fflush(stdout);
    test_null();
    printf("OK\n");

    printf("\nPress enter to continue ");
    getchar();
    getchar();
    main();
}
</code>```

How can I print the status of this function by using a progress bar (in percent) like this in the picture?

Status Bar

I tried to do this using python, but do not know how to fully control the function status

答:
The precision field, %.precision, will let you print a specific number of characters. An asterisk will allow the use of a variable. %.*s will print done number of characters from the x array, then 50 - done characters from the dash array.

Using a carriage return, \r, should keep printing the loop on the same line as the loop progresses.

```<code>#include <stdio.h>

int main()
{
    int loop = 1;
    int done = 0;
    int end = 200000;
    char dash[51] = "--------------------------------------------------";
    char x[51] =    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    float percent = 0.0f;
    while ( loop <= end) {
        percent = ( (float)loop * 100) / end;
        done = percent / 2.0f;
        printf ( "Progress: [%.*s%.*s]%6.1f%% Complete\r", done, x, 50 - done, dash, percent);
        loop++;
    }
    printf ( "\n");
    return 0;
}
</code>```

If your terminal supports escape codes, this may be used to achieve the colors indicated in the image.

```<code>#include <stdio.h>

int main()
{
    int loop = 1;
    int done = 0;
    int end = 200000;
    char dash[51]  = "--------------------------------------------------";
    char blank[51] = "                                                  ";
    float percent = 0.0f;
    printf ( "\033[?25l");//hide cursor
    printf ( "\033[38;5;10m");//green text
    printf ( "\033[48;5;0m");//on black
    while ( loop <= end) {
        percent = ( (float)loop * 100) / end;
        done = percent / 2.0f;
        printf ( "Progress: [\033[38;5;0m\033[48;5;10m");//black text on green
        printf ( "%.*s\033[38;5;10m\033[48;5;0m%.*s]%6.1f%% Complete\r"//back to green text on black
        , done, blank, 50 - done, dash, percent);
        loop++;
    }
    printf ( "\033[0m");//reset color
    printf ( "\033[?25h");//show cursor
    printf ( "\n");
    return 0;
}
</code>```

this wraps the progress in a function. call this function with the line you want the bar shown on ( 0 to 23), the items done so far and the total items.

```<code>#include <stdio.h>

void working ( int showat, int done, int total) {
    char dash[51]  = "--------------------------------------------------";
    char blank[51] = "                                                  ";
    int portion = 0;
    float percent = 0.0f;

    printf ( "\033[?25l");//hide cursor
    printf ( "\033[38;5;10m");//green text
    printf ( "\033[48;5;0m");//on black
    printf ( "\033[%d;H", showat);//move curson to line showat
    percent = ( (float)done * 100) / total;
    portion = percent / 2.0f;
    printf ( "Progress: [\033[38;5;0m\033[48;5;10m");//black text on green
    printf ( "%.*s\033[38;5;10m\033[48;5;0m%.*s]%6.1f%% Complete\r"//back to green text on black
    , portion, blank, 50 - portion, dash, percent);

    printf ( "\033[0m");//reset color
    printf ( "\033[?25h");//show cursor
}

int main()
{
    int loop = 1;
    int end  = 20000;
    while ( loop <= end) {
        working ( 23, loop, end);
        loop++;
    }
    printf ( "\n");
    return 0;
}
</code>```

Title: Status function bar - C

Body:
I have this function:

void choiceTwo(void){

    system("clear");
    printf("================ RUN ALL FUNCTION ================\n\n");

    printf("\nTest case 'create/destroy'... ");
    fflush(stdout);
    test_create_destroy();
    printf("OK\n");

    printf("Test case 'add/remove edge'... ");
    fflush(stdout);
    test_add_remove_edge();
    printf("OK\n");

    printf("Test case 'print graph'... ");
    fflush(stdout);
    test_print_graph();
    printf("OK\n");

    printf("Test case 'null'... ");
    fflush(stdout);
    test_null();
    printf("OK\n");

    printf("\nPress enter to continue ");
    getchar();
    getchar();
    main();
}

How can I print the status of this function by using a progress bar (in percent) like this in the picture?

Status Bar

I tried to do this using python, but do not know how to fully control the function status

Body:
The precision field, %.precision, will let you print a specific number of characters. An asterisk will allow the use of a variable. %.*s will print done number of characters from the x array, then 50 - done characters from the dash array.

Using a carriage return, \r, should keep printing the loop on the same line as the loop progresses.

#include <stdio.h>

int main()
{
    int loop = 1;
    int done = 0;
    int end = 200000;
    char dash[51] = "--------------------------------------------------";
    char x[51] =    "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    float percent = 0.0f;
    while ( loop <= end) {
        percent = ( (float)loop * 100) / end;
        done = percent / 2.0f;
        printf ( "Progress: [%.*s%.*s]%6.1f%% Complete\r", done, x, 50 - done, dash, percent);
        loop++;
    }
    printf ( "\n");
    return 0;
}

If your terminal supports escape codes, this may be used to achieve the colors indicated in the image.

#include <stdio.h>

int main()
{
    int loop = 1;
    int done = 0;
    int end = 200000;
    char dash[51]  = "--------------------------------------------------";
    char blank[51] = "                                                  ";
    float percent = 0.0f;
    printf ( "\033[?25l");//hide cursor
    printf ( "\033[38;5;10m");//green text
    printf ( "\033[48;5;0m");//on black
    while ( loop <= end) {
        percent = ( (float)loop * 100) / end;
        done = percent / 2.0f;
        printf ( "Progress: [\033[38;5;0m\033[48;5;10m");//black text on green
        printf ( "%.*s\033[38;5;10m\033[48;5;0m%.*s]%6.1f%% Complete\r"//back to green text on black
        , done, blank, 50 - done, dash, percent);
        loop++;
    }
    printf ( "\033[0m");//reset color
    printf ( "\033[?25h");//show cursor
    printf ( "\n");
    return 0;
}

this wraps the progress in a function. call this function with the line you want the bar shown on ( 0 to 23), the items done so far and the total items.

#include <stdio.h>

void working ( int showat, int done, int total) {
    char dash[51]  = "--------------------------------------------------";
    char blank[51] = "                                                  ";
    int portion = 0;
    float percent = 0.0f;

    printf ( "\033[?25l");//hide cursor
    printf ( "\033[38;5;10m");//green text
    printf ( "\033[48;5;0m");//on black
    printf ( "\033[%d;H", showat);//move curson to line showat
    percent = ( (float)done * 100) / total;
    portion = percent / 2.0f;
    printf ( "Progress: [\033[38;5;0m\033[48;5;10m");//black text on green
    printf ( "%.*s\033[38;5;10m\033[48;5;0m%.*s]%6.1f%% Complete\r"//back to green text on black
    , portion, blank, 50 - portion, dash, percent);

    printf ( "\033[0m");//reset color
    printf ( "\033[?25h");//show cursor
}

int main()
{
    int loop = 1;
    int end  = 20000;
    while ( loop <= end) {
        working ( 23, loop, end);
        loop++;
    }
    printf ( "\n");
    return 0;
}


来源: stackexchange

问:
Pytest: How to access command line arguments outside of a test
I would like to access command line arguments passed to pytest from within a non-test class.

I have added the following to my conftest.py file

```<code>def pytest_addoption(parser):  # pragma: no cover
  """Pytest hook to add custom command line option(s)."""
  group = parser.getgroup("Test", "My test option")
  group.addoption(
    "--stack",
    help="stack", metavar="stack", dest='stack', default=None)
</code>```

But I can not work out how to access the value passed on the command line.  I have found code on how to access it from a fixture, but I would like to access it from a method or class that is not part of the test case.

答:
You can access the parameters with sys.argv.
It will return a list of all the arguemnts you sent wrote when you called using the command line.

For example

```<code>def pytest_addoption(parser):  # pragma: no cover
  """Pytest hook to add custom command line option(s)."""
  params = sys.argv[1:]
  group = parser.getgroup("Test", "My test option")
  group.addoption(
    "--stack",
    help="stack", metavar="stack", dest='stack', default=None)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to access command line arguments passed to pytest from within a non-test class.

I have added the following to my conftest.py file

def pytest_addoption(parser):  # pragma: no cover
  """Pytest hook to add custom command line option(s)."""
  group = parser.getgroup("Test", "My test option")
  group.addoption(
    "--stack",
    help="stack", metavar="stack", dest='stack', default=None)

But I can not work out how to access the value passed on the command line.  I have found code on how to access it from a fixture, but I would like to access it from a method or class that is not part of the test case.

Body:
You can access the parameters with sys.argv.
It will return a list of all the arguemnts you sent wrote when you called using the command line.

For example

def pytest_addoption(parser):  # pragma: no cover
  """Pytest hook to add custom command line option(s)."""
  params = sys.argv[1:]
  group = parser.getgroup("Test", "My test option")
  group.addoption(
    "--stack",
    help="stack", metavar="stack", dest='stack', default=None)


问:
Android database.sqlite.SQLiteException in Query
I'm new to Android Studio. I am creating a contact manager mobile application. The contacts can be added to my SQLite database and the correct names of contacts are being displayed. When clicked, the name of the contact should appear in another activity. I was using the putExtra method but it would not work. This is my code for the first activity when a name is clicked:

```<code>    lv_contactlist.setAdapter(aa_contacts);
    lv_contactlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String Name = (lv_contactlist.getItemAtPosition(position).toString());
            Intent intent = new Intent(MainActivity.this, FinalActivity.class);
            intent.putExtra("Name",Name);
            startActivity(intent);
        }
    });
</code>```

The second activity receives this name and should show the full contact information. This is my code:

```<code>String Name = getIntent().getStringExtra("Name");
    Cursor cursor = sdb.rawQuery("SELECT * contact WHERE NAME = " + Name, null);
    name.setText("NAME: "+cursor.getString(0));
    homephone.setText("HOME PHONE: "+cursor.getString(1));
    mobilephone.setText("MOBILE PHONE: "+cursor.getString(2));
    mobilephone.setText("EMAIL ADDRESS: "+cursor.getString(3));
</code>```

When debugging, I get the error message:

```<code>java.lang.RuntimeException: Unable to start activity  android.database.sqlite.SQLiteException: near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John)
</code>```

This is the exact name appearing on my list. This has led me to believe it has to be the putExtra method passing the information to the second activity or the getStringExtra method receiving the name. Thanks in advance

答:
You are missing a 'FROM'. It should be something like:

```<code>SELECT * FROM table_name WHERE column = value.
</code>```

In your case, probably:

```<code>SELECT * FROM contact WHERE NAME = John
</code>```

Body:
I'm new to Android Studio. I am creating a contact manager mobile application. The contacts can be added to my SQLite database and the correct names of contacts are being displayed. When clicked, the name of the contact should appear in another activity. I was using the putExtra method but it would not work. This is my code for the first activity when a name is clicked:

    lv_contactlist.setAdapter(aa_contacts);
    lv_contactlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String Name = (lv_contactlist.getItemAtPosition(position).toString());
            Intent intent = new Intent(MainActivity.this, FinalActivity.class);
            intent.putExtra("Name",Name);
            startActivity(intent);
        }
    });

The second activity receives this name and should show the full contact information. This is my code:

String Name = getIntent().getStringExtra("Name");
    Cursor cursor = sdb.rawQuery("SELECT * contact WHERE NAME = " + Name, null);
    name.setText("NAME: "+cursor.getString(0));
    homephone.setText("HOME PHONE: "+cursor.getString(1));
    mobilephone.setText("MOBILE PHONE: "+cursor.getString(2));
    mobilephone.setText("EMAIL ADDRESS: "+cursor.getString(3));

When debugging, I get the error message:

java.lang.RuntimeException: Unable to start activity  android.database.sqlite.SQLiteException: near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John
              Error Code : 1 (SQLITE_ERROR)
              Caused By : SQL(query) error or missing database.
                (near "contact": syntax error (code 1): , while compiling: SELECT * contact WHERE NAME = John)

This is the exact name appearing on my list. This has led me to believe it has to be the putExtra method passing the information to the second activity or the getStringExtra method receiving the name. Thanks in advance

Body:
You are missing a 'FROM'. It should be something like:

SELECT * FROM table_name WHERE column = value.

In your case, probably:

SELECT * FROM contact WHERE NAME = John


问:
How to use Mac OSX Keymap on Windows for WebStorm or IntelliJ IDEA?
I use WebStorm on both my Mac and Windows for work purposes.
I would like to know if it is possible to use the MAC OSX keymap on Windows.

On windows if you load the MAC OSX keymap the mappings don't seem to line up correctly. For instance I see the character Meta being used, however Windows doesn't seem to properly map that character.

I also would like to note I am using a Mac keyboard on the Windows PC.

答: On Windows go to file > settings > keymap and in the keymaps dropdown select default and the meta (aka cmd) key will be replaced by ctrl.


问:
Javascript prevent "undefined" value with dynamic array
I have dynamic form elements and trying to add values to input's value attribute which is coming from as a array. However sometimes there are no any data ,then javascript prints undefined to value area of the input element.

How can i check it and dont print undefined in dynamic element?

```<code>$("#test").append("<input type='text' name='first-test' class='form-control' value='"+testarray['first-test']+"' >
</code>```

When we check the textbox , it shows "undefined" as a value.

答:
I think this will work

```<code>$("#test").append("<input type='text' name='first-test' class='form-control' value='"+(testarray['first-test']===undefined ? "Insert here what ever you want when it is empty.":testarray['first-test'])+"'>");
</code>```

https://jsfiddle.net/b51gq0mq/2/

Body:
I have dynamic form elements and trying to add values to input's value attribute which is coming from as a array. However sometimes there are no any data ,then javascript prints undefined to value area of the input element.

How can i check it and dont print undefined in dynamic element?

$("#test").append("<input type='text' name='first-test' class='form-control' value='"+testarray['first-test']+"' >

When we check the textbox , it shows "undefined" as a value.

Body:
I think this will work

$("#test").append("<input type='text' name='first-test' class='form-control' value='"+(testarray['first-test']===undefined ? "Insert here what ever you want when it is empty.":testarray['first-test'])+"'>");

https://jsfiddle.net/b51gq0mq/2/


问:
Why this CSS code is not working properly in all devices?
I have attached 2 pictures. The iPhone 6 picture is the correct one which should be displayed in all devices. Every page should display the page as in the 1st image (that of iPhone6). It is getting distorted in iPhone 5 (image attached), android devices and in tablets

HTML Code ( using AngularJS and ionic)

```<code><ion-view >
<ion-nav-title>
    <div class="trip-title">Trips</div>
</ion-nav-title>

<ion-content class="aaaaa">

    <ion-tabs class="tabs-striped tabs-top tabs-background-dark tabs-color-energized">

        <ion-tab title="PAST TRIPS" ui-sref="previous" on-select="onPreviousTabSelected()">
        <ion-nav-view name="previous"></ion-nav-view>
        </ion-tab>

        <ion-tab title="UPCOMING TRIPS" ui-sref="future" on-select="onFutureTabSelected()">
            <ion-nav-view name="future"></ion-nav-view>
        </ion-tab>

    </ion-tabs>

    <div class="triprepeat" ng-repeat="item in items| orderBy : '-tripDate'">
       <div class="div-box-trip">
           <img class="cartrip" src="http://www.irantravelservice.com/images/icon/car.png" alt="Custom Image"/>
            <span><div class="date-trip">{{item.starRating}}, {{item.tripDate}}</div></span>
             <span><div class="bookingidtitle-trip">Booking Id : </div></span>
             <span><div class="bookingid-trip">{{item.tripId}}</div></span>
             <span>
             <div class="starttime-trip">{{item.tripStartTime}}</div>
             <div>
                 <img class="arrowright-trip" src="http://worldconflictsresearch.t83.net/communities/8/004/013/145/338//images/4621747970_179x256.png" alt="Custom Arrow Image"/>
              </div>
              </span>
              <span>
              <div class="source-trip">{{item.sourceLocation}}</div>
              <div>
                 <img class="greencircle-trip" src="http://stavangerkarateklubb.no/wp-content/uploads/2016/05/grønn.png" alt="Custom Red Circle"/></div>
              </span>
              <span><div class="dashed-trip"><hr class="dashtrip"/></div></span>
              <span>
              <div class="dest-trip">{{item.destinationLocation}}</div>
              <div><img class="redcircle-trip" src="http://107.6.178.147/wp360/wordpress/wp-content/uploads/2016/04/red.png" alt="Custom Red Circle"/></div>
              </span>
            </div>

       </div>

</ion-content>
</code>```

CSS Code

```<code>.view-container .scroll-content.ionic-scroll.has-header.aaaaa {
  background-color: #ffffff;
}

.cartrip{
  max-width: 40px !important;
  margin-top: 15px;
  margin-left: 20px;
}

.triprepeat{
  background-color: #f1f1f1;
  border-bottom: solid 1.5px #B2B2B2;
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.date-trip{
  margin-left: 80px;
  margin-right: auto;
  margin-top: -50px;
  font-size: 12px;
  color: #000000;
}

.div-box-trip{
  height: 120px;
  width: auto;
}

.bookingidtitle-trip{
  margin-left: 80px;
  margin-top: 8px;
  font-size: 11px;
  color: #A9A9A9;
}

.bookingid-trip{
  margin-left: 160px;
  margin-right: auto;
  margin-top: -20px;
  font-size: 12px;
  color: #000000;
}

.starttime-trip{
  margin-left: 250px;
  margin-right: auto;
  margin-top: -48px;
  font-size: 12px;
}

.arrowright-trip{
  height: 15px;
  width: auto;
  position: absolute;
  margin-top: -18px;
  margin-left: 315px;
}

.source-trip{
  margin-left: 80px;
  margin-top: 40px;
  font-size: 12px;
  color: #000000;
}

.dest-trip{
  margin-left: 280px;
  margin-top: -32px;
  font-size: 12px;
  color: #000000;
}

.greencircle-trip{
  height: 15px;
  width: 15px;
  margin-left: 85px;
}

.redcircle-trip{
 height: 15px;
  width: 15px;
 margin-left: 295px;
}

.dashtrip{
  border-top: dotted 1px;
  width: 170px;
}

.dashed-trip{
  margin-left: 110px;
  margin-top: -10px;
}
</code>```

I am showing through two pictures how the page is getting distorted for some devices, say for example the code is working perfect for iPhone 6 but getting distorted for say iPhone5. This page should work in all mobile and tablet devices

iPhone 6

iPhone 5

I have to make it work for all devices like iPhone6 where it is working perfect. Since this page is mobile only I have not used @Media query.

答:
Consider using the ionic 2 grid system which is specifically created for developing responsive grid layouts.

In your case you would need something like

```<code><ion-grid>
   <ion-row>
      <ion-col col-2>
          Left Side
      </ion-col>

      <ion-col col-10>
         Right side
      </ion-col>
   </ion-row>
</ion-grid>
</code>```

For additional margin and padding you can add some of the ionic 2 css utilities instead of writing up your own css.

```<code> <ion-col col-10 margin-right no-padding>
</code>```

Body:
I have attached 2 pictures. The iPhone 6 picture is the correct one which should be displayed in all devices. Every page should display the page as in the 1st image (that of iPhone6). It is getting distorted in iPhone 5 (image attached), android devices and in tablets

HTML Code ( using AngularJS and ionic)

<ion-view >
<ion-nav-title>

Trips

</ion-nav-title>

<ion-content class="aaaaa">

    <ion-tabs class="tabs-striped tabs-top tabs-background-dark tabs-color-energized">

        <ion-tab title="PAST TRIPS" ui-sref="previous" on-select="onPreviousTabSelected()">
        <ion-nav-view name="previous"></ion-nav-view>
        </ion-tab>

        <ion-tab title="UPCOMING TRIPS" ui-sref="future" on-select="onFutureTabSelected()">
            <ion-nav-view name="future"></ion-nav-view>
        </ion-tab>

    </ion-tabs>

{{item.starRating}}, {{item.tripDate}}

Booking Id :

{{item.tripId}}

{{item.tripStartTime}}

{{item.sourceLocation}}

{{item.destinationLocation}}

</ion-content>

CSS Code

.view-container .scroll-content.ionic-scroll.has-header.aaaaa {
  background-color: #ffffff;
}

.cartrip{
  max-width: 40px !important;
  margin-top: 15px;
  margin-left: 20px;
}

.triprepeat{
  background-color: #f1f1f1;
  border-bottom: solid 1.5px #B2B2B2;
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.date-trip{
  margin-left: 80px;
  margin-right: auto;
  margin-top: -50px;
  font-size: 12px;
  color: #000000;
}

.div-box-trip{
  height: 120px;
  width: auto;
}

.bookingidtitle-trip{
  margin-left: 80px;
  margin-top: 8px;
  font-size: 11px;
  color: #A9A9A9;
}

.bookingid-trip{
  margin-left: 160px;
  margin-right: auto;
  margin-top: -20px;
  font-size: 12px;
  color: #000000;
}

.starttime-trip{
  margin-left: 250px;
  margin-right: auto;
  margin-top: -48px;
  font-size: 12px;
}

.arrowright-trip{
  height: 15px;
  width: auto;
  position: absolute;
  margin-top: -18px;
  margin-left: 315px;
}

.source-trip{
  margin-left: 80px;
  margin-top: 40px;
  font-size: 12px;
  color: #000000;
}

.dest-trip{
  margin-left: 280px;
  margin-top: -32px;
  font-size: 12px;
  color: #000000;
}

.greencircle-trip{
  height: 15px;
  width: 15px;
  margin-left: 85px;
}

.redcircle-trip{
 height: 15px;
  width: 15px;
 margin-left: 295px;
}

.dashtrip{
  border-top: dotted 1px;
  width: 170px;
}

.dashed-trip{
  margin-left: 110px;
  margin-top: -10px;
}

I am showing through two pictures how the page is getting distorted for some devices, say for example the code is working perfect for iPhone 6 but getting distorted for say iPhone5. This page should work in all mobile and tablet devices

iPhone 6

iPhone 5

I have to make it work for all devices like iPhone6 where it is working perfect. Since this page is mobile only I have not used @Media query.

Body:
Consider using the ionic 2 grid system which is specifically created for developing responsive grid layouts.

In your case you would need something like

<ion-grid>
   <ion-row>
      <ion-col col-2>
          Left Side
      </ion-col>

      <ion-col col-10>
         Right side
      </ion-col>
   </ion-row>
</ion-grid>

For additional margin and padding you can add some of the ionic 2 css utilities instead of writing up your own css.

 <ion-col col-10 margin-right no-padding>


问:
formatting of prime factorization algorithm
suppose we have following script for  prime factorization

```<code> z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end
</code>```

but output of this code is not formatted well,for instance

```<code> >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1
</code>```

how can i do  so  that i got

```<code>30=2^1*3^1*5^1?
</code>```

thanks in advance

答:
This could work! Just with a few changes to your code</p>

```<code>z=input('enter your number : ');
str=[num2str(z) '='];
first=0;
for ii=2:z
    s=0;
    while z/ii==floor(z/ii) % check if  z is divisible by ii
        z=z/ii;
        s=s+1;
    end
    if s>0
        if first==0
            str=[str num2str(ii) '^' num2str(s)];
            first=1;
        else
            str=[str '*' num2str(ii) '^' num2str(s)];
            if z == 1
                break
            end
        end
   end
end
</code>```

Body:
suppose we have following script for  prime factorization

 z=input('enter your number : ');
    for ii=2:z
       s=0;
       while z/ii==floor(z/ii) % check if  z is divisible by ii
           z=z/ii;
           s=s+1;
       end
       if s>0
                str = [num2str(ii) '^' num2str(s) ];
            disp(str) ;
            % If z = 1, no more divisions are necessary,
            % thus breaks the loop and quits
            if z == 1
                break
            end
        end

    end

but output of this code is not formatted well,for instance

 >> integer_factorization
    enter your number : 30
    2^1
    3^1
    5^1

how can i do  so  that i got

30=2^1*3^1*5^1?

thanks in advance

Body:
This could work! Just with a few changes to your code

z=input('enter your number : ');
str=[num2str(z) '='];
first=0;
for ii=2:z
    s=0;
    while z/ii==floor(z/ii) % check if  z is divisible by ii
        z=z/ii;
        s=s+1;
    end
    if s>0
        if first==0
            str=[str num2str(ii) '^' num2str(s)];
            first=1;
        else
            str=[str '*' num2str(ii) '^' num2str(s)];
            if z == 1
                break
            end
        end
   end
end


问:
ASP GridView List
If I wanted to add a new item to a <List> with the Data key name from a gridview how would I go about doing it?

Example.

```<code>List<myClass> myList  = new List<myClass>();

myList.add(new myClass(*//The value of the data key name that has been clicked*));
</code>```

A user might click on another item so it would be repeated etc etc.

答:
You have to do this in rowSelected, and get the data key in a form of:

```<code>protected void Gridview_SelectedIndexChanged(..)
{
   GridViewRow row = CustomersGridView.SelectedRow;
  var key = this.gvw.DataKeys[row.RowIndex].Value;
}
</code>```

Forget the exact syntax, but this is essentially what you do.

ContentLicense: CC BY-SA 2.5

Title: ASP GridView List

Body:
If I wanted to add a new item to a <List> with the Data key name from a gridview how would I go about doing it?

Example.

List<myClass> myList  = new List<myClass>();

myList.add(new myClass(*//The value of the data key name that has been clicked*));

A user might click on another item so it would be repeated etc etc.

Body:
You have to do this in rowSelected, and get the data key in a form of:

protected void Gridview_SelectedIndexChanged(..)
{
   GridViewRow row = CustomersGridView.SelectedRow;
  var key = this.gvw.DataKeys[row.RowIndex].Value;
}

Forget the exact syntax, but this is essentially what you do.


问:
Putting names from a file into an array is causing an infinite loop
I have a text file "names" which contains 10 names, each name on its own line. What I want to do is put these names into an array "anArray". Just to check that I'm doing an alright job, I outputted a line as you can see.

Here's the code I used to try to do that:

```<code> public static void main(String[] args) throws FileNotFoundException
    {
        File file=new File("names.txt");
        Scanner my_input= new Scanner(file);
        String [] anArray;
        anArray = new String[10];
        String a = my_input.nextLine();
        while(my_input.hasNextLine())
        {
            for(int i = 0; i<10;i++)
            {
                while (!(a.equals("\n")))
                {
                    anArray[i] = a;
                    System.out.println("Element" + i + "of the array is: " + anArray[i]);

                }
                i++;
                a=my_input.next();
            }
        }
        my_input.close();
    }
</code>```

However this code fails, what happens is "Element 0 of the array is: name 1" is outputted an infinite amount of times, "name 1" being the first name in the text file. I don't know what I'm doing wrong here, could anybody enlighten me?

答:
The condition in the innermost while loop never changes, so the contents will repeat indefinitely.

Something to change the value of the phrase

```<code>while (!(a.equals("\n")))
</code>```

must occur in the body of the loop, otherwise it will stay true if it starts out true.

Body:
I have a text file "names" which contains 10 names, each name on its own line. What I want to do is put these names into an array "anArray". Just to check that I'm doing an alright job, I outputted a line as you can see.

Here's the code I used to try to do that:

 public static void main(String[] args) throws FileNotFoundException
    {
        File file=new File("names.txt");
        Scanner my_input= new Scanner(file);
        String [] anArray;
        anArray = new String[10];
        String a = my_input.nextLine();
        while(my_input.hasNextLine())
        {
            for(int i = 0; i<10;i++)
            {
                while (!(a.equals("\n")))
                {
                    anArray[i] = a;
                    System.out.println("Element" + i + "of the array is: " + anArray[i]);

                }
                i++;
                a=my_input.next();
            }
        }
        my_input.close();
    }

However this code fails, what happens is "Element 0 of the array is: name 1" is outputted an infinite amount of times, "name 1" being the first name in the text file. I don't know what I'm doing wrong here, could anybody enlighten me?

Body:
The condition in the innermost while loop never changes, so the contents will repeat indefinitely.

Something to change the value of the phrase

while (!(a.equals("\n")))

must occur in the body of the loop, otherwise it will stay true if it starts out true.


问:
Passing a dynamic input box value to a an autocomplete get URL
I am using jQuery autocomplete tempplate that I found many years ago on the web. In a new autocomplete applicaton, I need to add a dynamic variable in the URL get string. This dynamic variable originates from another input box.The URL parameter $(database_name) below does not get loaded dynamically. It seems to get loaded when the page is loaded in at start.

Is there a way to do this without creating a trigger to reload the autocomplete.js file?
Code follows ...

var database_name="#database_name"; //html id
$("input#cities").autocomplete( {source:"../../../cgi-bin/rfdb/auto_suggest.pl?table_name=world&search_key=city&database="+ $(database_name).val(),

                minLength:0,
                delay:1,
                enable:true,
                cacheLength:1,
                close:function(event,ui){}
                });

答: I used an autocomplete POST. It seems that "Get" does not dynamically update the variable name. POST does.</p>


问:
CSS transition out error
and sorry for my horrible english.
I have got a problem with CSS and transition.

I need to make a div 100px x 100px, it's just an example of course.

When I put cursor hover it, it should grow and be 500px x 500px.

And here, everything is fine and working.
The thing is, when i remove the cursor, I need that the div return back to 100x100px, but it won't have a transition, it just disappear and return 100x100px.
How can I fix this?

Here is the code i use.

```<code><html>
<head>
  <style>
    div.resize {
      width: 100px;
      height: 100px;
      background: rgb(80,80,80);
      }
      div.resize:hover {
      width: 500px;
      height: 500px;
      transition-duration: 1s;
      }
  </style>
</head>
  <body>
   <div class="resize"></div>
  </body>
</html>
</code>```

答:
Here you go. Just move the transition to the container rather than the :hover. I included the prefixes for other browsers as well. If you want to see how you can modify the transitions, check out W3 Schools.

div.resize {
  width: 100px;
  height: 100px;
  background: rgb(80, 80, 80);

  -webkit-transition: all 1s ease; /* Safari and Chrome */
  -moz-transition: all 1s ease; /* Firefox */
  -o-transition: all 1s ease; /* IE 9 */
  -ms-transition: all 1s ease; /* Opera */
  transition: all 1s ease;

}

div.resize:hover {
  width: 500px;
  height: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="resize">
  </div>
</body></code>```

Title: CSS transition out error

Body:
Here you go. Just move the transition to the container rather than the :hover. I included the prefixes for other browsers as well. If you want to see how you can modify the transitions, check out W3 Schools.

div.resize {
  width: 100px;
  height: 100px;
  background: rgb(80, 80, 80);

  -webkit-transition: all 1s ease; /* Safari and Chrome */
  -moz-transition: all 1s ease; /* Firefox */
  -o-transition: all 1s ease; /* IE 9 */
  -ms-transition: all 1s ease; /* Opera */
  transition: all 1s ease;

}

div.resize:hover {
  width: 500px;
  height: 500px;
}

<body>
  <div class="resize">
  </div>
</body>


问:
Set NSScrollView to not editable
I was wondering how to take care that my NSScrollView is not editable by the user, but i didn't find a way, there is no option in IB, nor do I find an appropriate method of the NSSCrollView class.

A previous post suggested to implement a delegate method

```<code>- (BOOL)textShouldBeginEditing:(NSText *)aTextObject
</code>```

to return false, but this didn't work for me yet.
No solution was given on the previous question.

(I also tried selecting the TextView everything it doesn't display an option 'editable' i just downloaded the new Xcode so the version shouldn't be a problem)

答:
You can't make NSScrollView non-editable. You can hide scrollers with setHasVerical/HorizontalScroller: that would prevent user from scrolling.

If you have NSTextView and want to make it non-editable just send setEditable:NO to it, not the scroll view. For that you obviously need a reference to the NSTextView or use NSScrollViews -documentView.

Title: Set NSScrollView to not editable

Body:
I was wondering how to take care that my NSScrollView is not editable by the user, but i didn't find a way, there is no option in IB, nor do I find an appropriate method of the NSSCrollView class.

A previous post suggested to implement a delegate method

- (BOOL)textShouldBeginEditing:(NSText *)aTextObject

to return false, but this didn't work for me yet.
No solution was given on the previous question.

(I also tried selecting the TextView everything it doesn't display an option 'editable' i just downloaded the new Xcode so the version shouldn't be a problem)


问:
MySQL GTID consistency violation
I am trying to create a table from a select statement, and it give me a GTID consistency violation. [HY000][1786] Statement violates GTID consistency: CREATE TABLE ... SELECT.

```<code>create TABLE tags_mentions as
    select t.*, st.ts, m.user_id_from, m.user_id_to from Tags as t join Mentions as m
        on t.status_id = m.status_id AND m.user_id_from != m.user_id_to
        left join Statuses as st on t.status_id = st.status_id;
</code>```

What is GTID consistency, and how can I fix the SQL statement to avoid the violation?

答:
CREATE TABLE ... SELECT is not safe for statement-based replication. When using row-based replication, this statement is actually logged as two separate events — one for the creation of the table, and another for the insertion of rows from the source table into the new table just created.

When this statement is executed within a transaction, it is possible in some cases for these two events to receive the same transaction identifier, which means that the transaction containing the inserts is skipped by the slave. Therefore, CREATE TABLE ... SELECT is not supported when using GTID-based replication.

Title: MySQL GTID consistency violation

Body:
I am trying to create a table from a select statement, and it give me a GTID consistency violation. [HY000][1786] Statement violates GTID consistency: CREATE TABLE ... SELECT.

create TABLE tags_mentions as
    select t.*, st.ts, m.user_id_from, m.user_id_to from Tags as t join Mentions as m
        on t.status_id = m.status_id AND m.user_id_from != m.user_id_to
        left join Statuses as st on t.status_id = st.status_id;

What is GTID consistency, and how can I fix the SQL statement to avoid the violation?

ContentLicense: CC BY-SA 4.0


问:
Where to add CPU Instructions Installing Tensorflow From Source?
I am trying to install Tensorflow from source because of a warning about CPU instructions (SSE, AVX...) not being installed when I installed with pip AND virtualenv:

W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.

So I'm trying to install Tensorflow from source so that these instructions can be compiled with Tensorflow.

Do I need to do anything aside from the instructions on the Tensorflow website to compile with these instructions? (./configure?)

If so, what do I need to do and how exactly do I do it?

In the installation when I have to install the pip package, the Tensorflow website says that for Linux, the command is :
sudo pip install /tmp/tensorflow_pkg/tensorflow-1.0.1-py2-none-any.whlit says that this command will differ based on the machine, what is the equivalent command for MacOS? How do I go about the Bazel wheelsteps?

Side Note: I've been told that there are a few ways I could do this with Bazel, but being unexperienced with Bazel and not too experienced on Terminal, I need clear steps on what to do?

OS Sierra (10.12.2)

答:
On OSX you can just do </p>

```<code>brew install tensor-flow
</code>```

<p>I believe. </p>

Body:
On OSX you can just do

brew install tensor-flow

I believe.


问:
How to combine 3 MySQL table inserts
So, I'm creating a user system in php. And of course users need to be inserted in my MySQL table. Now, I've got three tables that need to be filled:

- emails

---- id, email, subscriber

- addresses

---- id, street, street_number, zip_code, city, country, phone, btw_number, company

- users

---- id, username, password, salt, surname, name, joined, email_id, permissions_id, address_id, address_2_id

I could insert the email query, then select it's ID (auto inc) as id1. After that INSERT address and SELECT the id (auto inc) and then combine those 2 to INSERT in the users table. But is there a more quicker way so that I don't have to select the id each time after I've inserted the data?

答:
There is a mysql function for that.
You can do the First user-insert and After that you can use LAST_INSERT_ID().
that Seems to be exactly what you need.
For More informations you can go here </p>

<p>And here you got some code examples </p>

Title: How to combine 3 MySQL table inserts

Body:
There is a mysql function for that.
You can do the First user-insert and After that you can use LAST_INSERT_ID().
that Seems to be exactly what you need.
For More informations you can go here

And here you got some code examples


问:
WPF MVVM Navigate betweel views from the same hierarchical level
I am trying to make a small program mainly to learn MVVM. Its a small Book Library.

I have 4 views(and 4 viewmodels).
MainWindow is the parent view, where i display the other 3 view in a content control.

The other 3 child views are HomeView, BookManagingView, ReaderManagingView.

In HomeView, i display 2 ListViews(one with readers, one with books), and in the other 2 views i edit/add books or readers.

In my HomeView i also have  2 buttons. When i click the buttons i want to switch from the HomeView, to BookManagingView or ReaderManagingView.

If i am trying to switch to any of the Views from the MainWindow, it works.

What i am trying to do is to switch from the HomeView, to BookManagingView  or ReaderManagingView. How can i achieve that?

MainWindow:

```<code>    <Grid>
    <ContentControl Content="{Binding CurrentView}" Height="340" Width="500" />
    <Button x:Name="btnHomeView" Content="Home" Command="{Binding ChangeViewToHomeView, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="16,70,0,0" VerticalAlignment="Top" Width="75"/>
    <Button x:Name="btnBookManagingView" Content="Reader Options" Command="{Binding ChangeViewToReaderManagView,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="96,70,0,0" VerticalAlignment="Top" Width="92"/>
    <Button x:Name="btnReaderManagingView" Content="Books Options" Command="{Binding ChangeViewToBookManagView,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="193,70,0,0" VerticalAlignment="Top" Width="92"/>
</Grid>
</code>```

MainWindowVM:

```<code>    public class MainWindowViewModel : ViewModelBase
{
    private object currentView;
    private HomeViewModel homeVM;
    private ReaderManagingViewModel readerManagingVM;
    private BookManagingViewModel bookManagingVM;

    public MainWindowViewModel()
    {
        homeVM = new HomeViewModel();
        readerManagingVM = new ReaderManagingViewModel();
        bookManagingVM = new BookManagingViewModel();
        CurrentView = homeVM;

        ChangeViewToHomeView = new DefCommand(DisplayHomeView);
        ChangeViewToReaderManagView = new DefCommand(DisplayReaderManagingView);
        ChangeViewToBookManagView = new DefCommand(DisplayBookManagingView);
    }

    public DefCommand ChangeViewToHomeView { get; private  set; }
    public DefCommand ChangeViewToReaderManagView { get; private set; }
    public DefCommand ChangeViewToBookManagView { get; private set; }

    public object CurrentView
    {
        get { return currentView; }
        set { currentView = value; RaisePropertyChanged(); }
    }

    public void DisplayHomeView()
    {
        CurrentView = homeVM;
    }

    public void DisplayReaderManagingView()
    {
        CurrentView = readerManagingVM;
    }

    public void DisplayBookManagingView()
    {
        CurrentView = bookManagingVM;
    }
</code>```

HomeView:

```<code><Grid>
    <ListView x:Name="listviewReaders" ItemsSource="{Binding ReadersList}" SelectedItem="{Binding SelectedReader, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="160" Margin="25,23,315,40">
</code>```

...

```<code>    <ListView x:Name="listviewBooks" ItemsSource="{Binding BookList, Mode=OneWay}" SelectedItem="{Binding SelectedBook, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="160" Margin="316,50,24,117">
</code>```

...

```<code>    <Button x:Name="btnEditReader" Command="{Binding EditReaderSwitch, UpdateSourceTrigger=PropertyChanged}" Content="EditR" HorizontalAlignment="Left" Margin="316,305,0,0" VerticalAlignment="Top" Width="74"/>
    <Button x:Name="btnEditBook" Command="{Binding EditBookSwitch, UpdateSourceTrigger=PropertyChanged}" Content="EditB" HorizontalAlignment="Left" Margin="402,305,0,0" VerticalAlignment="Top" Width="74"/>
</Grid>
</code>```

HomeVM:

```<code> private Reader selectedReader;
    private Book selectedBook;
    private BookListFilter selectedFilter;

    private ObservableCollection<Book> bookList;
    private ObservableCollection<Reader> readerList;
    private IEnumerable<BookListFilter> bookLstItemSrc;

    public HomeViewModel()
    {
        SelectedReader = new Reader();
        SelectedBook = new Book();
        SelectedFilter = BookListFilter.AllBooks;

        BookDBDataContext rdb = new BookDBDataContext();

        ReadersList = new ObservableCollection<Reader>(rdb.Readers);
        GetBookList();

        EditReaderSwitch = new DefCommand(EditReaderInfo);
        EditBookSwitch = new DefCommand(EditBookInfo);
    }

    public DefCommand EditReaderSwitch { get; private set; }
    public DefCommand EditBookSwitch { get; private set; }
 private void EditBookInfo()
    {
        var tmpBook = new BookManagingViewModel(this);
        var tmpMwvm = new MainWindowViewModel();
        tmpMwvm.DisplayBookManagingView();
    }

    private void EditReaderInfo()
    {
        var tmpReader = new ReaderManagingViewModel(this);
        var tmpMwvm = new MainWindowViewModel();
        tmpMwvm.DisplayReaderManagingView();
    }
</code>```

Book & Reader ManagingViews have a bunch of textboxes and buttons for adding, deleting to/from database.

Book & Reader ManagingVM have methods for adding/deleting to/from database(right now they are empty and i will finish them if i manage to solve this problem first)

I have tried to navigate from HomeView to Book/ReaderManagingView with the EditBook/ReaderSwitch commands and EditBook/ReaderInfo() methods, but it doesnt work.

What am i doing wrong, and what should i do to fix it?

Sorry for the long post.

答:
You need to set the CurrentView property of the existing MainWindowViewModel instance. Right now you are creating a new instance of the class.

You could inject the HomeViewModel with a MainWindowViewModel:

```<code>private readonly MainWindowViewModel _x;
public HomeViewModel(MainWindowViewModel x)
{
    _x = x;
    SelectedReader = new Reader();
    ...
}

private void EditBookInfo()
{
    _x.DisplayBookManagingView();
}
</code>```

MainWindowViewModel:

```<code>public MainWindowViewModel()
{
    homeVM = new HomeViewModel(this);
}
</code>```

Body:
I am trying to make a small program mainly to learn MVVM. Its a small Book Library.

I have 4 views(and 4 viewmodels).
MainWindow is the parent view, where i display the other 3 view in a content control.

The other 3 child views are HomeView, BookManagingView, ReaderManagingView.

In HomeView, i display 2 ListViews(one with readers, one with books), and in the other 2 views i edit/add books or readers.

In my HomeView i also have  2 buttons. When i click the buttons i want to switch from the HomeView, to BookManagingView or ReaderManagingView.

If i am trying to switch to any of the Views from the MainWindow, it works.

What i am trying to do is to switch from the HomeView, to BookManagingView  or ReaderManagingView. How can i achieve that?

MainWindow:

    <Grid>
    <ContentControl Content="{Binding CurrentView}" Height="340" Width="500" />
    <Button x:Name="btnHomeView" Content="Home" Command="{Binding ChangeViewToHomeView, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="16,70,0,0" VerticalAlignment="Top" Width="75"/>
    <Button x:Name="btnBookManagingView" Content="Reader Options" Command="{Binding ChangeViewToReaderManagView,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="96,70,0,0" VerticalAlignment="Top" Width="92"/>
    <Button x:Name="btnReaderManagingView" Content="Books Options" Command="{Binding ChangeViewToBookManagView,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="193,70,0,0" VerticalAlignment="Top" Width="92"/>
</Grid>

MainWindowVM:

    public class MainWindowViewModel : ViewModelBase
{
    private object currentView;
    private HomeViewModel homeVM;
    private ReaderManagingViewModel readerManagingVM;
    private BookManagingViewModel bookManagingVM;

    public MainWindowViewModel()
    {
        homeVM = new HomeViewModel();
        readerManagingVM = new ReaderManagingViewModel();
        bookManagingVM = new BookManagingViewModel();
        CurrentView = homeVM;

        ChangeViewToHomeView = new DefCommand(DisplayHomeView);
        ChangeViewToReaderManagView = new DefCommand(DisplayReaderManagingView);
        ChangeViewToBookManagView = new DefCommand(DisplayBookManagingView);
    }

    public DefCommand ChangeViewToHomeView { get; private  set; }
    public DefCommand ChangeViewToReaderManagView { get; private set; }
    public DefCommand ChangeViewToBookManagView { get; private set; }

    public object CurrentView
    {
        get { return currentView; }
        set { currentView = value; RaisePropertyChanged(); }
    }

    public void DisplayHomeView()
    {
        CurrentView = homeVM;
    }

    public void DisplayReaderManagingView()
    {
        CurrentView = readerManagingVM;
    }

    public void DisplayBookManagingView()
    {
        CurrentView = bookManagingVM;
    }

HomeView:

<Grid>
    <ListView x:Name="listviewReaders" ItemsSource="{Binding ReadersList}" SelectedItem="{Binding SelectedReader, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="160" Margin="25,23,315,40">

...

    <ListView x:Name="listviewBooks" ItemsSource="{Binding BookList, Mode=OneWay}" SelectedItem="{Binding SelectedBook, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="160" Margin="316,50,24,117">

...

    <Button x:Name="btnEditReader" Command="{Binding EditReaderSwitch, UpdateSourceTrigger=PropertyChanged}" Content="EditR" HorizontalAlignment="Left" Margin="316,305,0,0" VerticalAlignment="Top" Width="74"/>
    <Button x:Name="btnEditBook" Command="{Binding EditBookSwitch, UpdateSourceTrigger=PropertyChanged}" Content="EditB" HorizontalAlignment="Left" Margin="402,305,0,0" VerticalAlignment="Top" Width="74"/>
</Grid>

HomeVM:

 private Reader selectedReader;
    private Book selectedBook;
    private BookListFilter selectedFilter;

    private ObservableCollection<Book> bookList;
    private ObservableCollection<Reader> readerList;
    private IEnumerable<BookListFilter> bookLstItemSrc;

    public HomeViewModel()
    {
        SelectedReader = new Reader();
        SelectedBook = new Book();
        SelectedFilter = BookListFilter.AllBooks;

        BookDBDataContext rdb = new BookDBDataContext();

        ReadersList = new ObservableCollection<Reader>(rdb.Readers);
        GetBookList();

        EditReaderSwitch = new DefCommand(EditReaderInfo);
        EditBookSwitch = new DefCommand(EditBookInfo);
    }

    public DefCommand EditReaderSwitch { get; private set; }
    public DefCommand EditBookSwitch { get; private set; }
 private void EditBookInfo()
    {
        var tmpBook = new BookManagingViewModel(this);
        var tmpMwvm = new MainWindowViewModel();
        tmpMwvm.DisplayBookManagingView();
    }

    private void EditReaderInfo()
    {
        var tmpReader = new ReaderManagingViewModel(this);
        var tmpMwvm = new MainWindowViewModel();
        tmpMwvm.DisplayReaderManagingView();
    }

Book & Reader ManagingViews have a bunch of textboxes and buttons for adding, deleting to/from database.

Book & Reader ManagingVM have methods for adding/deleting to/from database(right now they are empty and i will finish them if i manage to solve this problem first)

I have tried to navigate from HomeView to Book/ReaderManagingView with the EditBook/ReaderSwitch commands and EditBook/ReaderInfo() methods, but it doesnt work.

What am i doing wrong, and what should i do to fix it?

Sorry for the long post.

Body:
You need to set the CurrentView property of the existing MainWindowViewModel instance. Right now you are creating a new instance of the class.

You could inject the HomeViewModel with a MainWindowViewModel:

private readonly MainWindowViewModel _x;
public HomeViewModel(MainWindowViewModel x)
{
    _x = x;
    SelectedReader = new Reader();
    ...
}

private void EditBookInfo()
{
    _x.DisplayBookManagingView();
}

MainWindowViewModel:

public MainWindowViewModel()
{
    homeVM = new HomeViewModel(this);
}


问:
Java Android - Encrypt/Decrypt file contents
So at the moment I'm trying to write some encrypted text to a file and then be able to read that back in, decrypt it and display it to the user. I'm currently using AES-256 with PBKDF2 password derivation as I'd like to be able to use a user's password to encrypt/decrypt the files. The files are simple text files. The code I am currently using to encrypt some text and save it to a file is below. As far as I can tell, from having a look using adb, this works correctly.

```<code>FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
int iterationCount = 1000;
int keyLength = 256;
int saltLength = keyLength / 8;
SecureRandom randomGenerator = new SecureRandom();
byte[] salt = new byte[saltLength];
randomGenerator.nextBytes(salt);
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, iterationCount, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
randomGenerator.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] ciphertext = cipher.doFinal(defaultMessage.getBytes("UTF-8"));
String finalMessage = ciphertext.toString() + "]" + iv.toString() + "]" + salt.toString();
out.write(finalMessage.getBytes());
out.close();
</code>```

P.S The above is within a Try/Except.

The code below is what I'm currently trying to use to read in the file and then decrypt it, however, when I try to display the decrypted contents via the test view at the end, it does not show up.

```<code>FileInputStream fileInputStream = new FileInputStream(mypath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((fileContents = bufferedReader.readLine()) != null) {
    stringBuffer.append(fileContents + "\n");
}
String fileContentsString = stringBuffer.toString();
String[] fileContentsList = fileContentsString.split("]");
byte[] cipherText = fileContentsList[0].getBytes();
Toast.makeText(getApplicationContext(), fileContentsList[0], Toast.LENGTH_LONG).show();
byte[] iv = fileContentsList[1].getBytes();
byte[] salt = fileContentsList[2].getBytes();
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, 1000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherText);
String plainrStr = new String(plaintext , "UTF-8");
textEdit.setText(plainrStr);
</code>```

Hopefully someone can provide me with some assistance here. Again, the second code segment is within a Try/Except statement.

答:
You have multiple problems with your code.

Encryption

This code

```<code>String finalMessage = ciphertext.toString() + "]" + iv.toString() + "]" + salt.toString();
</code>```

does not produce a ciphertext. See here: Java: Syntax and meaning behind "[B@1ef9157"? Binary/Address?

The IV and salt have fixed sizes, so they can be placed in front of the ciphertext. After you've written the whole ciphertext, you need to use something like Base64 or Hex in order to get a String. Modern ciphers like AES produce ciphertexts that can contain bytes of any value which don't always constitute valid character encodings such as UTF-8. Strings are no containers for arbitrary byte[] contents.

```<code>ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(iv);
baos.write(salt);
baos.write(ciphertext);
String finalMessage = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
</code>```

But you don't need that at all, because you can directly write your ciphertext into the file:

```<code>out.write(iv);
out.write(salt);
out.write(ciphertext);
</code>```

Decryption

Don't use InputStreamReader, a BufferedReader and a StringBuffer for binary data. Otherwise, you'll corrupt your binary ciphertext.

You only need this:

```<code>byte[] iv = new byte[16];
byte[] salt = new byte[32];
byte[] ctChunk = new byte[8192]; // not for whole ciphertext, just a buffer

if (16 != fileInputStream.read(iv) || 32 != fileInputStream.read(salt)) {
    throw new Exception("IV or salt too short");
}

KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, 1000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);

int read;
ByteArrayOutputStream ctBaos = new ByteArrayOutputStream();
while((read = fileInputStream.read(ctChunk)) > 0) {
    ctBaos.write(cipher.update(cipherText, 0, read));
}
ctBaos.write(cipher.doFinal());

String plainrStr = new String(ctBaos.toByteArray(), "UTF-8");
textEdit.setText(plainrStr);
</code>```

This handles randomization properly but doesn't provide integrity. If you want to detect (malicious) manipulations of your ciphertexts (and generally you'll want that to prevent some attacks), you'd need to use an authenticated mode like GCM or EAX, or employ an encrypt-then-MAC scheme with a strong MAC like HMAC-SHA256.

Use a library like tozny/java-aes-crypto in order to use good defaults.

Body:
So at the moment I'm trying to write some encrypted text to a file and then be able to read that back in, decrypt it and display it to the user. I'm currently using AES-256 with PBKDF2 password derivation as I'd like to be able to use a user's password to encrypt/decrypt the files. The files are simple text files. The code I am currently using to encrypt some text and save it to a file is below. As far as I can tell, from having a look using adb, this works correctly.

FileOutputStream out = new FileOutputStream(mypath);
String defaultMessage = "Empty File";
int iterationCount = 1000;
int keyLength = 256;
int saltLength = keyLength / 8;
SecureRandom randomGenerator = new SecureRandom();
byte[] salt = new byte[saltLength];
randomGenerator.nextBytes(salt);
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, iterationCount, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
randomGenerator.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] ciphertext = cipher.doFinal(defaultMessage.getBytes("UTF-8"));
String finalMessage = ciphertext.toString() + "]" + iv.toString() + "]" + salt.toString();
out.write(finalMessage.getBytes());
out.close();

P.S The above is within a Try/Except.

The code below is what I'm currently trying to use to read in the file and then decrypt it, however, when I try to display the decrypted contents via the test view at the end, it does not show up.

FileInputStream fileInputStream = new FileInputStream(mypath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((fileContents = bufferedReader.readLine()) != null) {
    stringBuffer.append(fileContents + "\n");
}
String fileContentsString = stringBuffer.toString();
String[] fileContentsList = fileContentsString.split("]");
byte[] cipherText = fileContentsList[0].getBytes();
Toast.makeText(getApplicationContext(), fileContentsList[0], Toast.LENGTH_LONG).show();
byte[] iv = fileContentsList[1].getBytes();
byte[] salt = fileContentsList[2].getBytes();
KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, 1000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherText);
String plainrStr = new String(plaintext , "UTF-8");
textEdit.setText(plainrStr);

Hopefully someone can provide me with some assistance here. Again, the second code segment is within a Try/Except statement.

Body:
You have multiple problems with your code.

Encryption

This code

String finalMessage = ciphertext.toString() + "]" + iv.toString() + "]" + salt.toString();

does not produce a ciphertext. See here: Java: Syntax and meaning behind "[B@1ef9157"? Binary/Address?

The IV and salt have fixed sizes, so they can be placed in front of the ciphertext. After you've written the whole ciphertext, you need to use something like Base64 or Hex in order to get a String. Modern ciphers like AES produce ciphertexts that can contain bytes of any value which don't always constitute valid character encodings such as UTF-8. Strings are no containers for arbitrary byte[] contents.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(iv);
baos.write(salt);
baos.write(ciphertext);
String finalMessage = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);

But you don't need that at all, because you can directly write your ciphertext into the file:

out.write(iv);
out.write(salt);
out.write(ciphertext);

Decryption

Don't use InputStreamReader, a BufferedReader and a StringBuffer for binary data. Otherwise, you'll corrupt your binary ciphertext.

You only need this:

byte[] iv = new byte[16];
byte[] salt = new byte[32];
byte[] ctChunk = new byte[8192]; // not for whole ciphertext, just a buffer

if (16 != fileInputStream.read(iv) || 32 != fileInputStream.read(salt)) {
    throw new Exception("IV or salt too short");
}

KeySpec keySpec = new PBEKeySpec(submittedPassword.toCharArray(), salt, 1000, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);

int read;
ByteArrayOutputStream ctBaos = new ByteArrayOutputStream();
while((read = fileInputStream.read(ctChunk)) > 0) {
    ctBaos.write(cipher.update(cipherText, 0, read));
}
ctBaos.write(cipher.doFinal());

String plainrStr = new String(ctBaos.toByteArray(), "UTF-8");
textEdit.setText(plainrStr);

This handles randomization properly but doesn't provide integrity. If you want to detect (malicious) manipulations of your ciphertexts (and generally you'll want that to prevent some attacks), you'd need to use an authenticated mode like GCM or EAX, or employ an encrypt-then-MAC scheme with a strong MAC like HMAC-SHA256.

Use a library like tozny/java-aes-crypto in order to use good defaults.


问:
Auto Login using Python to my local internet page
I have cable internet which requires me to login though a web page. It's annoying how it resets every day at 8 and 12am. I wanted to write a python script which will automate the login process. I've read many StackOverflow solutions so far, nothing has worked. I have tried Requests, Twill, RoboBrowser etc.

Upon inspecting the page source I came across a doLogin() ajax script, which is triggered by login button. Here is the full page source.

following is one of my implementations which fails

```<code>import requests

# Fill in your details here to be posted to the login form.
payload = {
    'action': 'http://10.10.0.1/login',
    'actualusername': 'username',
    'actualpassword': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post("http://103.251.83.134/captiveportal/Default.aspx", data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    #r = s.get('http://www.google.com')
    #print r.text
</code>```

EDIT: Solution

I used Selenium WebDriver to fix this. Check answer.

答:
Your URL may be wrong. Looking at the source code it looks like the HTML form is posting data to the http://10.10.0.1/login page and then the doLogin() function is submitting data to Register.aspx?CheckCustomerStatus=1.

Also your payload includes the variable action and you're using a Session object, which I don't think is necessary.

I can't test it since it's a local login page I can't access, but I would try modifying your code to submit the login info to both pages using a simpler POST request

Body:
I have cable internet which requires me to login though a web page. It's annoying how it resets every day at 8 and 12am. I wanted to write a python script which will automate the login process. I've read many StackOverflow solutions so far, nothing has worked. I have tried Requests, Twill, RoboBrowser etc.

Upon inspecting the page source I came across a doLogin() ajax script, which is triggered by login button. Here is the full page source.

following is one of my implementations which fails

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'action': 'http://10.10.0.1/login',
    'actualusername': 'username',
    'actualpassword': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post("http://103.251.83.134/captiveportal/Default.aspx", data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    #r = s.get('http://www.google.com')
    #print r.text

EDIT: Solution

I used Selenium WebDriver to fix this. Check answer.


问:
Base URL of Mojolicious response
The HTTP::Response module has a base method that returns the base URL to use when converting relative URLs in the content of the message to absolute ones. It retrieves it from the message body (as a <base> element inside the HTML ), the HTTP header Content-Location (or the obsolete Content-Base), or the requested URL (from the most recent redirect, if any)

I can't see any way that Mojo::Message::Response provides the same information, and I don't want to have to code it myself if it's already in there somewhere

Can anyone help me out?

答:
Update   At this point I think that this framework doesn't have an equivalent of base from LWP

I am finding the content_location method in Mojo::Headers class. The Mojo::Message::Response inherits from the base Mojo::Message and Mojo::Headers seems to be picked up as well

Adding to the example from synopsis

```<code>my $res = Mojo::Message::Response->new;
$res->parse("HTTP/1.0 200 OK\x0d\x0a");
$res->parse("Content-Length: 12\x0d\x0a");
$res->parse("Content-Type: text/plain\x0d\x0a\x0d\x0a");
$res->parse('Hello World!');
say $res->code;
say $res->headers->content_type;
say $res->body;

say $res->headers->content_location // 'location not defined';  # /
$res->headers->content_location('set_some_location');
say $res->headers->content_location // 'location not defined';
</code>```

seems to work.  Is this suitable?  I can't readily find a real page to try with.

This doesn't scan the document content but only works with headers. The LWP sets headers from the document when producing the HTTP::Response object, as explained in the question and under base. In my tests (v5.16) Mojo::UA doesn't do that. I couldn't find a direct capability for this.

One way to obtain base URL would then be via DOM, for instance

```<code>use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $base_url = $ua->get($url)
    ->res->dom
    ->at('head')->at('base')->attr('href');
</code>```

The method dom is from Mojo::Message while base and attr are in Mojo::DOM.  Or

```<code>$dom->at('head > base[href]');
</code>```

which returns a hashref { href => URL }, while the first example returns the URL.

The at returns undef on failure so one first needs to check.

This is an additional, manual search through the content but at least it's focused in .

Update

I have looked over the source code of the mentioned components and their parent classes. This also brought up Mojo::Content whose subclass Single is returned by Mojo::Message::content, and Mojo::UserAgent::Transactor with its redirect method, that makes use of Mojo::URL.  However, they have different purposes. Altogether I found no help to directly unearth the base URL.

At this point I have to conclude that a direct capability like base in LWP isn't available here.

Title: Base URL of Mojolicious response

Body:
Update   At this point I think that this framework doesn't have an equivalent of base from LWP

I am finding the content_location method in Mojo::Headers class. The Mojo::Message::Response inherits from the base Mojo::Message and Mojo::Headers seems to be picked up as well

Adding to the example from synopsis

my $res = Mojo::Message::Response->new;
$res->parse("HTTP/1.0 200 OK\x0d\x0a");
$res->parse("Content-Length: 12\x0d\x0a");
$res->parse("Content-Type: text/plain\x0d\x0a\x0d\x0a");
$res->parse('Hello World!');
say $res->code;
say $res->headers->content_type;
say $res->body;

say $res->headers->content_location // 'location not defined';  # /
$res->headers->content_location('set_some_location');
say $res->headers->content_location // 'location not defined';

seems to work.  Is this suitable?  I can't readily find a real page to try with.

This doesn't scan the document content but only works with headers. The LWP sets headers from the document when producing the HTTP::Response object, as explained in the question and under base. In my tests (v5.16) Mojo::UA doesn't do that. I couldn't find a direct capability for this.

One way to obtain base URL would then be via DOM, for instance

use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $base_url = $ua->get($url)
    ->res->dom
    ->at('head')->at('base')->attr('href');

The method dom is from Mojo::Message while base and attr are in Mojo::DOM.  Or

$dom->at('head > base[href]');

which returns a hashref { href => URL }, while the first example returns the URL.

The at returns undef on failure so one first needs to check.

This is an additional, manual search through the content but at least it's focused in <head>.

Update

I have looked over the source code of the mentioned components and their parent classes. This also brought up Mojo::Content whose subclass Single is returned by Mojo::Message::content, and Mojo::UserAgent::Transactor with its redirect method, that makes use of Mojo::URL.  However, they have different purposes. Altogether I found no help to directly unearth the base URL.

At this point I have to conclude that a direct capability like base in LWP isn't available here.


问:
Dialog menu not responding to clicks
I used the MSVC++ wizard to create a win32 application. I added a new menu resource and added the typical 'File'->'Exit' etc.. Then I added it to the main dialog under the properties in msvc++. When I run the form it shows the menu on the form but if I click on File it doesn't even do the hover and it doesn't show the popup of Exit. Its almost like it's disabled. I really didn't think I needed to add any code. Any help is appreciated. Thanks.</p>

```<code>#include "stdafx.h"

#define MAX_LOADSTRING 100

struct _globals {
    HINSTANCE hInst;
    HWND      hWnd;
} g;

LRESULT CALLBACK DialogProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_     HINSTANCE hInstance,
                      _In_opt_ HINSTANCE hPrevInstance,
                      _In_     LPWSTR    lpCmdLine,
                      _In_     int       nCmdShow)
{

    InitCommonControls();

    g.hInst = hInstance;

    g.hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, (DLGPROC)DialogProc);
    if (g.hWnd == NULL) {
        GetLastError();
        return FALSE;
    }

    ShowWindow(g.hWnd, nCmdShow);
    UpdateWindow(g.hWnd);

    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ACCELLS));
    MSG msg;

    while (GetMessage(&msg, NULL, 0, 0)) {
        if (TranslateAccelerator(g.hWnd, hAccelTable, &msg))
            continue;
        if (IsDialogMessage(g.hWnd, &msg))
            continue;
        // process message
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
        break;
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            switch (wmId)
            {
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}
</code>```

答: Your DialogProc function looks more like a window procedure than a dialog procedure. Unlike window procedures, dalog procedures do not return LRESULT values, they return BOOL values, and they do not call DefWindowProc. There are some other differences as well.</p>

Title: Dialog menu not responding to clicks

Body:
I used the MSVC++ wizard to create a win32 application. I added a new menu resource and added the typical 'File'->'Exit' etc.. Then I added it to the main dialog under the properties in msvc++. When I run the form it shows the menu on the form but if I click on File it doesn't even do the hover and it doesn't show the popup of Exit. Its almost like it's disabled. I really didn't think I needed to add any code. Any help is appreciated. Thanks.

#include "stdafx.h"

#define MAX_LOADSTRING 100

struct _globals {
    HINSTANCE hInst;
    HWND      hWnd;
} g;

LRESULT CALLBACK DialogProc(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_     HINSTANCE hInstance,
                      _In_opt_ HINSTANCE hPrevInstance,
                      _In_     LPWSTR    lpCmdLine,
                      _In_     int       nCmdShow)
{

    InitCommonControls();

    g.hInst = hInstance;

    g.hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, (DLGPROC)DialogProc);
    if (g.hWnd == NULL) {
        GetLastError();
        return FALSE;
    }

    ShowWindow(g.hWnd, nCmdShow);
    UpdateWindow(g.hWnd);

    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ACCELLS));
    MSG msg;

    while (GetMessage(&msg, NULL, 0, 0)) {
        if (TranslateAccelerator(g.hWnd, hAccelTable, &msg))
            continue;
        if (IsDialogMessage(g.hWnd, &msg))
            continue;
        // process message
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

LRESULT CALLBACK DialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
        break;
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            switch (wmId)
            {
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}


问:
Find number of CPUs in linux kernel
I want detect number of CPUs in linux kernel and write a sys_call that find it.

cpuinfo_x86 gives features of one CPU and cpu_detect fills it but how to find number of CPUs to detect?

答: Personally, I cat /proc/cpuinfo to learn about the CPUs on a machine.</p>

Title: Find number of CPUs in linux kernel


问:
How to retain a space after floated :first-letter when the first letter is immediately followed by a space?
What's an elegant solution (i.e. without adding a   to the text), to introduce a space between the drop capital and the second letter, when the first word is a single letter?

I'm trying to add drop capitals to the first letter of a paragraph. The problem I am encountering is that it looks confusing if the first word is a 1 letter word, like I, which causes the space after to disappear.

An example is below:

p::first-letter {
  font-size: 150%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Some text.</p>

<p>
    I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text.
</p></code>```

The solution must keep the line height the same between lines in the same way that float: left does.

答:
This was a bit tricky to figure out, but change your CSS to this.

```<code>p::first-letter {
  font-size: 150%;
  vertical-align: text-top;
}
</code>```

The float: left; attribute was removing the spacing so if you replace it with vertical-align instead, it keeps the space and aligns the text to the top to achieve the desired effect.

Edit

Here is an example JSFiddle to show it working.

Body:
What's an elegant solution (i.e. without adding a   to the text), to introduce a space between the drop capital and the second letter, when the first word is a single letter?

I'm trying to add drop capitals to the first letter of a paragraph. The problem I am encountering is that it looks confusing if the first word is a 1 letter word, like I, which causes the space after to disappear.

An example is below:

p::first-letter {
  font-size: 150%;
  float: left;
}

Some text.

    I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text. I am some long text.

The solution must keep the line height the same between lines in the same way that float: left does.

Body:
This was a bit tricky to figure out, but change your CSS to this.

p::first-letter {
  font-size: 150%;
  vertical-align: text-top;
}

The float: left; attribute was removing the spacing so if you replace it with vertical-align instead, it keeps the space and aligns the text to the top to achieve the desired effect.

Edit

Here is an example JSFiddle to show it working.


问:
How can I place ships for Battleship game?
I have to create 10X10 board and 5 ships each has length of 2,3,3,4,5. Ships shouldn't overlap one another and they should be within the grid(10x10) and they should only be either vertical or horizontal.

I have been working on it for almost two days and the only thing I've been able to do so far is making 4 horizontal and overlapping ships length of 2,3,4,5 on a 10x10 board.

So the part I'm stuck on is as below:
1)I made ships to be within the grid but they are overlapping.
2)I can make 4 ships each length of 2,3,4,5 but can't do 3 to occur twice.
3)I can only do horizontal arrangement not vertical. I want the ship to be either vertical or horizontal randomly.

So the code I've written is as below:

{

```<code>matrix = zeros(10,10);
row = randi(size(matrix, 1),1,1); %row number
col = randi(size(matrix, 2),1,1); %column number

for i=2:5
        while  col(1,1)+i-1>10 % Checking if it is within grid
                row = randi(size(matrix, 1),1,1); %row number
                col = randi(size(matrix, 2),1,1); %column number
        end
            matrix(row,col:col+i-1)=i;
            row = randi(size(matrix, 1),1,1); %row number
            col = randi(size(matrix, 2),1,1); %column number

end
matrix
</code>```

}

I couldn't come up with any solutions. I really appreciate the help in advance.

答:
If I am not mistaken, you are having trouble with the approach and not the coding itself.

I would recommend you use a flag (ship ID) for each ship, and enter that ID on every spot occupied by the given ship in the 10x10 matrix (all other spots being 0 for ex).

Now to place a ship:

Randomly select a spot (x,y coordinate) from the free spots of the 10x10 matrix. Let that coordinate represent one end of the ship we are trying to place. Now the ship can only be placed in 4 possible ways (the 4 orientations up/down/left/right starting from this selected coordinate).
For each of the 4 possible ways, check (depending on the length of the ship) if:

a) the ship fits and does not go outside the 10x10 matrix

b) the ship does not overlap with an occupied spot

If both are satisfied for 1 or more of the 4 orientations, then pick one at random and place the ship. Otherwise, in a dummy 10x10 matrix, mark this unoccupied spot as a spot that cannot be used to place the current ship, and pick at random another unoccupied spot (which is still plausible, i.e. that is not marked impossible inside our dummy matrix).

Body:
I have to create 10X10 board and 5 ships each has length of 2,3,3,4,5. Ships shouldn't overlap one another and they should be within the grid(10x10) and they should only be either vertical or horizontal.

I have been working on it for almost two days and the only thing I've been able to do so far is making 4 horizontal and overlapping ships length of 2,3,4,5 on a 10x10 board.

So the part I'm stuck on is as below:
1)I made ships to be within the grid but they are overlapping.
2)I can make 4 ships each length of 2,3,4,5 but can't do 3 to occur twice.
3)I can only do horizontal arrangement not vertical. I want the ship to be either vertical or horizontal randomly.

So the code I've written is as below:

{

matrix = zeros(10,10);
row = randi(size(matrix, 1),1,1); %row number
col = randi(size(matrix, 2),1,1); %column number

for i=2:5
        while  col(1,1)+i-1>10 % Checking if it is within grid
                row = randi(size(matrix, 1),1,1); %row number
                col = randi(size(matrix, 2),1,1); %column number
        end
            matrix(row,col:col+i-1)=i;
            row = randi(size(matrix, 1),1,1); %row number
            col = randi(size(matrix, 2),1,1); %column number

end
matrix

}

I couldn't come up with any solutions. I really appreciate the help in advance.


问:
How to use c like structure in r
I am trans-code from matlab to r. I have code which is c-like structure in matlab.

```<code>for i = 1:m0
    Ent(i).connums = m0 - 1;        % number of neighbours
    Ent(i).con = [1:i-1 i+1:m0]';   % neighbour list
    Ent(i).H = [];
    Ent(i).L = [];
end
</code>```

Ent in code above is a c like structure array. I am trying to store a graph as adjacent list. In r, I was trying to use a list of lists. Say, Ent is a list of lists includes nodes.  Sublists in Ent is a list including a node detail information.

What I tried:

```<code>rm(list = setdiff(ls(), lsf.str()))
m0<-4
Ent <- list()

for (i in seq(1, m0))
{
    connums <- m0 - 1
    if (i + 1 > m0)
    {
        con <- seq(1,i-1)
    }
    else if (i - 1 < 1)
    {
        con <- c(seq(i+1,m0))
    }
    else
    {
        con <- c(seq(1,i-1), seq(i+1,m0))
    }

    H <- 0
    L <- 0
    Ent <- c(Ent, list(n=i, connums=connums, con=con, H=H, L=L))
}
Ent
is.list(Ent)
is.vector(Ent)
print(length(Ent))

for (f in Ent)
{
    print(f)
}
</code>```

the results:

```<code>> Ent
$n
[1] 1

$connums
[1] 3

$con
[1] 2 3 4

$H
[1] 0

$L
[1] 0

$n
[1] 2

$connums
[1] 3

$con
[1] 1 3 4

$H
[1] 0

$L
[1] 0

$n
[1] 3

$connums
[1] 3

$con
[1] 1 2 4

$H
[1] 0

$L
[1] 0

$n
[1] 4

$connums
[1] 3

$con
[1] 1 2 3

$H
[1] 0

$L
[1] 0

> is.list(Ent)
[1] TRUE
> is.vector(Ent)
[1] TRUE
> print(length(Ent))
[1] 20
> for (f in Ent)
+ {
+ print(f)
+ }
[1] 1
[1] 3
[1] 2 3 4
[1] 0
[1] 0
[1] 2
[1] 3
[1] 1 3 4
[1] 0
[1] 0
[1] 3
[1] 3
[1] 1 2 4
[1] 0
[1] 0
[1] 4
[1] 3
[1] 1 2 3
[1] 0
[1] 0
</code>```

Why the length of Ent is 20? The list seems be unlist.  My expected result might be sublists in a list. The length of Ent of sublist should be 4. I've read this solution and I still cant find my solution. Is it possible to store c like structure in r? how to do that? Any alternative solutions?

答:
The length of the list is 20 because of Ent <- c(Ent, list(n=i, connums=connums, con=con, H=H, L=L)). Here you concatenate the list to the previous list. You do not concatenate the specific elements of the lists to eachother. Thus if Ent has length 0, 5 gets added. This happens 4 times (since length(seq(1, m0)) = 4), and 4*5 = 20. If you want to append to a specific elemnt in Ent, you could try:

```<code>Ent$H = c(Ent$H, ...) # replace ... with values to append
Ent$L = c(Ent$L, ...)
</code>```

Title: How to use c like structure in r

Body:
I am trans-code from matlab to r. I have code which is c-like structure in matlab.

for i = 1:m0
    Ent(i).connums = m0 - 1;        % number of neighbours
    Ent(i).con = [1:i-1 i+1:m0]';   % neighbour list
    Ent(i).H = [];
    Ent(i).L = [];
end

Ent in code above is a c like structure array. I am trying to store a graph as adjacent list. In r, I was trying to use a list of lists. Say, Ent is a list of lists includes nodes.  Sublists in Ent is a list including a node detail information.

What I tried:

rm(list = setdiff(ls(), lsf.str()))
m0<-4
Ent <- list()

for (i in seq(1, m0))
{
    connums <- m0 - 1
    if (i + 1 > m0)
    {
        con <- seq(1,i-1)
    }
    else if (i - 1 < 1)
    {
        con <- c(seq(i+1,m0))
    }
    else
    {
        con <- c(seq(1,i-1), seq(i+1,m0))
    }

    H <- 0
    L <- 0
    Ent <- c(Ent, list(n=i, connums=connums, con=con, H=H, L=L))
}
Ent
is.list(Ent)
is.vector(Ent)
print(length(Ent))

for (f in Ent)
{
    print(f)
}

the results:

> Ent
$n
[1] 1

$connums
[1] 3

$con
[1] 2 3 4

$H
[1] 0

$L
[1] 0

$n
[1] 2

$connums
[1] 3

$con
[1] 1 3 4

$H
[1] 0

$L
[1] 0

$n
[1] 3

$connums
[1] 3

$con
[1] 1 2 4

$H
[1] 0

$L
[1] 0

$n
[1] 4

$connums
[1] 3

$con
[1] 1 2 3

$H
[1] 0

$L
[1] 0

> is.list(Ent)
[1] TRUE
> is.vector(Ent)
[1] TRUE
> print(length(Ent))
[1] 20
> for (f in Ent)
+ {
+ print(f)
+ }
[1] 1
[1] 3
[1] 2 3 4
[1] 0
[1] 0
[1] 2
[1] 3
[1] 1 3 4
[1] 0
[1] 0
[1] 3
[1] 3
[1] 1 2 4
[1] 0
[1] 0
[1] 4
[1] 3
[1] 1 2 3
[1] 0
[1] 0

Why the length of Ent is 20? The list seems be unlist.  My expected result might be sublists in a list. The length of Ent of sublist should be 4. I've read this solution and I still cant find my solution. Is it possible to store c like structure in r? how to do that? Any alternative solutions?

Body:
The length of the list is 20 because of Ent <- c(Ent, list(n=i, connums=connums, con=con, H=H, L=L)). Here you concatenate the list to the previous list. You do not concatenate the specific elements of the lists to eachother. Thus if Ent has length 0, 5 gets added. This happens 4 times (since length(seq(1, m0)) = 4), and 4*5 = 20. If you want to append to a specific elemnt in Ent, you could try:

Ent$H = c(Ent$H, ...) # replace ... with values to append
Ent$L = c(Ent$L, ...)


问:
Search string and grab all contents between 2 key words VB .NET
I've seen a bunch of examples on this online but I can't seem to find the one I'm looking for which uses Regex. I've seen many that use a loop and use a lot of lines of code but I'd like to see an example of Regex.

What I'm trying to create is an app that will connect too a webpage take the source search for a keyword once its found copy the text from that keyword to another keyword and save it into a string or to a textbox whatever.

I'm already using web request to get the information and put it into a string I just need to search the string for what I am looking for.

The reason for this app is to search webpage for an updated version of some software I'm using. I want to monitor for updates and the app to notify me when an update is available. Just a simple app but having issues searching for what I need.

```<code>For Example:
first words to search for: Server 64-bit
second words/characters to search for: </div>
</code>```

grab first words everything in between and last word saved into a string.

EDIT: The information I am trying to grab is this....

```<code>Server 64-bit
                  <span class="version">
          3.0.13.6
                      </span>
              </h3>
                    <div class="checksum">SHA256: c7eeb1937b0bce0b99e7c7e20de030a4b71adcaf09750481801cfa361433522f</div>
</code>```

答:
you can use the following code with RegEx to return the whole sentence including the two keywords you are providing

```<code>Dim str As String = "first words to search for: Server 64-bit second words/characters to search for: </div>"

str = str.Replace(vbNewLine,"|")
Dim strA As String = Regex.Match(str, "Server 64-bit(.*?)</div>", RegexOptions.Singleline).Value

Msgbox(strA)
</code>```

Or you can use the following expression to get only value between this two keywords:

```<code>Dim strA As String = Regex.Match(str, "(?<=Server 64-bit)(.*)(?=</div>)", RegexOptions.Singleline).Value
</code>```

Body:
I've seen a bunch of examples on this online but I can't seem to find the one I'm looking for which uses Regex. I've seen many that use a loop and use a lot of lines of code but I'd like to see an example of Regex.

What I'm trying to create is an app that will connect too a webpage take the source search for a keyword once its found copy the text from that keyword to another keyword and save it into a string or to a textbox whatever.

I'm already using web request to get the information and put it into a string I just need to search the string for what I am looking for.

The reason for this app is to search webpage for an updated version of some software I'm using. I want to monitor for updates and the app to notify me when an update is available. Just a simple app but having issues searching for what I need.

For Example:
first words to search for: Server 64-bit
second words/characters to search for:

grab first words everything in between and last word saved into a string.

EDIT: The information I am trying to grab is this....

Server 64-bit

          3.0.13.6

SHA256: c7eeb1937b0bce0b99e7c7e20de030a4b71adcaf09750481801cfa361433522f

Body:
you can use the following code with RegEx to return the whole sentence including the two keywords you are providing

Dim str As String = "first words to search for: Server 64-bit second words/characters to search for: </div>"

str = str.Replace(vbNewLine,"|")
Dim strA As String = Regex.Match(str, "Server 64-bit(.*?)</div>", RegexOptions.Singleline).Value

Msgbox(strA)

Or you can use the following expression to get only value between this two keywords:

Dim strA As String = Regex.Match(str, "(?<=Server 64-bit)(.*)(?=</div>)", RegexOptions.Singleline).Value


问:
How to issue a warning when package is required at runtime
How can I have emacs issue a warning when a package is required at runtime? I want to do something like cl does with its warning,

Warning: cl package required at runtime

I don't see the responsible piece of code in the cl library.

答:
You could try something like the following:

```<code>(when (assoc '(t byte-compile-file-form-require ((require '<mypkg>)) nil)
             (backtrace-frames))
  (message "Warning: package <mypkg> required at runtime"))
</code>```

Note that backtrace-frames is new in Emacs-26, so for earlier Emacsen, you'll need to reproduce it from backtrace-frame or some such.  E.g. for earlier Emacsen, you could use macroexp--backtrace:

```<code>(when (assoc '(t byte-compile-file-form-require (require '<mypkg>))
             (macroexp--backtrace))
  (message "Warning: package <mypkg> required at runtime"))
</code>```

Body:
You could try something like the following:

(when (assoc '(t byte-compile-file-form-require ((require '<mypkg>)) nil)
             (backtrace-frames))
  (message "Warning: package <mypkg> required at runtime"))

Note that backtrace-frames is new in Emacs-26, so for earlier Emacsen, you'll need to reproduce it from backtrace-frame or some such.  E.g. for earlier Emacsen, you could use macroexp--backtrace:

(when (assoc '(t byte-compile-file-form-require (require '<mypkg>))
             (macroexp--backtrace))
  (message "Warning: package <mypkg> required at runtime"))


问:
How to replace all occurrences of an array in JavaScript
If my array is gave me:
["ITEM_1", "ITEM_2", "ITEM_3"]

How I can remove the part ITEM_ to get only ["1", "2", "3"] ?

答:
You could do:

console.log(
  ["ITEM_1", "ITEM_2", "ITEM_3"].join().match(/\d+/g)
)```