问:
How do i fork a Github repo, make a change, then use it in my app?
Actually I know how to fork a repo (lets call it "originalModule") and have already made a small JS fix. However the owner of the npm module isnt maintaining it anymore so isn't doing anything with pull requests.

How can I simply take this forked version and then use it in my (react native) app? I want to be sure than if I ever delete the node_modules dir, when I run "yarn" or "npm install" that i dont get the originalModule and instead get the version from my forked Github location.

答:
npm is able to install a module from git repo: package.json.

If the change is generally enough, you can also consider to send a Pull Request though :)


来源: stackexchange

问:
Improve run time for GBM package
I am building a GBM model with rather large datasets. data.table is great for processing data. But when I run GBM model, it takes forever to finish. Looking at Activity Monitor (in Mac), I can see the process doesn't use up all memory, and doesn't max out processor.

Since GBM is single core, and I can't modify it to run on multicore, what are my options to improve my run time? Right now I am using Macbook Air with 4BG RAM and 1.7GHz i5.

I am not sure which of the following options would help performance the most: buying a (i) computer with bigger memory; (ii) get a more powerful chip (i7), or (iii) use Amazon AWS and install R there. How each of these will help?

Add sample code per Brandson's request:

```<code>library(gbm)

GBM_NTREES = 100
GBM_SHRINKAGE = 0.05
GBM_DEPTH = 4
GBM_MINOBS = 50

GBM_model <- gbm.fit(
  x = data[,-target] ,
  y = data[,target] ,
  #var.monotone = TRUE, #NN added
  distribution = "gaussian"
  ,n.trees = GBM_NTREES ,
  shrinkage = GBM_SHRINKAGE ,
  interaction.depth = GBM_DEPTH ,
  n.minobsinnode = GBM_MINOBS ,
  verbose = TRUE)
</code>```

答:
Maybe something worth considering is using the XGBoost library. According to the Github repo:

"XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way."

I also realize the original question is quite old, but maybe this will help someone out down the road.

ContentLicense: CC BY-SA 3.0

Title: Improve run time for GBM package

Body:
I am building a GBM model with rather large datasets. data.table is great for processing data. But when I run GBM model, it takes forever to finish. Looking at Activity Monitor (in Mac), I can see the process doesn't use up all memory, and doesn't max out processor.

Since GBM is single core, and I can't modify it to run on multicore, what are my options to improve my run time? Right now I am using Macbook Air with 4BG RAM and 1.7GHz i5.

I am not sure which of the following options would help performance the most: buying a (i) computer with bigger memory; (ii) get a more powerful chip (i7), or (iii) use Amazon AWS and install R there. How each of these will help?

Add sample code per Brandson's request:

library(gbm)

GBM_NTREES = 100
GBM_SHRINKAGE = 0.05
GBM_DEPTH = 4
GBM_MINOBS = 50

GBM_model <- gbm.fit(
  x = data[,-target] ,
  y = data[,target] ,
  #var.monotone = TRUE, #NN added
  distribution = "gaussian"
  ,n.trees = GBM_NTREES ,
  shrinkage = GBM_SHRINKAGE ,
  interaction.depth = GBM_DEPTH ,
  n.minobsinnode = GBM_MINOBS ,
  verbose = TRUE)


问:
Retrofit Cache Data for Offline Usage
I am using Retrofit library to parse and populate JSON data into RecyclerView.

But, Now I would like to know, How could I store same data for Offline usage, (even Internet is not available).

```<code>@Override
    public void onResume() {
        super.onResume();
        subscription = sampleAPI.getSamples()
                .cache()
                .timeout(5000, TimeUnit.MILLISECONDS)
                .retry(1)
                .doOnUnsubscribe(new Action0() {
                    @Override
                    public void call() {
                        Log.d(getClass().getName(), "Called unsubscribe OnPause()");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<SampleTypePojo>() {
                               @Override
                               public void call(SampleTypePojo jokesModel) {
                                   sampleList = jokesModel.getValue();

                                   displaySampleList(sampleList);

                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   Log.e(getClass().getName(), "ERROR: " + throwable.getMessage());
                                   throwable.printStackTrace();

                               }
                           }
                );
    }

    private void getSampleData() {
        if (sampleAPI == null) {
            sampleAPI = new RestAdapter.Builder()
                    .setEndpoint(Constants.BASE_URL)
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .build()
                    .create(SampleAPI.class);
        }
    }
</code>```

app level: build.gradle

```<code>dependencies {
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'io.reactivex:rxjava:1.0.4'
    compile 'io.reactivex:rxandroid:0.24.0'
}
</code>```

答:
Let’s first build a OKHTTP client with

a cache
an interceptor that checks for connectivity and if none asks for cached data:
Here’s the client.

```<code>OkHttpClient client = new OkHttpClient
  .Builder()
  .cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
  .addInterceptor(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      if (App.isNetworkAvailable()) {
        request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
      } else {
        request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
      }
      return chain.proceed(request);
    }
  })
  .build();
</code>```

We first create the cache object with 10 MB, getting the cache directory from a static Application context.

Then the Interceptor uses a utility method in my Application class to check for connectivity. If there is connectivity, we tell the request it can reuse the data for sixty seconds.

If there’s no connectivity, we ask to be given only (only-if-cached) ‘stale’ data upto 7 days ago.

Now make this OkHTTP client your client for Retrofit2 and you will be able to use your old cached data when the app goes offline

Title: Retrofit Cache Data for Offline Usage

Body:
I am using Retrofit library to parse and populate JSON data into RecyclerView.

But, Now I would like to know, How could I store same data for Offline usage, (even Internet is not available).

@Override
    public void onResume() {
        super.onResume();
        subscription = sampleAPI.getSamples()
                .cache()
                .timeout(5000, TimeUnit.MILLISECONDS)
                .retry(1)
                .doOnUnsubscribe(new Action0() {
                    @Override
                    public void call() {
                        Log.d(getClass().getName(), "Called unsubscribe OnPause()");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<SampleTypePojo>() {
                               @Override
                               public void call(SampleTypePojo jokesModel) {
                                   sampleList = jokesModel.getValue();

                                   displaySampleList(sampleList);

                               }
                           }, new Action1<Throwable>() {
                               @Override
                               public void call(Throwable throwable) {
                                   Log.e(getClass().getName(), "ERROR: " + throwable.getMessage());
                                   throwable.printStackTrace();

                               }
                           }
                );
    }

    private void getSampleData() {
        if (sampleAPI == null) {
            sampleAPI = new RestAdapter.Builder()
                    .setEndpoint(Constants.BASE_URL)
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .build()
                    .create(SampleAPI.class);
        }
    }

app level: build.gradle

dependencies {
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'io.reactivex:rxjava:1.0.4'
    compile 'io.reactivex:rxandroid:0.24.0'
}

Body:
Let’s first build a OKHTTP client with

a cache
an interceptor that checks for connectivity and if none asks for cached data:
Here’s the client.

OkHttpClient client = new OkHttpClient
  .Builder()
  .cache(new Cache(App.sApp.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
  .addInterceptor(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      if (App.isNetworkAvailable()) {
        request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
      } else {
        request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
      }
      return chain.proceed(request);
    }
  })
  .build();

We first create the cache object with 10 MB, getting the cache directory from a static Application context.

Then the Interceptor uses a utility method in my Application class to check for connectivity. If there is connectivity, we tell the request it can reuse the data for sixty seconds.

If there’s no connectivity, we ask to be given only (only-if-cached) ‘stale’ data upto 7 days ago.

Now make this OkHTTP client your client for Retrofit2 and you will be able to use your old cached data when the app goes offline


问:
I have error in inner join statement
I have an error in an inner join statement. I have 2 tables, input and input1.
In input field, I have the material id name
input1 I have another details on material.
When I use inner join, I have lerrorinfo.getdescription failed whith e_fail(0x80004005)

My code:

```<code>da = New OleDbDataAdapter("SELECT * FROM input1 inner join input on input1.id = input.id where [input.id] = '" & TextBox1.Text & "'", conn)
dt.Clear()
da.Fill(dt)
da.Dispose()
da = Nothing
DataGridView1.DataSource = dt
DataGridView1.Columns(0).HeaderText = "اسم المادة"
DataGridView1.Columns(1).HeaderText = "الكمية"
DataGridView1.Columns(2).HeaderText = "رقم المستند"
DataGridView1.Columns(3).HeaderText = "تاريخ المستند"
DataGridView1.Columns(4).HeaderText = "المستلم"
DataGridView1.Columns(5).HeaderText = "المسلم"
DataGridView1.Columns(6).HeaderText = "تاريخ التسليم"
DataGridView1.Columns(7).HeaderText = "رقم الموافقه "
DataGridView1.Columns(8).HeaderText = "تاريخ الموافقه"
DataGridView1.Columns(9).HeaderText = "ملاحظات الموافقه"
DataGridView1.Columns(10).HeaderText = "تاريخ الموافقه"
DataGridView1.Columns(11).HeaderText = "الملاحظات"
</code>```

答:
Been a while since I've written OleDB Sql (Access, etc.), but I'll take a stab at it.  You don't have your connection string here, so not sure of the version/brand of database.  I like to keep things simple so as not to run afoul of database idiosyncrasies, so here goes:

```<code>da = New OleDbDataAdapter("SELECT specificfield1, specificfield2 FROM input1, input where input1.id = input.id and [input.id] = '" & TextBox1.Text & "'", conn)
</code>```

I don't know what the structure of your two data tables are and you are using "Select *", if the tables are not identical , that may generate an error or (very) unexpected results.  Also, I like to be very specific as to what data I return and how the tables are linked.  I have found that what works with one database doesn't necessarily work with another.  So if you want data from both tables, alias the tables and be specific about what columns you want in the resultset from what table.  That's what I do anyway.  See if this example doesn't work for you.

R/
Prescott ...

Title: I have error in inner join statement

Body:
I have an error in an inner join statement. I have 2 tables, input and input1.
In input field, I have the material id name
input1 I have another details on material.
When I use inner join, I have lerrorinfo.getdescription failed whith e_fail(0x80004005)

My code:

da = New OleDbDataAdapter("SELECT * FROM input1 inner join input on input1.id = input.id where [input.id] = '" & TextBox1.Text & "'", conn)
dt.Clear()
da.Fill(dt)
da.Dispose()
da = Nothing
DataGridView1.DataSource = dt
DataGridView1.Columns(0).HeaderText = "اسم المادة"
DataGridView1.Columns(1).HeaderText = "الكمية"
DataGridView1.Columns(2).HeaderText = "رقم المستند"
DataGridView1.Columns(3).HeaderText = "تاريخ المستند"
DataGridView1.Columns(4).HeaderText = "المستلم"
DataGridView1.Columns(5).HeaderText = "المسلم"
DataGridView1.Columns(6).HeaderText = "تاريخ التسليم"
DataGridView1.Columns(7).HeaderText = "رقم الموافقه "
DataGridView1.Columns(8).HeaderText = "تاريخ الموافقه"
DataGridView1.Columns(9).HeaderText = "ملاحظات الموافقه"
DataGridView1.Columns(10).HeaderText = "تاريخ الموافقه"
DataGridView1.Columns(11).HeaderText = "الملاحظات"

Body:
Been a while since I've written OleDB Sql (Access, etc.), but I'll take a stab at it.  You don't have your connection string here, so not sure of the version/brand of database.  I like to keep things simple so as not to run afoul of database idiosyncrasies, so here goes:

da = New OleDbDataAdapter("SELECT specificfield1, specificfield2 FROM input1, input where input1.id = input.id and [input.id] = '" & TextBox1.Text & "'", conn)

I don't know what the structure of your two data tables are and you are using "Select *", if the tables are not identical , that may generate an error or (very) unexpected results.  Also, I like to be very specific as to what data I return and how the tables are linked.  I have found that what works with one database doesn't necessarily work with another.  So if you want data from both tables, alias the tables and be specific about what columns you want in the resultset from what table.  That's what I do anyway.  See if this example doesn't work for you.

R/
Prescott ...


问:
Which transformerClasses to use for complex Magnolia forms
I need to define a dialog, consisting of a several basic fields (text) nested in a switchable field, which itself is nested in a composite field, which itself is nested in a multivalue field.

```<code>Multivalue
  -> Composite
    -> Switchable
       -> textField1
       -> textField2
    -> generic textField (belonging to  composite, but not to switchable)
</code>```

However i cant manage to find the correct and working combination of transformerClasses, which I need to use. If using the corresponding DelegatingXXTransformer classes on multiValue and composite field, it nearly worked as expected, but those delegating transformers hide the required UI-controls (arrow down/up) buttons (see image).
But I need those controls.
I need the information which transformerClass to use for any element, to dont lose the ui controls, but still be able to handle nested fields with a higher level than two.
Anyway to solve this ?

relevant yaml-config:

```<code>form:
  tabs:
   - name: tabMain
     fields:
      - name: mainNav
        class: info.magnolia.ui.form.field.definition.MultiValueFieldDefinition
        transformerClass: info.magnolia.ui.form.field.transformer.multi.DelegatingMultiValueSubnodeTransformer
        field:
          name: composite
          class: info.magnolia.ui.form.field.definition.CompositeFieldDefinition
          transformerClass: info.magnolia.ui.form.field.transformer.composite.DelegatingCompositeFieldTransformer
          layout: vertical
          fields:
            - !include /module-ui/dialogs/common/link.yaml
            - !include /module-ui/common/link-title.yaml
            - !include /module-ui/dialogs/common/link-target.yaml
actions: !include /module-ui/dialogs/actions/default.yaml
</code>```

link.yaml:

```<code>name: link
class: info.magnolia.ui.form.field.definition.SwitchableFieldDefinition
transformerClass: info.magnolia.ui.form.field.transformer.composite.SwitchableTransformer
options:
 - name: internal
   value: internal
   selected: true
 - name: external
   value: external
   fields:
    - name: internal
      class: info.magnolia.ui.form.field.definition.LinkFieldDefinition
      appName: pages
      identifierToPathConverter:
        class:    info.magnolia.ui.form.field.converter.BaseIdentifierToPathConverter
 - name: external
   class: info.magnolia.ui.form.field.definition.TextFieldDefinition
   defaultValue: "http://"
</code>```

答:
Delegating transformers do not support ordering of the sub fields in multi field. This is due to the fact that they simply delegate persistence down to each individual field and have no control over how those fields will be persisted. Those sub fields then have no knowledge of the surrounding fields so they can't do anything either.

The only solution is to use other than delegating transformers or if none of the out of the box available transformers suit your needs, write your own.

Jan

Body:
I need to define a dialog, consisting of a several basic fields (text) nested in a switchable field, which itself is nested in a composite field, which itself is nested in a multivalue field.

Multivalue
  -> Composite
    -> Switchable
       -> textField1
       -> textField2
    -> generic textField (belonging to  composite, but not to switchable)

However i cant manage to find the correct and working combination of transformerClasses, which I need to use. If using the corresponding DelegatingXXTransformer classes on multiValue and composite field, it nearly worked as expected, but those delegating transformers hide the required UI-controls (arrow down/up) buttons (see image).
But I need those controls.
I need the information which transformerClass to use for any element, to dont lose the ui controls, but still be able to handle nested fields with a higher level than two.
Anyway to solve this ?

relevant yaml-config:

form:
  tabs:
   - name: tabMain
     fields:
      - name: mainNav
        class: info.magnolia.ui.form.field.definition.MultiValueFieldDefinition
        transformerClass: info.magnolia.ui.form.field.transformer.multi.DelegatingMultiValueSubnodeTransformer
        field:
          name: composite
          class: info.magnolia.ui.form.field.definition.CompositeFieldDefinition
          transformerClass: info.magnolia.ui.form.field.transformer.composite.DelegatingCompositeFieldTransformer
          layout: vertical
          fields:
            - !include /module-ui/dialogs/common/link.yaml
            - !include /module-ui/common/link-title.yaml
            - !include /module-ui/dialogs/common/link-target.yaml
actions: !include /module-ui/dialogs/actions/default.yaml

link.yaml:

name: link
class: info.magnolia.ui.form.field.definition.SwitchableFieldDefinition
transformerClass: info.magnolia.ui.form.field.transformer.composite.SwitchableTransformer
options:
 - name: internal
   value: internal
   selected: true
 - name: external
   value: external
   fields:
    - name: internal
      class: info.magnolia.ui.form.field.definition.LinkFieldDefinition
      appName: pages
      identifierToPathConverter:
        class:    info.magnolia.ui.form.field.converter.BaseIdentifierToPathConverter
 - name: external
   class: info.magnolia.ui.form.field.definition.TextFieldDefinition
   defaultValue: "http://"


问:
Issue in accesing a website hosting on weblogic server through IIS
We are facing issue while configuring IIS setup for weblogic servers.
Following are the environment details:

IIS8.5 on windows 2012 R2 standard 64x, wls_plugin_12.2.1.2.0 for weblogic server.

We have done the following steps:

Created a new web site on IIS.

Enabling the authentication settings.

Enabling the Directory browsing.

Added the script mapping in Handler mapping and set the path of iisproxy.dll as executor.

ISAPI filter setting for the iisproxy.dll

We are able to view the directory structure while accessing the IP and Port, but the request is not redirecting to the weblogic ip and port what we have configured in iisproxy.ini.

Is there any web.config or handler settings required to process the request?

答:
The issue is that we are using wls-Plugin12.2.1.2.0 whose iisproxy.dll is not working in IIS8.5 on windows 2012 R2 server. After using the lower version of the plugin, able to access the web logic instance through proxy the IIS.

After that we are able to view the login page of web logic instance but not able to login to the application as it through s "404 Not found error". For this we have to change the handler mapping settings --> Request restrictions --> Mapping --> uncheck the invoke handle, restart the iis application and try browsing again. You will be able to login to web logic applications.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to map values in a matrix to colours in MATLAB
I have been trying to get an image from a matrix. Initially I had converted the matrix to a grey-scale image with 5 levels. I want to know if the same thing can be done to make the grey-scale image a colors one, i.e. say I have a value 2.2 and I need it to be in dark blue color, is there any inbuilt function to map values this way and also is it possible to map all the 5 levels to different colours?

Consider the following to be my matrix

```<code>   x = [ 2.2 2.2 2.2 2.6
         2.2 2.3 2.4 2.5
         2.3 2.7 2.5 2.2
         2.6 2.2 2.2 2.2]
</code>```

And I need to map the levels as follows,such that when I convert this into an image , I should be getting the colors in my output image.

```<code>                 2.2--> Dark blue
                 2.3--> Blue
                 2.4--> Green
                 2.5--> Yellow
                 2.6--> Orange
                 2.7--> Red
</code>```

How do I do it? Please help..Thanks!!

答:
You can change the ColorOrder of the axes you plot in and then use imagesc. If you don't know in advance how many different values you x matrix will have, you have to create your colormap a bit more dynamic than the solution below.

```<code>% Create your own "colormap"
imgColor = [...
    0 0 0.5; ... % Dark blue
    0 0 1;   ... % Blue
    0 0.8 0; ... % Green
    1 1 0;   ... % Yellow
    1 0.5 0; ... % Orange
    1 0 0    ... % Red
    ];

% Create an axes and set your color order
a = axes;
a.ColorOrder = imgColor;
% Draw image
imagesc(x)
</code>```

You could also try to play around with the colormap editor to change the colors. To open, just type:

```<code>colormapeditor
</code>```

Body:
I have been trying to get an image from a matrix. Initially I had converted the matrix to a grey-scale image with 5 levels. I want to know if the same thing can be done to make the grey-scale image a colors one, i.e. say I have a value 2.2 and I need it to be in dark blue color, is there any inbuilt function to map values this way and also is it possible to map all the 5 levels to different colours?

Consider the following to be my matrix

   x = [ 2.2 2.2 2.2 2.6
         2.2 2.3 2.4 2.5
         2.3 2.7 2.5 2.2
         2.6 2.2 2.2 2.2]

And I need to map the levels as follows,such that when I convert this into an image , I should be getting the colors in my output image.

                 2.2--> Dark blue
                 2.3--> Blue
                 2.4--> Green
                 2.5--> Yellow
                 2.6--> Orange
                 2.7--> Red

How do I do it? Please help..Thanks!!

Body:
You can change the ColorOrder of the axes you plot in and then use imagesc. If you don't know in advance how many different values you x matrix will have, you have to create your colormap a bit more dynamic than the solution below.

% Create your own "colormap"
imgColor = [...
    0 0 0.5; ... % Dark blue
    0 0 1;   ... % Blue
    0 0.8 0; ... % Green
    1 1 0;   ... % Yellow
    1 0.5 0; ... % Orange
    1 0 0    ... % Red
    ];

% Create an axes and set your color order
a = axes;
a.ColorOrder = imgColor;
% Draw image
imagesc(x)

You could also try to play around with the colormap editor to change the colors. To open, just type:

colormapeditor


问:
Android: conerting Image into byteArray
In my project I have an bitmap image. I need to convert this picture to byteArray in order to manipulate some bytes and after that save it as image.

with this code image = BitmapFactory.decodeResource(context.getResources(), R.drawable.tasnim); I have acces to width and height but how can I have access to bytes of this image?

Thanks

答:
I'm assuming the OP wants to manipulate the pixels, not the header information of the Image...

Assuming your image is a Bitmap

```<code>int w = image.getWidth(), h = image.getHeight();
int[] rgbStream = new int[w * h];
image.getPixels(rgbStream, 0, w, 0, 0, w, h);
</code>```

Of course, this gets you Pixel values as Integers...But you can always convert them again.

```<code>    int t = w * h;

    for (int i = 0; i < t; i++) {
        pixel = rgbStream[i];  //get pixel value (ARGB)
        int A = (pixel >> 24) & 0xFF; //Isolate Alpha value...
        int R = (pixel >> 16) & 0xFF; //Isolate Red Channel value...
        int G = (pixel >> 8) & 0xFF; //Isolate Green Channel value...
        int B = pixel & 0xFF; //Isolate Blue Channel value...
                       //NOTE, A,R,G,B can be cast as bytes...

    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Android: conerting Image into byteArray

Body:
I'm assuming the OP wants to manipulate the pixels, not the header information of the Image...

Assuming your image is a Bitmap

int w = image.getWidth(), h = image.getHeight();
int[] rgbStream = new int[w * h];
image.getPixels(rgbStream, 0, w, 0, 0, w, h);

Of course, this gets you Pixel values as Integers...But you can always convert them again.

    int t = w * h;

    for (int i = 0; i < t; i++) {
        pixel = rgbStream[i];  //get pixel value (ARGB)
        int A = (pixel >> 24) & 0xFF; //Isolate Alpha value...
        int R = (pixel >> 16) & 0xFF; //Isolate Red Channel value...
        int G = (pixel >> 8) & 0xFF; //Isolate Green Channel value...
        int B = pixel & 0xFF; //Isolate Blue Channel value...
                       //NOTE, A,R,G,B can be cast as bytes...

    }


问:
OneSignal Push Notification ClickEvent show empty values Windows phone 8.1 C#
I'm working on One Signal Push Notifications for windows phone 8.1. Notification works fine. but when I click on notification then the message display empty value. While when application is ON then message display in event.
how can I get the notification text to save in my notification screen?

My App.Xaml.cs Function code is here.

OnLaunched Event:

```<code> OneSignal.Init("32cdee4b-7838-4b6c-a024-ae25cecb2234", e);
 OneSignal.Init("32cdee4b-7838-4b6c-a024-ae25cecb2234", e, notificationOpened);
</code>```

Here is notificationOpened Function Code:

```<code>  private async void notificationOpened(string message, IDictionary<string, string> additionalData, bool isActive)
    {

        if (message != null && message != "")
        {
            DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Creating object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs

            try
            {
                Db_Helper.Insert(new MessagesClass(message));

            }
            catch
            {
                MessageDialog messageDialog = new MessageDialog("There is an error while saving this details. Please try again later!");//Text should not be empty
                await messageDialog.ShowAsync();

            }

        }
        else
        {
            //Here I have check for empty value
            settingsClass.SaveSetting("NotiClick", "MoveToMeldingen");

        }
</code>```

When application is on active state then I gets the message but when application is in background and notification receives in notification tray then y clicking on this I gets empty message string.
Please help me to get rid of this issue.
Thank you!

答: You first need to debug and check if it really receives the message in notificatonOpened method. It might be due to the message not being recived properly by it while in background.</p>

Body:
I'm working on One Signal Push Notifications for windows phone 8.1. Notification works fine. but when I click on notification then the message display empty value. While when application is ON then message display in event.
how can I get the notification text to save in my notification screen?

My App.Xaml.cs Function code is here.

OnLaunched Event:

 OneSignal.Init("32cdee4b-7838-4b6c-a024-ae25cecb2234", e);
 OneSignal.Init("32cdee4b-7838-4b6c-a024-ae25cecb2234", e, notificationOpened);

Here is notificationOpened Function Code:

  private async void notificationOpened(string message, IDictionary<string, string> additionalData, bool isActive)
    {

        if (message != null && message != "")
        {
            DatabaseHelperClass Db_Helper = new DatabaseHelperClass();//Creating object for DatabaseHelperClass.cs from ViewModel/DatabaseHelperClass.cs

            try
            {
                Db_Helper.Insert(new MessagesClass(message));

            }
            catch
            {
                MessageDialog messageDialog = new MessageDialog("There is an error while saving this details. Please try again later!");//Text should not be empty
                await messageDialog.ShowAsync();

            }

        }
        else
        {
            //Here I have check for empty value
            settingsClass.SaveSetting("NotiClick", "MoveToMeldingen");

        }

When application is on active state then I gets the message but when application is in background and notification receives in notification tray then y clicking on this I gets empty message string.
Please help me to get rid of this issue.
Thank you!


问:
Jump directly to certain parts of a function
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

```<code>#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}
</code>```

答:
Here's an alternate solution that doesn't depend on stack manipulation. The fundamental 'trick' is that the program provides its own implementation of printf() instead of using the standard library's.

Tested on gcc (Mingw, Linux x86 and Linux x64) and MSVC:

```<code>#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
    return;
}

void putstr( char const* s)
{
    for (;*s;++s) {
        putchar(*s);
    }
}

int printf(char const* fmt, ...)
{
    static char const* pushed_fmt = 0;

    if (*fmt == '\n') {
        putstr(fmt);
        return 0;
    }

    if (pushed_fmt == 0) {
        pushed_fmt = fmt;
        return 0;
    }

    putstr(fmt);
    putstr(pushed_fmt);

    return 0;
}
</code>```

Body:
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}

Body:
Here's an alternate solution that doesn't depend on stack manipulation. The fundamental 'trick' is that the program provides its own implementation of printf() instead of using the standard library's.

Tested on gcc (Mingw, Linux x86 and Linux x64) and MSVC:

#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
    return;
}

void putstr( char const* s)
{
    for (;*s;++s) {
        putchar(*s);
    }
}

int printf(char const* fmt, ...)
{
    static char const* pushed_fmt = 0;

    if (*fmt == '\n') {
        putstr(fmt);
        return 0;
    }

    if (pushed_fmt == 0) {
        pushed_fmt = fmt;
        return 0;
    }

    putstr(fmt);
    putstr(pushed_fmt);

    return 0;
}


问:
Applying fminunc to costFunction for Logistic Regression
I have met a problem when practicing coding logistic regression for machine learning course using a Mac version of Matlab_R2016a.

First,this is my code of costFunction which works fine with returning the cost and the gradient:

```<code>function [J,grad] = costFunction(X, y, theta)

    % Initialize some useful values
    h=sigmoid(X*theta);
    m = length(y); % number of training examples

    grad = m^(-1) * ((h-y)'*X)';
    J=sum(-y.*log(h)-(1-y).*log(1-h))/m;

end
</code>```

And this is the sigmoid function:

```<code>function h=sigmoid(z)

h = (1 + exp(-1 *z)).^(-1);

end
</code>```

Finally, I applied costFunction to fminunc with the form like this in the following picture(enter image description here). But, the strange thing was that it said my Inner matrix dimensions of X*theta in costFunction was wrong(It was fine before). I appreciate some solutions or ideas from you.

答:
Please control the order of the parameters in your anonymous function call inside fminunc.

In your function "costFunction" they are X,y,theta;
when you call fminunc(@(t) costFunction(t,X,y) ...) you have X and y as second and third parameter, respectively.

Hope this helps.

Body:
I have met a problem when practicing coding logistic regression for machine learning course using a Mac version of Matlab_R2016a.

First,this is my code of costFunction which works fine with returning the cost and the gradient:

function [J,grad] = costFunction(X, y, theta)

    % Initialize some useful values
    h=sigmoid(X*theta);
    m = length(y); % number of training examples

    grad = m^(-1) * ((h-y)'*X)';
    J=sum(-y.*log(h)-(1-y).*log(1-h))/m;

end

And this is the sigmoid function:

function h=sigmoid(z)

h = (1 + exp(-1 *z)).^(-1);

end

Finally, I applied costFunction to fminunc with the form like this in the following picture(enter image description here). But, the strange thing was that it said my Inner matrix dimensions of X*theta in costFunction was wrong(It was fine before). I appreciate some solutions or ideas from you.


问:
With Freebase Suggest how do I filter one field based on the selection of another
If I'm using Freebase Suggest ( http://wiki.freebase.com/wiki/Freebase_Suggest ) and I have one field that selects either Country or State, how do I then have another field "City" filter to display only cities in that Country or State?

Also, if someone selected as their State "New York" ("/en/new_york"), how would I query to find out the "Country" is "United States of America"?

答:
Unfortunately, this isn't as easy as you'd hope. You can look at the /location/location/contained_by property of the city and see if /en/united_states (or whatever you're looking for) is included in there. However, this won't give you all the answers you're hoping for - for example, if you look at /en/new_york you'll see that it's contained by /en/new_york_state, but there's no direct link to /en/united_states.

You can look at /en/new_york_state and find that's contained by /en/united_states, but there's no easy way to do that kind of "transitive" search in Suggest.

The only thing you can do is to use the "included" MQL extension, but that relies on correct geodata being present in Freebase.

With regards to New York (State) being part of the United States, just look at the /location/administrative_division/country.

Hope this helps!


问:
SSL Client-Server with self signed certificate imported at runtime fails on handshake
EDIT: I fixed the code. See my answer for explanation.

I am trying to create a android app that sends data to a server using a SSLSocket. The certificate is self signed and I am trying add it in the server KeyManager and client TrustManager using SSLContext, as per instructions I found on other threads.

However both the client and server return exceptions when I try to send data.

Please keep in mind that this is my first time dealing with SSL connections. I created and singed the 'server.crt' certificate using the Java keytool.

client exception

```<code>javax.net.ssl.SSLHandshakeException: Handshake failed
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:390)
at com.android.org.conscrypt.OpenSSLSocketImpl.waitForHandshake(OpenSSLSocketImpl.java:623)
at com.android.org.conscrypt.OpenSSLSocketImpl.getOutputStream(OpenSSLSocketImpl.java:609)
...
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73c6ac00: Failure in SSL library, usually a protocol error
</code>```

server exception

```<code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: no cipher suites in common
...
at java.io.InputStream.read(InputStream.java:101)
</code>```

FIXED client code (running on android)

```<code>AssetManager assetManager = getAssets();
InputStream keyStoreInputStream = assetManager.open("keystore.bks");

KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null,null);
keyStore.load(keyStoreInputStream, KEY_PASSWORD);

TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

SSLSocketFactory sslsocketfactory = sslContext.getSocketFactory();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.212", 4444);

InputStream inputStream = assetManager.open(MainActivity.FILE_NAME);

OutputStream outputStream = sslsocket.getOutputStream();

int count;
byte[] buffer = new byte[12 * 1024];
while ((count = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, count);
}
</code>```

FIXED server code (running on windows)

```<code>FileInputStream keyStoreInputStream = new FileInputStream(KEYSTORE_PATH);

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.load(keyStoreInputStream, KEY_PASSWORD);

KeyManagerFactory keyManagerFactory =
    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, KEY_PASSWORD);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);

SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
SSLServerSocket sslServerSocket =
    (SSLServerSocket) sslServerSocketFactory.createServerSocket(4444);

while (true) {
    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();

    InputStream inputStream = sslSocket.getInputStream();

    FileOutputStream outputStream = new FileOutputStream(OUTPUT_PATH,false);

    byte[] bytes = new byte[12 * 1024];
    int count;
    while ((count = inputStream.read(bytes)) > 0) {
        outputStream.write(bytes, 0, count);
    }
}
</code>```

答:
For testing purposes, I needed to spin up an HTTPS server. As the cert didn't really matter, I needed to create one. Why leave the JVM and use keytool when we can do it all in java.

This requires BouncyCastle.

```<code>static SSLContext createSSLContext() throws Exception {
    final KeyStore ks = createSelfSignedKeyStore();
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, new char[0]);

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);

    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return sslContext;
}

private static KeyStore createSelfSignedKeyStore() throws Exception {
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);

    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    final KeyPair keyPair = keyGen.generateKeyPair();
    final Certificate selfSignedCert = generate(InetAddress.getLocalHost().getCanonicalHostName(), keyPair);

    ks.setCertificateEntry("alias.cert", selfSignedCert);
    ks.setKeyEntry("alias.key", keyPair.getPrivate(), new char[0], new Certificate[] { selfSignedCert });
    return ks;
}

private static Certificate generate(final String fqdn, final KeyPair keypair) throws Exception {
    final Instant now = Instant.now();
    final Date notBefore = Date.from(now.minus(24, ChronoUnit.HOURS));
    final Date notAfter = Date.from(now.plus(24, ChronoUnit.HOURS));
    final ContentSigner selfSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
        .build(keypair.getPrivate());
    final X500Name owner = new X500Name("CN=" + fqdn);
    final X509CertificateHolder certHolder = new JcaX509v3CertificateBuilder(
        /*issuer*/owner,
        /*serial*/new BigInteger(64, new SecureRandom()),
        /*cert start*/notBefore,
        /*cert end*/notAfter,
        /*subject*/owner,
        /*subject public key*/keypair.getPublic())
        .build(selfSigner);
    final X509Certificate selfSignedCert = new JcaX509CertificateConverter()
        .getCertificate(certHolder);
    selfSignedCert.verify(keypair.getPublic()); // Certificate is good!
    return selfSignedCert;
}
</code>```

Body:
EDIT: I fixed the code. See my answer for explanation.

I am trying to create a android app that sends data to a server using a SSLSocket. The certificate is self signed and I am trying add it in the server KeyManager and client TrustManager using SSLContext, as per instructions I found on other threads.

However both the client and server return exceptions when I try to send data.

Please keep in mind that this is my first time dealing with SSL connections. I created and singed the 'server.crt' certificate using the Java keytool.

client exception

javax.net.ssl.SSLHandshakeException: Handshake failed
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:390)
at com.android.org.conscrypt.OpenSSLSocketImpl.waitForHandshake(OpenSSLSocketImpl.java:623)
at com.android.org.conscrypt.OpenSSLSocketImpl.getOutputStream(OpenSSLSocketImpl.java:609)
...
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73c6ac00: Failure in SSL library, usually a protocol error

server exception

Exception in thread "main" javax.net.ssl.SSLHandshakeException: no cipher suites in common
...
at java.io.InputStream.read(InputStream.java:101)

FIXED client code (running on android)

AssetManager assetManager = getAssets();
InputStream keyStoreInputStream = assetManager.open("keystore.bks");

KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null,null);
keyStore.load(keyStoreInputStream, KEY_PASSWORD);

TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

SSLSocketFactory sslsocketfactory = sslContext.getSocketFactory();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("192.168.1.212", 4444);

InputStream inputStream = assetManager.open(MainActivity.FILE_NAME);

OutputStream outputStream = sslsocket.getOutputStream();

int count;
byte[] buffer = new byte[12 * 1024];
while ((count = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, count);
}

FIXED server code (running on windows)

FileInputStream keyStoreInputStream = new FileInputStream(KEYSTORE_PATH);

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.load(keyStoreInputStream, KEY_PASSWORD);

KeyManagerFactory keyManagerFactory =
    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, KEY_PASSWORD);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);

SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
SSLServerSocket sslServerSocket =
    (SSLServerSocket) sslServerSocketFactory.createServerSocket(4444);

while (true) {
    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();

    InputStream inputStream = sslSocket.getInputStream();

    FileOutputStream outputStream = new FileOutputStream(OUTPUT_PATH,false);

    byte[] bytes = new byte[12 * 1024];
    int count;
    while ((count = inputStream.read(bytes)) > 0) {
        outputStream.write(bytes, 0, count);
    }
}

Body:
For testing purposes, I needed to spin up an HTTPS server. As the cert didn't really matter, I needed to create one. Why leave the JVM and use keytool when we can do it all in java.

This requires BouncyCastle.

static SSLContext createSSLContext() throws Exception {
    final KeyStore ks = createSelfSignedKeyStore();
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, new char[0]);

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);

    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return sslContext;
}

private static KeyStore createSelfSignedKeyStore() throws Exception {
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);

    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    final KeyPair keyPair = keyGen.generateKeyPair();
    final Certificate selfSignedCert = generate(InetAddress.getLocalHost().getCanonicalHostName(), keyPair);

    ks.setCertificateEntry("alias.cert", selfSignedCert);
    ks.setKeyEntry("alias.key", keyPair.getPrivate(), new char[0], new Certificate[] { selfSignedCert });
    return ks;
}

private static Certificate generate(final String fqdn, final KeyPair keypair) throws Exception {
    final Instant now = Instant.now();
    final Date notBefore = Date.from(now.minus(24, ChronoUnit.HOURS));
    final Date notAfter = Date.from(now.plus(24, ChronoUnit.HOURS));
    final ContentSigner selfSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
        .build(keypair.getPrivate());
    final X500Name owner = new X500Name("CN=" + fqdn);
    final X509CertificateHolder certHolder = new JcaX509v3CertificateBuilder(
        /*issuer*/owner,
        /*serial*/new BigInteger(64, new SecureRandom()),
        /*cert start*/notBefore,
        /*cert end*/notAfter,
        /*subject*/owner,
        /*subject public key*/keypair.getPublic())
        .build(selfSigner);
    final X509Certificate selfSignedCert = new JcaX509CertificateConverter()
        .getCertificate(certHolder);
    selfSignedCert.verify(keypair.getPublic()); // Certificate is good!
    return selfSignedCert;
}


答:
I think "date" as the column name is a bad idea.
Try quoting them with double quote.</p>

Title: Extracting rows between 2 dates using SQL

Body:
id    date       temp       prcp
1   2015-01-01  -27.18      0
1   2015-01-02  -25.9       1.03
1   2015-01-03  -17.89      9.44
1   2015-01-04  -17.89      9.44
1   2015-01-05  -17.89      9.44

SELECT * FROM tbl WHERE id=1 and date between '2015-01-03' and '2015-01-05'

How do I fix the SQL query above? I am trying to extract all rows between the 2 dates '2015-01-03' and '2015-01-05'


问:
C++ Read file into vectors
I'm having trouble figuring out how to read a file line by line into different data type vectors. Is there a way to do this with inFile >> ? My code is below. Thanks in advance!</p>

```<code>void fileOpen()
{
    fstream inFile;
    inFile.open(userFile);

    // Check if file open successful -- if so, process

    if (!inFile.is_open()) {cout << "File could not be opened.";}
    else
    {
        cout << "File is open.\n";

        string firstLine;
        string line;

        vector<char> printMethod;
        vector<string> shirtColor;
        vector<string> orderID;
        vector<string> region;
        vector<int> charCount;
        vector<int> numMedium;
        vector<int> numLarge;
        vector<int> numXL;

        getline(inFile, firstLine); // get column headings out of the way
        cout << firstLine << endl << endl;

        while(inFile.good()) // while we are not at the end of the file, process
        {
            while(getline(inFile, line)) // get each line of the file separately
            {
               for (int i = 1; i < 50; i++)
               {
                  inFile >> date >> printMethod.at(i);
                  cout << date << printMethod.at(i) << endl;
               }

            }
        }

    }
}
</code>```

答:
Before you use vector.at(i) in your case you should be sure that your vector is long enough cause at will generate out of range exception. As I can see from your code your vector printMethod contains no more than 50 elements so you can resize vector printMethod before use e.g.

```<code>vector<char> printMethod(50);
</code>```

or

```<code>vector<char> printMethod;
printMethod.resize(50);
</code>```

If you're planning to use a variable number of elements more than 50 you should use push_back method like @Phil1970 recommended e.g.

```<code>char other_data;
inFile >> date >> other_data;
printMethod.push_back(other_data);
</code>```

Title: C++ Read file into vectors

Body:
I'm having trouble figuring out how to read a file line by line into different data type vectors. Is there a way to do this with inFile >> ? My code is below. Thanks in advance!

void fileOpen()
{
    fstream inFile;
    inFile.open(userFile);

    // Check if file open successful -- if so, process

    if (!inFile.is_open()) {cout << "File could not be opened.";}
    else
    {
        cout << "File is open.\n";

        string firstLine;
        string line;

        vector<char> printMethod;
        vector<string> shirtColor;
        vector<string> orderID;
        vector<string> region;
        vector<int> charCount;
        vector<int> numMedium;
        vector<int> numLarge;
        vector<int> numXL;

        getline(inFile, firstLine); // get column headings out of the way
        cout << firstLine << endl << endl;

        while(inFile.good()) // while we are not at the end of the file, process
        {
            while(getline(inFile, line)) // get each line of the file separately
            {
               for (int i = 1; i < 50; i++)
               {
                  inFile >> date >> printMethod.at(i);
                  cout << date << printMethod.at(i) << endl;
               }

            }
        }

    }
}

Body:
Before you use vector.at(i) in your case you should be sure that your vector is long enough cause at will generate out of range exception. As I can see from your code your vector printMethod contains no more than 50 elements so you can resize vector printMethod before use e.g.

vector<char> printMethod(50);

or

vector<char> printMethod;
printMethod.resize(50);

If you're planning to use a variable number of elements more than 50 you should use push_back method like @Phil1970 recommended e.g.

char other_data;
inFile >> date >> other_data;
printMethod.push_back(other_data);


问:
How to perform pivoting for the below query?
I have

```<code>DispositionCode #OfAccounts %OfAccounts
Contact           2            7
NC                3           11
Paid              2            7
PTP               21           75
</code>```

being generated by

```<code>DECLARE @T TABLE(DispositionCode Varchar(10),[#OfAccounts] INT,[%OfAccounts] INT)
Insert into @T Values('Contact',2,7),('NC',3,11),('Paid',2,7),('PTP',21,75)
Select *
From @T
</code>```

Lookng for the below format

```<code>Vals         Contact    NC  Paid    PTP
#OfAccounts    2        3   2       21
%OfAccounts    7        11  7       75
</code>```

Might be with Pivoting?

答:
It's both unpivot and pivot. Unpivoting is performed here using cross apply and pivoting using pivot.

```<code>select *
from (
    select DispositionCode, x.*
    from @T
    cross apply (
        values ('#OfAccounts', [#OfAccounts]), ('%OfAccounts', [%OfAccounts])
    ) x (vals, val)
) t pivot (
    max(val) for DispositionCode in ([Contact],[NC],[Paid],[PTP])
) pvt;
</code>```

Demo

Body:
I have

DispositionCode #OfAccounts %OfAccounts
Contact           2            7
NC                3           11
Paid              2            7
PTP               21           75

being generated by

DECLARE @T TABLE(DispositionCode Varchar(10),[#OfAccounts] INT,[%OfAccounts] INT)
Insert into @T Values('Contact',2,7),('NC',3,11),('Paid',2,7),('PTP',21,75)
Select *
From @T

Lookng for the below format

Vals         Contact    NC  Paid    PTP
#OfAccounts    2        3   2       21
%OfAccounts    7        11  7       75

Might be with Pivoting?

Body:
It's both unpivot and pivot. Unpivoting is performed here using cross apply and pivoting using pivot.

select *
from (
    select DispositionCode, x.*
    from @T
    cross apply (
        values ('#OfAccounts', [#OfAccounts]), ('%OfAccounts', [%OfAccounts])
    ) x (vals, val)
) t pivot (
    max(val) for DispositionCode in ([Contact],[NC],[Paid],[PTP])
) pvt;

Demo


问:
Angular JS - How to reset / reload an angular app
Does anyone knows how to exactly reset / reload an angular app?

```<code>var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
    $scope.sel1 = {
    '1':{title:'1X', val:'1'},
    '2':{title:'2X', val:'2'},
    '3':{title:'3X', val:'3'},
    '5':{title:'5X', val:'5'},
    };

    $scope.xyz='123';
    $scope.func_1();
});
.
.
.

<input type='text' ng-model='xyz' />
<select ng-options='v.title for v in sel1'></select>
<input type='text' value='{{sel1.val}}' />
</code>```

Thanks

答:
I found the solution myself. We can do it using the following steps as an example

1) Put the default values in a separate function:

```<code>function controller_defaults($scope)
{
    $scope.xyz='123';
    $scope.func_1();
}
</code>```

2) setup a reset function in the controller:

```<code>dtApp.controller('Cont1', function($scope)
{
    $scope.resetx = function()
    {
        controller_defaults($scope);
        $scope.$apply();
    }
}
</code>```

3) call the reset function from outside the angular code, e.g. a button click:

```<code>angular.element(document.getElementById("cont_tag_id")).scope().resetx();
document.getElementById('form_id').reset(); //additional work to reset rest of the form
</code>```

Body:
Does anyone knows how to exactly reset / reload an angular app?

var dtApp = angular.module('App1', []);
dtApp.controller('Cont1', function($scope)
{
    $scope.sel1 = {
    '1':{title:'1X', val:'1'},
    '2':{title:'2X', val:'2'},
    '3':{title:'3X', val:'3'},
    '5':{title:'5X', val:'5'},
    };

    $scope.xyz='123';
    $scope.func_1();
});
.
.
.

<input type='text' ng-model='xyz' />
<select ng-options='v.title for v in sel1'></select>
<input type='text' value='{{sel1.val}}' />

Thanks

Body:
I found the solution myself. We can do it using the following steps as an example

1) Put the default values in a separate function:

function controller_defaults($scope)
{
    $scope.xyz='123';
    $scope.func_1();
}

2) setup a reset function in the controller:

dtApp.controller('Cont1', function($scope)
{
    $scope.resetx = function()
    {
        controller_defaults($scope);
        $scope.$apply();
    }
}

3) call the reset function from outside the angular code, e.g. a button click:

angular.element(document.getElementById("cont_tag_id")).scope().resetx();
document.getElementById('form_id').reset(); //additional work to reset rest of the form


问:
How to prevent overflow in simple VBA code?
I'm new to VBA and was writing a simple code to take all numbers in column A and add 99 to those numbers in column B. However, as soon as it passes 1000, an overflow occurs. What can I do to cut off the while loop so it doesn't overflow the remaining columns with 99? Thanks!</p>

```<code>Sub Button1_Click()

Dim n As Integer
n = 0
While Cells(1 + n, 1) <= 1000
    If Cells(1 + n, 2) = 0 Then
        Stop
    End If
    Cells(1 + n, 2).Value = Cells(1 + n, 1) + 99
    n = n + 1
Wend

End Sub
</code>```

答:
maybe you're after this:</p>

```<code>Dim cell As Range

For Each cell In Range("A:A").SpecialCells(xlCellTypeConstants, xlNumbers) '<--| loop through column A cells with constant numeric content
    If cell.Value > 1000 Then Exit For '<--| exit loop as soon as the current cell value exceeds 1000
    cell.Offset(, 1).Value = cell.Value + 99
Next
</code>```

Body:
I'm new to VBA and was writing a simple code to take all numbers in column A and add 99 to those numbers in column B. However, as soon as it passes 1000, an overflow occurs. What can I do to cut off the while loop so it doesn't overflow the remaining columns with 99? Thanks!

Sub Button1_Click()

Dim n As Integer
n = 0
While Cells(1 + n, 1) <= 1000
    If Cells(1 + n, 2) = 0 Then
        Stop
    End If
    Cells(1 + n, 2).Value = Cells(1 + n, 1) + 99
    n = n + 1
Wend

End Sub

Body:
maybe you're after this:

Dim cell As Range

For Each cell In Range("A:A").SpecialCells(xlCellTypeConstants, xlNumbers) '<--| loop through column A cells with constant numeric content
    If cell.Value > 1000 Then Exit For '<--| exit loop as soon as the current cell value exceeds 1000
    cell.Offset(, 1).Value = cell.Value + 99
Next