问:
Django image field default static file
I was wondering if there is a way to use an static image file as a default for an ImageField?

I'm asking this because if you write something like this because first, I'm not able to upload media folder to my github repository because I store in there the user uploads, and the default file always be the same, so I want to serve the default from static but the user uploads from media directory.

If you use this:

```<code>image = models.ImageField(upload_to=/upload/folder/, default=/img/default.jpg, blank=True, null=True)
</code>```

It will try to load the default image from the media directory.

答:
UPDATE: This answer no longer works. Since version 1.9, Django removes the leading / from the file path to convert it to a relative path and then appends /media/ to the path.

This change was made due to this ticket: https://code.djangoproject.com/ticket/25905

Alternative: I like this answer as an alternative.

Original answer:

First, look at the these two paths:

```<code>/img/default.jpg    -   Absolute Path (starts with slash)
img/default.jpg     -   Relative Path (doesn't start with slash)
</code>```

Now, if your default path is absolute, then Django will not convert the url to /media/.../. Django only converts the relative paths.

So, if you want to serve the default file from static folder, you can just set an absolute path to your file like - /static/img/default.jpg.

Extra:

You can even verify this. Django uses urllib.parse.urljoin to create the url. Try this:

```<code>>>> media_url = '/media/'
>>> abs_url   = '/img/default.jpg' # absolute url
>>> rel_url   = 'img/default.jpg'  # relative url

>>> from urllib.parse import urljoin # in Python 2: from urlparse import urljoin

>>> urljoin(media_url, abs_url) # test with absolute url
'/img/default.jpg'
>>> urljoin(media_url, rel_url) # test with relative url
'/media/img/default.jpg'
</code>```

Title: Django image field default static file

Body:
I was wondering if there is a way to use an static image file as a default for an ImageField?

I'm asking this because if you write something like this because first, I'm not able to upload media folder to my github repository because I store in there the user uploads, and the default file always be the same, so I want to serve the default from static but the user uploads from media directory.

If you use this:

image = models.ImageField(upload_to=/upload/folder/, default=/img/default.jpg, blank=True, null=True)

It will try to load the default image from the media directory.

Body:
UPDATE: This answer no longer works. Since version 1.9, Django removes the leading / from the file path to convert it to a relative path and then appends /media/ to the path.

This change was made due to this ticket: https://code.djangoproject.com/ticket/25905

Alternative: I like this answer as an alternative.

Original answer:

First, look at the these two paths:

/img/default.jpg    -   Absolute Path (starts with slash)
img/default.jpg     -   Relative Path (doesn't start with slash)

Now, if your default path is absolute, then Django will not convert the url to /media/.../. Django only converts the relative paths.

So, if you want to serve the default file from static folder, you can just set an absolute path to your file like - /static/img/default.jpg.

Extra:

You can even verify this. Django uses urllib.parse.urljoin to create the url. Try this:

>>> media_url = '/media/'
>>> abs_url   = '/img/default.jpg' # absolute url
>>> rel_url   = 'img/default.jpg'  # relative url

>>> from urllib.parse import urljoin # in Python 2: from urlparse import urljoin

>>> urljoin(media_url, abs_url) # test with absolute url
'/img/default.jpg'
>>> urljoin(media_url, rel_url) # test with relative url
'/media/img/default.jpg'

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Continue calendar time after timepick
How do I make a calendar's time to run after I pick in timepicker? It seems calendar's time does not run if I pick. If I pick 1:00PM it will be 1:00PM forever. how do i make it 1:01PM after 1 minute? what i did was after timepicker, i set it to a calendar.

Sorry for my English

答:
If I understand your question correctly, you want a user to be able to set a clock using the TimePicker dialog, and have the TimePicker dialog show the previous set time + elapsed time the next time it shows?
This may work for you:

MainActivity.java

```<code>// class implements TimePickerDialog.OnTimeSetListener and uses onTimeSet()
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
  //myTime wrapped in Long instead of primitive long so it can be null
  Long myTime;
  int hours, mins;

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

  //TimePickerDialog.OnTimeSetListener returns here
  @Override
  public void onTimeSet(TimePicker view, int hour, int min) {
    myTime = System.currentTimeMillis();
    this.hours = hour;
    this.mins = min;
  }

  //our xml button onClick method to trigger TimePicker dialog
  public  void timeButtonClicked( View v ){
    //send bundle arguments to fragment if hour/minute previously set
    TimePickerFragment fragment = TimePickerFragment.newInstance( myTime, hours, mins );
    fragment.show(getFragmentManager(), "timePicker");
  }
}
</code>```

TimePickerFragment.java

```<code>public  class TimePickerFragment extends DialogFragment {

  public static TimePickerFragment newInstance( Long savedTime, int hours, int mins ){
    TimePickerFragment myFragment = new TimePickerFragment();
    Bundle args = new Bundle();
    //savedTime is Long wrapped so it can be null if not set
    //and thus bundle will not be set if savedTime is null
    if(savedTime!=null){
      args.putLong("savedTime", savedTime);
      args.putInt("hours", hours);
      args.putInt("mins", mins);
      myFragment.setArguments(args);
    }
    return myFragment;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState){
    Long savedTime;
    int hoursDiff=0, minsDiff=0;
    int hourOfDay, minute;

    // create a Calendar instance of the current time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();

    // create hourOfDay, minute variables to pass as parameters
    // to the TimePicker dialog. If passed by bundle, use that
    // time and difference otherwise use current time
    Bundle bundle = getArguments();  //NOT savedInstanceState bundle
    if (bundle != null) {
      // unix time in milliseconds since Epoch set
      // by System.currentTimeMillis() by MainActivity.onTimeSet()
      savedTime = bundle.getLong("savedTime");
      // set calendar to passed savedTime + (current time difference)
      long timeDifference = currentTime-savedTime;
      minsDiff = (int)(timeDifference/60000);
      if(minsDiff>60) hoursDiff = (int)(minsDiff/60);
      // hours and mins last set by MainActivity.onTimeSet()
      hourOfDay=bundle.getInt("hours")+hoursDiff;
      minute=bundle.getInt("mins")+minsDiff;
    }
    else {
       // bundle not set, use current time
       hourOfDay = c.get(Calendar.HOUR_OF_DAY);
       minute = c.get(Calendar.MINUTE);
    }

    // Create a new instance of TimePickerDialog with hourOfDay and minute parameters and return the fragment
    return new TimePickerDialog( getActivity(),
        (TimePickerDialog.OnTimeSetListener) getActivity(), hourOfDay, minute,
        DateFormat.is24HourFormat(getActivity()));
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Continue calendar time after timepick

Body:
If I understand your question correctly, you want a user to be able to set a clock using the TimePicker dialog, and have the TimePicker dialog show the previous set time + elapsed time the next time it shows?
This may work for you:

MainActivity.java

// class implements TimePickerDialog.OnTimeSetListener and uses onTimeSet()
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
  //myTime wrapped in Long instead of primitive long so it can be null
  Long myTime;
  int hours, mins;

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

  //TimePickerDialog.OnTimeSetListener returns here
  @Override
  public void onTimeSet(TimePicker view, int hour, int min) {
    myTime = System.currentTimeMillis();
    this.hours = hour;
    this.mins = min;
  }

  //our xml button onClick method to trigger TimePicker dialog
  public  void timeButtonClicked( View v ){
    //send bundle arguments to fragment if hour/minute previously set
    TimePickerFragment fragment = TimePickerFragment.newInstance( myTime, hours, mins );
    fragment.show(getFragmentManager(), "timePicker");
  }
}

TimePickerFragment.java

public  class TimePickerFragment extends DialogFragment {

  public static TimePickerFragment newInstance( Long savedTime, int hours, int mins ){
    TimePickerFragment myFragment = new TimePickerFragment();
    Bundle args = new Bundle();
    //savedTime is Long wrapped so it can be null if not set
    //and thus bundle will not be set if savedTime is null
    if(savedTime!=null){
      args.putLong("savedTime", savedTime);
      args.putInt("hours", hours);
      args.putInt("mins", mins);
      myFragment.setArguments(args);
    }
    return myFragment;
  }

  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState){
    Long savedTime;
    int hoursDiff=0, minsDiff=0;
    int hourOfDay, minute;

    // create a Calendar instance of the current time
    Calendar c = Calendar.getInstance();
    long currentTime = c.getTimeInMillis();

    // create hourOfDay, minute variables to pass as parameters
    // to the TimePicker dialog. If passed by bundle, use that
    // time and difference otherwise use current time
    Bundle bundle = getArguments();  //NOT savedInstanceState bundle
    if (bundle != null) {
      // unix time in milliseconds since Epoch set
      // by System.currentTimeMillis() by MainActivity.onTimeSet()
      savedTime = bundle.getLong("savedTime");
      // set calendar to passed savedTime + (current time difference)
      long timeDifference = currentTime-savedTime;
      minsDiff = (int)(timeDifference/60000);
      if(minsDiff>60) hoursDiff = (int)(minsDiff/60);
      // hours and mins last set by MainActivity.onTimeSet()
      hourOfDay=bundle.getInt("hours")+hoursDiff;
      minute=bundle.getInt("mins")+minsDiff;
    }
    else {
       // bundle not set, use current time
       hourOfDay = c.get(Calendar.HOUR_OF_DAY);
       minute = c.get(Calendar.MINUTE);
    }

    // Create a new instance of TimePickerDialog with hourOfDay and minute parameters and return the fragment
    return new TimePickerDialog( getActivity(),
        (TimePickerDialog.OnTimeSetListener) getActivity(), hourOfDay, minute,
        DateFormat.is24HourFormat(getActivity()));
  }
}


问:
Problems changing datagrid color using WPF C#
I am using a datagrid and changing the color of the rows according to their conditions and I am performing this programmatically.
follow the example
as my datagrid is bound to a datatable I load information straight from the datatable

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

gvDados.UpdateLayout ();
for (int i = 0; i <dt.Rows.Count; i ++)
{
      var rowContext = (DataGridRow)
      gvDados.ItemContainerGenerator.ContainerFromIndex (i);

      if (rowContext! = null)
      {
            if (dt.Rows [i] ["situation"]. ToString (). Equals (1))
                     rowContext.Background = Brushes.Green;
            else
                     rowContext.Background = Brushes.Red;
      }
   }
}
</code>```

With this I can update the color of my grid even though it is not the best method to be approached. my problem is this, whenever I use the scroll to go down or up the bar the colors become outdated. How do I prevent this from happening? that even when I roll the bar the colors stay fixed?

答:
Often, XAML is too simple to express more complicated conditions. I prefer to put the logic which values should use which colors into a converter. This leads to a simpler XAML and much greater flexibility for the converter in C#.

```<code><datagrid.rowstyle>
  <style targettype="DataGridRow">
    <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self},
      Path=Item.situation, Converter={StaticResource ValueToBackgroundConverter}}"/>
  </style>
</datagrid.rowstyle>
</code>```

In C#:

```<code>class ValueToBackgroundConverter: IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
    if (value is int) {
      int quantity = (int)value;
      if (quantity>=100) return Brushes.White;
      if (quantity>=10) return Brushes.WhiteSmoke;
      if (quantity>=0) return Brushes.LightGray;
      return Brushes.White; //quantity should not be below 0
    }
    //value is not an integer. Do not throw an exception
    // in the converter, but return something that is obviously wrong
    return Brushes.Yellow;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
    throw new NotImplementedException();
   }
}
</code>```

Formatting the various parts of a WPF Datagrid is notoriously difficult and Microsoft is not providing the necessary information how to do it. Read my article Codeproject: Guide to WPF DataGrid formatting using binding to get a better understanding how to do it easily.

Body:
I am using a datagrid and changing the color of the rows according to their conditions and I am performing this programmatically.
follow the example
as my datagrid is bound to a datatable I load information straight from the datatable

private void UpdateCor () {

gvDados.UpdateLayout ();
for (int i = 0; i <dt.Rows.Count; i ++)
{
      var rowContext = (DataGridRow)
      gvDados.ItemContainerGenerator.ContainerFromIndex (i);

      if (rowContext! = null)
      {
            if (dt.Rows [i] ["situation"]. ToString (). Equals (1))
                     rowContext.Background = Brushes.Green;
            else
                     rowContext.Background = Brushes.Red;
      }
   }
}

With this I can update the color of my grid even though it is not the best method to be approached. my problem is this, whenever I use the scroll to go down or up the bar the colors become outdated. How do I prevent this from happening? that even when I roll the bar the colors stay fixed?

Body:
Often, XAML is too simple to express more complicated conditions. I prefer to put the logic which values should use which colors into a converter. This leads to a simpler XAML and much greater flexibility for the converter in C#.

<datagrid.rowstyle>
  <style targettype="DataGridRow">
    <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self},
      Path=Item.situation, Converter={StaticResource ValueToBackgroundConverter}}"/>
  </style>
</datagrid.rowstyle>

In C#:

class ValueToBackgroundConverter: IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
    if (value is int) {
      int quantity = (int)value;
      if (quantity>=100) return Brushes.White;
      if (quantity>=10) return Brushes.WhiteSmoke;
      if (quantity>=0) return Brushes.LightGray;
      return Brushes.White; //quantity should not be below 0
    }
    //value is not an integer. Do not throw an exception
    // in the converter, but return something that is obviously wrong
    return Brushes.Yellow;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
    throw new NotImplementedException();
   }
}

Formatting the various parts of a WPF Datagrid is notoriously difficult and Microsoft is not providing the necessary information how to do it. Read my article Codeproject: Guide to WPF DataGrid formatting using binding to get a better understanding how to do it easily.


问:
How to create a typedef for function pointers
I think it would be easier to use function pointers if I created a typedef for a function pointer, but I seem to be getting myself tripped up on some syntax or usage or something about typedef for function pointers, and I could use some help.

I've got

```<code>int foo(int i){ return i + 1;}
typedef <???> g;
int hvar;
hvar = g(3)
</code>```

That's basically what I'm trying to accomplish I'm a rather new C programmer and this is throwing me too much. What replaces <???> ?

答:
You are right. The function pointer can be conveniently used to point to the different functions of the same return type and taking same number of arguments.
The argument types should match the declaration of the function pointer arguments.

In your case you could define your function pointer g as:

typedef int (*g)(int);        // typedef of the function pointer.

g is a function pointer for the function returning int value and taking one int argument.

The usage of function pointer could be illustrated by a simple program below:

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

typedef int (*pointer_to_function)(int first_parameter_of_type_int, int second_parameter_of_type_int);

int my_function_returning_int_and_taking_two_int_arguments(int par1, int par2)
{
    int result = par1 + par2;
    return result;
}

int my_mul_function(int par1, int par2)
{
    int result = par1 * par2;
    return result;
}

int main()
{
    int res; // returning result will be here
    pointer_to_function my_fun_pointer; // declare function pointer variable;

    my_fun_pointer = my_function_returning_int_and_taking_two_int_arguments; // function pointer points to `my_function_returning_int_and_taking_two_int_arguments` function
    res = my_fun_pointer(2,3);       // Call function through pointer
    printf(" result of `my_function_returning_int_and_taking_two_int_arguments` = %d \n", res);

    my_fun_pointer = my_mul_function; // now function pointer points to another function: `my_mul_function`
    res = my_fun_pointer(2,3);       // Call function through pointer
    printf(" result of `my_mul_function` = %d \n", res);

   return 0;
}
</code>```

OUTPUT:

```<code>result of `my_function_returning_int_and_taking_two_int_arguments` = 5
result of `my_mul_function` = 6
</code>```

Body:
I think it would be easier to use function pointers if I created a typedef for a function pointer, but I seem to be getting myself tripped up on some syntax or usage or something about typedef for function pointers, and I could use some help.

I've got

int foo(int i){ return i + 1;}
typedef <???> g;
int hvar;
hvar = g(3)

That's basically what I'm trying to accomplish I'm a rather new C programmer and this is throwing me too much. What replaces <???> ?

Body:
You are right. The function pointer can be conveniently used to point to the different functions of the same return type and taking same number of arguments.
The argument types should match the declaration of the function pointer arguments.

In your case you could define your function pointer g as:

typedef int (*g)(int);        // typedef of the function pointer.

g is a function pointer for the function returning int value and taking one int argument.

The usage of function pointer could be illustrated by a simple program below:

#include<stdio.h>

typedef int (*pointer_to_function)(int first_parameter_of_type_int, int second_parameter_of_type_int);

int my_function_returning_int_and_taking_two_int_arguments(int par1, int par2)
{
    int result = par1 + par2;
    return result;
}

int my_mul_function(int par1, int par2)
{
    int result = par1 * par2;
    return result;
}

int main()
{
    int res; // returning result will be here
    pointer_to_function my_fun_pointer; // declare function pointer variable;

    my_fun_pointer = my_function_returning_int_and_taking_two_int_arguments; // function pointer points to `my_function_returning_int_and_taking_two_int_arguments` function
    res = my_fun_pointer(2,3);       // Call function through pointer
    printf(" result of `my_function_returning_int_and_taking_two_int_arguments` = %d \n", res);

    my_fun_pointer = my_mul_function; // now function pointer points to another function: `my_mul_function`
    res = my_fun_pointer(2,3);       // Call function through pointer
    printf(" result of `my_mul_function` = %d \n", res);

   return 0;
}

OUTPUT:

result of `my_function_returning_int_and_taking_two_int_arguments` = 5
result of `my_mul_function` = 6


问:
running a mysql query inside a loop of another without a sync error
If I have code like this (irrelevant things like initialising the connection and handle omitted):

```<code>MYSQL_RES *res;
MYSQL_ROW row;
mysql_query(mysql, "some select query");
res = mysql_use_result(mysql);
while (row = mysql_fetch_row(res)) {
    MYSQL_RES *res2;
    MYSQL_ROW row2;
    mysql_query(mysql, "some other select query using an id from the first");
    res2 = mysql_use_result(mysql);
    /* ... */
    mysql_free_result(res2);
}
mysql_free_result(res);
</code>```

Whenever I run the second mysql_query (in the loop), I get the error

```<code>mysql: 2014: Commands out of sync; you can't run this command now
</code>```

How can I run another select query while fetching rows from one select query?

答:
The real question is: why do you need two loops? </p>

<p>It's almost always more efficient to create a single statement that returns everything you want, instead of firing off one statement per row from the outer statement. </p>

ContentLicense: CC BY-SA 2.5

Body:
If I have code like this (irrelevant things like initialising the connection and handle omitted):

MYSQL_RES *res;
MYSQL_ROW row;
mysql_query(mysql, "some select query");
res = mysql_use_result(mysql);
while (row = mysql_fetch_row(res)) {
    MYSQL_RES *res2;
    MYSQL_ROW row2;
    mysql_query(mysql, "some other select query using an id from the first");
    res2 = mysql_use_result(mysql);
    /* ... */
    mysql_free_result(res2);
}
mysql_free_result(res);

Whenever I run the second mysql_query (in the loop), I get the error

mysql: 2014: Commands out of sync; you can't run this command now

How can I run another select query while fetching rows from one select query?

Body:
The real question is: why do you need two loops?

It's almost always more efficient to create a single statement that returns everything you want, instead of firing off one statement per row from the outer statement.


问:
take a particular key from list and store to another list using stream
I have a Class with these fields

```<code>class ListA {
    Long id
    double lat
    doubel lon
    Timestamp timestamp
}
</code>```

I need to make a new list which will only have lat, lon

```<code>class LatLng {
    double lat
    double lon
}
</code>```

how can I do this using streams in Java?

I am able to do this using native for loop. But I want to learn to do it using stream.

```<code>List<ListA> listAs = this.dao.findAll();

List<LatLng> latLngs = new ArrayList();
for (ListA listA : listAs) {
    LatLng latLng = new LatLng(listA.getLat(), listA.getLon());
    latLngs.add(latlng)
}
</code>```

I just want to pluck lat and lon from ListA and store it to LatLng.

答:
You can do this :

```<code>List<ListA> listAs = this.dao.findAll();

List<LatLng> latLngs = listAs.stream()
                .map(listA -> new LatLng(listA.getLat(), listA.getLon()))
                .collect(Collectors.toList());
</code>```

Or even this to save a variable :

```<code>List<LatLng> latLngs = this.dao.findAll().stream()
                .map(listA -> new LatLng(listA.getLat(), listA.getLon()))
                .collect(Collectors.toList());
</code>```

Body:
I have a Class with these fields

class ListA {
    Long id
    double lat
    doubel lon
    Timestamp timestamp
}

I need to make a new list which will only have lat, lon

class LatLng {
    double lat
    double lon
}

how can I do this using streams in Java?

I am able to do this using native for loop. But I want to learn to do it using stream.

List<ListA> listAs = this.dao.findAll();

List<LatLng> latLngs = new ArrayList();
for (ListA listA : listAs) {
    LatLng latLng = new LatLng(listA.getLat(), listA.getLon());
    latLngs.add(latlng)
}

I just want to pluck lat and lon from ListA and store it to LatLng.

Body:
You can do this :

List<ListA> listAs = this.dao.findAll();

List<LatLng> latLngs = listAs.stream()
                .map(listA -> new LatLng(listA.getLat(), listA.getLon()))
                .collect(Collectors.toList());

Or even this to save a variable :

List<LatLng> latLngs = this.dao.findAll().stream()
                .map(listA -> new LatLng(listA.getLat(), listA.getLon()))
                .collect(Collectors.toList());


问:
How to try/catch all exceptions
I'm completing a UWP app started by someone else. The app crashes frequently and I always end up in App.g.i.cs at

```<code>if (global::System.Diagnostics.Debugger.IsAttached)
    global::System.Diagnostics.Debugger.Break();
</code>```

where I then have to say "no, don't start the debugger" and close 2 windows.

Is there somewhere I could put a big try/catch so that I don't have to restart the app each time this happen? I can't find anything in AppShell or App.

Or do I have to put a try/catch in every single event handler?

答:
If you want to treat the cause rather than the symptoms, you should enable first-chance exceptions in the debugger settings. Then the debugger should break at the source of the exception, rather than in the global handler. You can then address the root cause of the problems directly.

Shipping an app that has the global handler blindly set every exception as "handled" even when you don't know why it's failing is not a good solution.

Title: How to try/catch all exceptions

Body:
I'm completing a UWP app started by someone else. The app crashes frequently and I always end up in App.g.i.cs at

if (global::System.Diagnostics.Debugger.IsAttached)
    global::System.Diagnostics.Debugger.Break();

where I then have to say "no, don't start the debugger" and close 2 windows.

Is there somewhere I could put a big try/catch so that I don't have to restart the app each time this happen? I can't find anything in AppShell or App.

Or do I have to put a try/catch in every single event handler?


问:
Get row number for prediction with caret
I use caret a lot for my machine learning tasks in R and I like it a lot.

But I face the following problem:

I train a model in caret, say a linear regression with lm()

When I want to score new data, I do: predict(model, new_data)

When new_datacontains missing values in my predictors, predict returns no prediction, instead of say NA

Is it possible to either:

return a prediction for all rows in new_data with a prediction of NA when it is not possible or

return predictions + the row number of the dataframe the prediction corresponds to?

E.g. like the mlr-package does with an id-column that shows which row the prediction corresponds to:

Here is the link to the mlr-predict page with more details:
mlr-package: predict with row-id

Any help greatly appreciated!

答:
You can identify the cases with missing values prior to running caret::train() by creating a new column with the row names in your data set, since these default to the row numbers in the data frame.

Using the Sonar data set from the mlbench package as an illustration:

```<code>library(mlbench)
data(Sonar)
library(caret)
set.seed(95014)

# add row numbers
Sonar$rowId <- rownames(Sonar)
# create training & testing data sets

inTraining <- createDataPartition(Sonar$Class, p = .75, list=FALSE)
training <- Sonar[inTraining,]
testing <- Sonar[-inTraining,]
# set column 60 to NA for some values in test data
testing[48:51,60] <- NA
testing[!complete.cases(testing),"rowId"]
</code>```

...and the output:

```<code>> testing[!complete.cases(testing),"rowId"]
[1] "193" "194" "200" "206"
</code>```

You can then run predict() on the rows in the test data set that have complete cases. Again using the Sonar dataset with a random forest model and 3 fold cross validation to expedite processing:

```<code>fitControl <- trainControl(method = "cv",number = 3)
fit <- train(x,y, method="rf",data=Sonar,trControl = fitControl)
predicted <- predict(fit,testing[complete.cases(testing),])
</code>```

Another way to handle this situation is to use an imputation strategy to eliminate the missing values for the independent variables in your model. My article on Github, Strategies for Handling Missing Values links to a number of research papers on this topic.

Body:
You can identify the cases with missing values prior to running caret::train() by creating a new column with the row names in your data set, since these default to the row numbers in the data frame.

Using the Sonar data set from the mlbench package as an illustration:

library(mlbench)
data(Sonar)
library(caret)
set.seed(95014)

# add row numbers
Sonar$rowId <- rownames(Sonar)
# create training & testing data sets

inTraining <- createDataPartition(Sonar$Class, p = .75, list=FALSE)
training <- Sonar[inTraining,]
testing <- Sonar[-inTraining,]
# set column 60 to NA for some values in test data
testing[48:51,60] <- NA
testing[!complete.cases(testing),"rowId"]

...and the output:

> testing[!complete.cases(testing),"rowId"]
[1] "193" "194" "200" "206"

You can then run predict() on the rows in the test data set that have complete cases. Again using the Sonar dataset with a random forest model and 3 fold cross validation to expedite processing:

fitControl <- trainControl(method = "cv",number = 3)
fit <- train(x,y, method="rf",data=Sonar,trControl = fitControl)
predicted <- predict(fit,testing[complete.cases(testing),])

Another way to handle this situation is to use an imputation strategy to eliminate the missing values for the independent variables in your model. My article on Github, Strategies for Handling Missing Values links to a number of research papers on this topic.


问:
When pressed 'Enter', sum the input and clear it
I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared

The amounts entered must be added together and their total must be shown in a second text box.

my HTML:

```<code><input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
</code>```

My JS:

```<code>input = document.getElementById("input");
        input.onkeypress = function(event) {
            ceckKey(event);
        };

        function ceckKey(e) {
            // check for enter: e.key is for Firefox
            // if true, make input empty
            if (e.keyCode == 13 || e.key == 13) {
                input.value = "";
            }
            var number = +input.value;
            return number;
        }

        var total = 0
        total += checkKey();
        document.getElementById("output").value = total;
</code>```

The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.

I hope you guys can help!

答:
You are updating the output element outside of the ceckKey function.

This update IS not automatic. You must trigger it.
Also, check carefully that function. Callbacks can return a value but using the dame function for a callbacks and getting that output contents does not look good.

Body:
I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared

The amounts entered must be added together and their total must be shown in a second text box.

my HTML:

<input type="text" id="input">

Uw totaal:

<input type="text" id="output">

My JS:

input = document.getElementById("input");
        input.onkeypress = function(event) {
            ceckKey(event);
        };

        function ceckKey(e) {
            // check for enter: e.key is for Firefox
            // if true, make input empty
            if (e.keyCode == 13 || e.key == 13) {
                input.value = "";
            }
            var number = +input.value;
            return number;
        }

        var total = 0
        total += checkKey();
        document.getElementById("output").value = total;

The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.

I hope you guys can help!


问:
Timeout for multiprocessing?
This code pings various machines. Could you please help me change this code so if a process of pinging hangs for more then 7 seconds it shuts down and returns some flag?

(I'd like to pull various data from machines using WMI. For that I'll change ping function to something else. The issue is on some machines WMI is corrupted and process of pulling data hangs indefinitely. Timeout is needed.)

```<code>import multiprocessing.dummy
import subprocess
import numpy as np
import time

start_time = time.time()

def ping(ipadd):
    try:
        response = subprocess.check_output(['ping', ipadd])
        return True
    except subprocess.CalledProcessError as e:
        return False
#print(ping('10.25.59.20'))
machine_names = \
'''
ya.ru
microsoft.com
www.google.com
www.amazon.com
www.nasa.com
'''.split()

np_machine_names = np.array(machine_names)
p = multiprocessing.dummy.Pool(7)
ping_status = p.map(ping, machine_names)
np_ping_status = np.fromiter(ping_status, dtype=bool)
print(*np_machine_names[np_ping_status], sep = '\n')

run_time = time.time() - start_time
print(f'Runtime: {run_time:.0f}')
</code>```

UPDATE:
While I appreciate for the tip on adding timeout to subprocess the question remains. How do I shutdown hanged function? Let's say I've changed pinging to pulling WMI data from a machine (this one pulls list of installed software from Windows machine). There is no subprocess to set timer on:

```<code>#pip install pypiwin32
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
for objItem in colItems:
    print( "Caption: ", objItem.Caption )
</code>```

答:
There are several ways to tackle long running executions. Each way has its benefits and drawbacks.

APIs

As already suggested, the simplest ways is to rely on the APIs timeouts. Modules such as subprocess, socket, requests etc... expose timeout parameters within their APIs.

This is the preferable approach whenever feasible.

Threads

The long-running/hanging logic is executed within a separate thread. The main loop can continue undisturbed and ignore the hanging execution.

```<code>import threading

TIMEOUT = 60

def hanging_function():
    hang_here()

thread = threading.Tread(target=hanging_function)
thread.daemon = True
thread.start()

thread.join(TIMEOUT)
if thread.is_alive():
    print("Function is hanging!")
</code>```

One of the issue with this approach is that the hanging thread will continue to execute in the background consuming resources.

Another limitation is due to the fact that threads share memory. If your your function happens to crash badly it might affect your main execution as well.

Processes

My favourite approach is to execute the problematic logic in a separate process using the multiprocessing facilities. As processes do not share memory, whatever happens in the problematic function remains limited to the child process which you can terminate at any point in time.

```<code>import multiprocessing

TIMEOUT = 60

def hanging_function():
    hang_here()

process = multiprocessing.Process(target=hanging_function)
process.daemon = True
process.start()

process.join(TIMEOUT)
if process.is_alive():
    print("Function is hanging!")
    process.terminate()
    print("Kidding, just terminated!")
</code>```

The pebble library was built on top of this principle. Allowing to easily separate problematic code and deal with failures and catastrophes.

The drawback of using processes is that they are a bit heavier than the other two approaches. Moreover, as memory between processes is isolated, it's a bit more complicated to share data.

Title: Timeout for multiprocessing?

Body:
This code pings various machines. Could you please help me change this code so if a process of pinging hangs for more then 7 seconds it shuts down and returns some flag?

(I'd like to pull various data from machines using WMI. For that I'll change ping function to something else. The issue is on some machines WMI is corrupted and process of pulling data hangs indefinitely. Timeout is needed.)

import multiprocessing.dummy
import subprocess
import numpy as np
import time

start_time = time.time()

def ping(ipadd):
    try:
        response = subprocess.check_output(['ping', ipadd])
        return True
    except subprocess.CalledProcessError as e:
        return False
#print(ping('10.25.59.20'))
machine_names = \
'''
ya.ru
microsoft.com
www.google.com
www.amazon.com
www.nasa.com
'''.split()

np_machine_names = np.array(machine_names)
p = multiprocessing.dummy.Pool(7)
ping_status = p.map(ping, machine_names)
np_ping_status = np.fromiter(ping_status, dtype=bool)
print(*np_machine_names[np_ping_status], sep = '\n')

run_time = time.time() - start_time
print(f'Runtime: {run_time:.0f}')

UPDATE:
While I appreciate for the tip on adding timeout to subprocess the question remains. How do I shutdown hanged function? Let's say I've changed pinging to pulling WMI data from a machine (this one pulls list of installed software from Windows machine). There is no subprocess to set timer on:

#pip install pypiwin32
import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_Product")
for objItem in colItems:
    print( "Caption: ", objItem.Caption )

Body:
There are several ways to tackle long running executions. Each way has its benefits and drawbacks.

APIs

As already suggested, the simplest ways is to rely on the APIs timeouts. Modules such as subprocess, socket, requests etc... expose timeout parameters within their APIs.

This is the preferable approach whenever feasible.

Threads

The long-running/hanging logic is executed within a separate thread. The main loop can continue undisturbed and ignore the hanging execution.

import threading

TIMEOUT = 60

def hanging_function():
    hang_here()

thread = threading.Tread(target=hanging_function)
thread.daemon = True
thread.start()

thread.join(TIMEOUT)
if thread.is_alive():
    print("Function is hanging!")

One of the issue with this approach is that the hanging thread will continue to execute in the background consuming resources.

Another limitation is due to the fact that threads share memory. If your your function happens to crash badly it might affect your main execution as well.

Processes

My favourite approach is to execute the problematic logic in a separate process using the multiprocessing facilities. As processes do not share memory, whatever happens in the problematic function remains limited to the child process which you can terminate at any point in time.

import multiprocessing

TIMEOUT = 60

def hanging_function():
    hang_here()

process = multiprocessing.Process(target=hanging_function)
process.daemon = True
process.start()

process.join(TIMEOUT)
if process.is_alive():
    print("Function is hanging!")
    process.terminate()
    print("Kidding, just terminated!")

The pebble library was built on top of this principle. Allowing to easily separate problematic code and deal with failures and catastrophes.

The drawback of using processes is that they are a bit heavier than the other two approaches. Moreover, as memory between processes is isolated, it's a bit more complicated to share data.


问:
I am calling an external js file however it does nothing. Am I calling it wrong?
```<code><!DOCTYPE html>
<html>
<head>

</head>
<body>

<input type="text" id="TEXTBOX1_ID"></input>
<input type="button" id="button1" value="Add"onclick="add_element_to_array()"></input>
<input type="button" id="button2" value="Display" onclick="display_array()"</input>

<script src="js/app-functions.js"</script>

</body>
</html>
</code>```

<p>the above code contains two buttons and onclick they use a function from a js file. However once I press any of the bottoms it does nothing a piece of text is meant to appear, I don't think it is my js code as It very simple and I have made sure it's not a syntax error. </p>

答:
you missed to > in script.it didn't include file .

corrected:

```<code><script src="js/app-functions.js"></script>
</code>```

Body:
<!DOCTYPE html>

<input type="text" id="TEXTBOX1_ID"></input>
<input type="button" id="button1" value="Add"onclick="add_element_to_array()"></input>
<input type="button" id="button2" value="Display" onclick="display_array()"</input>

the above code contains two buttons and onclick they use a function from a js file. However once I press any of the bottoms it does nothing a piece of text is meant to appear, I don't think it is my js code as It very simple and I have made sure it's not a syntax error.

Body:
you missed to > in script.it didn't include file .

corrected:

<script src="js/app-functions.js"></script>


问:
Download files from USB-connected smartphone to Windows by script (or Python)
Is there a way to download to Windows (and later erase) files on an USB-connected smartphone? I'd like to create an automatic download and backup of pictures for a family smartphone... </p>

<p>I've seen hints only about Unix, and no indication on how copy files via USB on Windows. Finally, I'd like to use Python, so I looked into the libusb package, but this seemed far away from any files&folders model. I have not even been able to find any "mountpoint" on Windows (which I assumed to exist from the presentation of the smartphones in Windows Explorer). </p>

答:
If I connect my android  smartphone to an Windows OS, normaly it gets its own drive letter after allowing the data connection by the phone.

So I would be able to make a backup of pictures with a simple batch-script or even with a python script ( using the functionalities of the os modul).

Body:
Is there a way to download to Windows (and later erase) files on an USB-connected smartphone? I'd like to create an automatic download and backup of pictures for a family smartphone...

I've seen hints only about Unix, and no indication on how copy files via USB on Windows. Finally, I'd like to use Python, so I looked into the libusb package, but this seemed far away from any files&folders model. I have not even been able to find any "mountpoint" on Windows (which I assumed to exist from the presentation of the smartphones in Windows Explorer).


问:
stop execution script within condition
I have the following code in the script test.R:

```<code>if (x==2){
  stop("the script ends")
}
</code>```

Now I source this script

```<code>source(test.R)
t <- 2
</code>```

I would like the code to stop if x==2 and does not go further. However, it continues and assigns t <- 2. I can use the function warnings(options) but I want to avoid this option and implement a condition within the if. Any suggestion?

答:
The code you list should work as expected.

As an example, I made two scripts, test.R and test2.R:

1. File test.R:

```<code>if (identical(x, 2)) {
  stop("the script ends")
}
</code>```

(Note: I'm using identical(x, 2) as the safer way to check whether x equals 2, but x == 2 would work the same in this example.)

2. File test2.R:

```<code>x <- 1
source("test.R")
t <- 1
print("This should be printed.")

x <- 2
source("test.R")
t <- 2
print("This should not be printed!")
</code>```

Now I run test2.R from the console:

```<code>> t <- 5
> source('test2.R')
[1] "This should be printed."
 Error in eval(ei, envir) : the script ends
> t
[1] 1
</code>```

We see that the check passed the first time, when x == 1, and it failed the second time, when x == 2. Therefore, the value of t at the end is 1, because the first assignment was run and the second was not.

Title: stop execution script within condition

Body:
I have the following code in the script test.R:

if (x==2){
  stop("the script ends")
}

Now I source this script

source(test.R)
t <- 2

I would like the code to stop if x==2 and does not go further. However, it continues and assigns t <- 2. I can use the function warnings(options) but I want to avoid this option and implement a condition within the if. Any suggestion?

Body:
The code you list should work as expected.

As an example, I made two scripts, test.R and test2.R:

1. File test.R:

if (identical(x, 2)) {
  stop("the script ends")
}

(Note: I'm using identical(x, 2) as the safer way to check whether x equals 2, but x == 2 would work the same in this example.)

2. File test2.R:

x <- 1
source("test.R")
t <- 1
print("This should be printed.")

x <- 2
source("test.R")
t <- 2
print("This should not be printed!")

Now I run test2.R from the console:

> t <- 5
> source('test2.R')
[1] "This should be printed."
 Error in eval(ei, envir) : the script ends
> t
[1] 1

We see that the check passed the first time, when x == 1, and it failed the second time, when x == 2. Therefore, the value of t at the end is 1, because the first assignment was run and the second was not.


问:
Clustered Index in MySQL
Are clustered index created and stored separately than the actual data in MySQL and if so, then why can we not have more than one clustered index. All we need to do is create another index and store it in memory. </p>

答:
MySQL's InnoDB does the following for its PRIMARY KEY:  The data records are in PK order, stored together in a B+Tree structure.  This allows for rapid point-queries and range scans.  That is, the value at the 'bottom' of the tree has all the columns of the table.

InnoDB's secondary keys are also in a B+Tree, but the bottom values are the PK columns.  Hence, a second lookup is needed to fetch a row(s) by a secondary key.

Note that a secondary key could contain all the columns of the table, thereby acting like a second clustered index.  The drawback is that any modification to the table would necessarily involve changes to both BTrees.

MyISAM, in contrast, throws the data into a file (the .MYD) and has every index in its own BTree in the .MYI file.  The bottom of each BTree is a pointer (row number or byte offset) into the .MYD.  The PK is not implemented any differently than a secondary key.

(Note: FULLTEXT and SPATIAL indexes are not covered by the above discussion.)

Title: Clustered Index in MySQL


问:
Add _redirects file to root path for Vue SPA hosted on Netlify
I'm developing a Single Page App using Vue CLI and want history pushstate to work so I get clean URLs.

I have to follow this: https://www.netlify.com/docs/redirects/#history-pushstate-and-single-page-apps and add a _redirects file to the root of my site folder with the following:

```<code>/*    /index.html   200
</code>```

The problem is I don't know how to add this _redirects file to the root of my dist folder. I tried adding it to the static folder but it ends up in a subfolder and not in root. How can I include this file so that history mode works after deploying on Netlify ?

```<code>// config/index.js
build: {
  // Paths
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
</code>```

答:
vue-cli created app 3.x

For the new build setup using the vue-cli version 3.0.0-beta.x there is a public folder now and you do not need the following setup. Just put your _redirects file under the public folder root. When you build it will make a copy to the dist folder which will be used for your deploy.

vue-cli created app prior to 3.x

Vue.js uses webpack to copy the static assets. This is maintained in webpack.prod.conf.js for the production build which is what you will need in this case for Netlify. I believe the best and cleanest configuration is based on this solution.

Search the file for the new CopyWebpackPlugin in webpack.prod.conf.js.

// copy custom static assets
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  }
])
```

<p><strong>Create a root ( folder in your project same level of the static folder )</strong>
You could name this anything you like, but I will use <code>root</code> for the example.</p>

<p>You would then make sure the <code>_redirects</code> file is in the new <code>root</code> directory or whatever you called it. In this case it is named <code>root</code></p>

<p>Now modify the <code>webpack.prod.conf.js</code> CopyWebpackPlugin section to look like the following:</p>

<pre class="lang-js prettyprint-override"><code>// copy custom static assets
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  },
  {
    from: path.resolve(__dirname, '../root'),
    to: config.build.assetsRoot,
    ignore: ['.*']
  }
])
</code>```

Body:
I'm developing a Single Page App using Vue CLI and want history pushstate to work so I get clean URLs.

I have to follow this: https://www.netlify.com/docs/redirects/#history-pushstate-and-single-page-apps and add a _redirects file to the root of my site folder with the following:

/*    /index.html   200

The problem is I don't know how to add this _redirects file to the root of my dist folder. I tried adding it to the static folder but it ends up in a subfolder and not in root. How can I include this file so that history mode works after deploying on Netlify ?

// config/index.js
build: {
  // Paths
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',

Body:
vue-cli created app 3.x

For the new build setup using the vue-cli version 3.0.0-beta.x there is a public folder now and you do not need the following setup. Just put your _redirects file under the public folder root. When you build it will make a copy to the dist folder which will be used for your deploy.

vue-cli created app prior to 3.x

Vue.js uses webpack to copy the static assets. This is maintained in webpack.prod.conf.js for the production build which is what you will need in this case for Netlify. I believe the best and cleanest configuration is based on this solution.

Search the file for the new CopyWebpackPlugin in webpack.prod.conf.js.

// copy custom static assets
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  }
])

Create a root ( folder in your project same level of the static folder )
You could name this anything you like, but I will use root for the example.

You would then make sure the _redirects file is in the new root directory or whatever you called it. In this case it is named root

Now modify the webpack.prod.conf.js CopyWebpackPlugin section to look like the following:

// copy custom static assets
new CopyWebpackPlugin([
  {
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  },
  {
    from: path.resolve(__dirname, '../root'),
    to: config.build.assetsRoot,
    ignore: ['.*']
  }
])


问:
TypeError: Cannot read property 'assertNoMembers' of null
In Ionic I'm having an issue while executing the following command:

ionic cordova build ios --prod

After that, in "ngc started" the following message appears:

```<code>TypeError: Cannot read property 'assertNoMembers' of null
at AotSummaryResolver.resolveSummary (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:31986:21)
at CompileMetadataResolver._loadSummary (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:14710:66)
at CompileMetadataResolver._getEntryComponentMetadata (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:15742:66)
at /dir/node_modules/@angular/compiler/bundles/compiler.umd.js:14904:76
at Array.map (native)
at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:14904:22)
at /dir/node_modules/@angular/compiler/bundles/compiler.umd.js:29359:88
at Array.forEach (native)
at AotCompiler.findGeneratedFileNames (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:29358:25)
at Object.findGeneratedFileNames (/dir/node_modules/@angular/compiler-cli/src/transformers/program.js:392:82)
</code>```

Command without "--prod" works fine. Also "ionic serve" works fine

答:
I ran into the same error this morning, for me the problem was that I had something like this in one of my module:

```<code>@NgModule({
  imports: [...],
  declarations: [...],
  entryComponents: components.filter(x => x.entryComponent)],
})
</code>```

entryComponents should be an array of type so that the compiler could resolve it at compile time. Changing it to solve the problem:

```<code>@NgModule({
  imports: [...],
  declarations: [...],
  entryComponents: [MyComponent],
})
</code>```

Note: if you ran into this problem with ng serve, the error usually disappear when you change a file and angular recompile your project.

Body:
In Ionic I'm having an issue while executing the following command:

ionic cordova build ios --prod

After that, in "ngc started" the following message appears:

TypeError: Cannot read property 'assertNoMembers' of null
at AotSummaryResolver.resolveSummary (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:31986:21)
at CompileMetadataResolver._loadSummary (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:14710:66)
at CompileMetadataResolver._getEntryComponentMetadata (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:15742:66)
at /dir/node_modules/@angular/compiler/bundles/compiler.umd.js:14904:76
at Array.map (native)
at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:14904:22)
at /dir/node_modules/@angular/compiler/bundles/compiler.umd.js:29359:88
at Array.forEach (native)
at AotCompiler.findGeneratedFileNames (/dir/node_modules/@angular/compiler/bundles/compiler.umd.js:29358:25)
at Object.findGeneratedFileNames (/dir/node_modules/@angular/compiler-cli/src/transformers/program.js:392:82)

Command without "--prod" works fine. Also "ionic serve" works fine

Body:
I ran into the same error this morning, for me the problem was that I had something like this in one of my module:

@NgModule({
  imports: [...],
  declarations: [...],
  entryComponents: components.filter(x => x.entryComponent)],
})

entryComponents should be an array of type so that the compiler could resolve it at compile time. Changing it to solve the problem:

@NgModule({
  imports: [...],
  declarations: [...],
  entryComponents: [MyComponent],
})

Note: if you ran into this problem with ng serve, the error usually disappear when you change a file and angular recompile your project.


问:
pymysql return error SQL syntax
On py3, i use pymysql module for connecting to MySQL.

i write function into Database() class like this where MySQLi run on constructor:

```<code>def add_user_to_database(self, id, first_name, last_name, username, lang_code):
    with self.MySQLi.cursor() as cursor:
        cursor.execute('INSERT INTO users (id, first_name, last_name, username, language_code) VALUES ({0}, {1}, {2}, {3}, {4})'.format(id, first_name, last_name, username, lang_code))
    connection.commit()
</code>```

after i run py database.php it show this error :( :

```<code>    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' sepwhrr, en)' at line 1")
</code>```

答:
When you build a query with string interpolation, you can get escape/quoiting issues, however it's easy to use a parametrised query:</p>

```<code>sql = "INSERT INTO `users` (`id`, `first_name`) VALUES (%s, %s)"
cursor.execute(sql, (id, first_name)
</code>```

Title: pymysql return error SQL syntax

Body:
On py3, i use pymysql module for connecting to MySQL.

i write function into Database() class like this where MySQLi run on constructor:

def add_user_to_database(self, id, first_name, last_name, username, lang_code):
    with self.MySQLi.cursor() as cursor:
        cursor.execute('INSERT INTO users (id, first_name, last_name, username, language_code) VALUES ({0}, {1}, {2}, {3}, {4})'.format(id, first_name, last_name, username, lang_code))
    connection.commit()

after i run py database.php it show this error :( :

    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' sepwhrr, en)' at line 1")

Body:
When you build a query with string interpolation, you can get escape/quoiting issues, however it's easy to use a parametrised query:

sql = "INSERT INTO `users` (`id`, `first_name`) VALUES (%s, %s)"
cursor.execute(sql, (id, first_name)


问:
Need help with While Loop
I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.

I need to create a script in Python using a while loop that does this:

```
zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza
```

Keep in mind that the script should be able to do this with any word.  For example, right now a = 'zebra'.  If a = 'cat' the the script should look like:

```
cat tac
atc cta
tca cat
```

I've figured out how to do it with a for loop...just can't figure out exactly how to implement it with a while loop.

My for loop:

```<code>a = 'zebra'
for i in range(len(a)):
    print a[i:] + a[:i], (a[i:] + a[:i])[::-1]
</code>```

If anyone could help me out, or give me hints...I'd really appreciate it!
thanks!

答:
The following code seems to work as well, but I am not sure if this is what your teacher wants</p>

```<code>a = 'zebra'
b=''
while a:
    print a+b, (a+b)[::-1]
    b+=a[0]
    a=a[1:]
</code>```

Title: Need help with While Loop

Body:
I am extremely new to programming so it's taking a lot to re-wire. my brain to think like a computer programmer.

I need to create a script in Python using a while loop that does this:

zebra arbez
ebraz zarbe
braze ezarb
razeb bezar
azebr rbeza

Keep in mind that the script should be able to do this with any word.  For example, right now a = 'zebra'.  If a = 'cat' the the script should look like:

cat tac
atc cta
tca cat

I've figured out how to do it with a for loop...just can't figure out exactly how to implement it with a while loop.

My for loop:

a = 'zebra'
for i in range(len(a)):
    print a[i:] + a[:i], (a[i:] + a[:i])[::-1]

If anyone could help me out, or give me hints...I'd really appreciate it!
thanks!

Body:
The following code seems to work as well, but I am not sure if this is what your teacher wants

a = 'zebra'
b=''
while a:
    print a+b, (a+b)[::-1]
    b+=a[0]
    a=a[1:]


问:
DbContext is not giving any data from database
I have two sets of codes. The first one doesn't give me the list of data but the second on does. Please see codes below:

First Code:
Model

```<code>public class Student
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}
</code>```

DataConnection

```<code>public class DataConnection : DbContext
{
    public DataConnection()
        : base("DefaultConnection")
    {

    }
    public DbSet<Student> Students { get; set; }
}
</code>```

Interface

```<code>public interface IStudent
{
    List<Student> StudentList();
    void InsertStudent(Student student);
    void UpdateStudent(Student student);
    Student GetStudentById(int id);
    void DeleteStudent(int id);
}
</code>```

Concrete

```<code>readonly DataConnection _context;

public StudentConcrete()
{
    _context = new DataConnection();
}

public List<Student> StudentList()
{
    var studentList = (from s in _context.Students select s).ToList();
    return studentList;
}
</code>```

Second Code
Concrete

```<code>readonly DataConnection _context;

public StudentConcrete()
{
_context = new DataConnection();
}

public List<Student> StudentList()
{
    SqlConnection xxx = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    var cmd = new SqlCommand("GetAllStudents", xxx);
    var da = new SqlDataAdapter(cmd);
    var ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
    {
        return (from DataRow row in ds.Tables[0].Rows
                select new Student()
                {
                    Age = Convert.ToInt32(row["Age"]),
                    FirstName = row["FirstName"].ToString(),
                    Gender = row["Gender"].ToString(),
                    LastName = row["LastName"].ToString()
                }).ToList();
    }
    else
    {
        return null;
    }

}
</code>```

I would like to get the data using the first code but I don't know where I get it wrong. My SP is just to get the students.

答:
I suspected that maybe you are retrieving the records from another table somehow. Would you try to add Table attribute for Student entity.

```<code>using System.ComponentModel.DataAnnotations.Schema;

[Table("Students")]
public class Student
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}
</code>```

Body:
I have two sets of codes. The first one doesn't give me the list of data but the second on does. Please see codes below:

First Code:
Model

public class Student
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}

DataConnection

public class DataConnection : DbContext
{
    public DataConnection()
        : base("DefaultConnection")
    {

    }
    public DbSet<Student> Students { get; set; }
}

Interface

public interface IStudent
{
    List<Student> StudentList();
    void InsertStudent(Student student);
    void UpdateStudent(Student student);
    Student GetStudentById(int id);
    void DeleteStudent(int id);
}

Concrete

readonly DataConnection _context;

public StudentConcrete()
{
    _context = new DataConnection();
}

public List<Student> StudentList()
{
    var studentList = (from s in _context.Students select s).ToList();
    return studentList;
}

Second Code
Concrete

readonly DataConnection _context;

public StudentConcrete()
{
_context = new DataConnection();
}

public List<Student> StudentList()
{
    SqlConnection xxx = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    var cmd = new SqlCommand("GetAllStudents", xxx);
    var da = new SqlDataAdapter(cmd);
    var ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
    {
        return (from DataRow row in ds.Tables[0].Rows
                select new Student()
                {
                    Age = Convert.ToInt32(row["Age"]),
                    FirstName = row["FirstName"].ToString(),
                    Gender = row["Gender"].ToString(),
                    LastName = row["LastName"].ToString()
                }).ToList();
    }
    else
    {
        return null;
    }

}

I would like to get the data using the first code but I don't know where I get it wrong. My SP is just to get the students.

Body:
I suspected that maybe you are retrieving the records from another table somehow. Would you try to add Table attribute for Student entity.

using System.ComponentModel.DataAnnotations.Schema;

[Table("Students")]
public class Student
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}


问:
VBA Code for disable the Right Click option in Excel for the current Workbook only
I have created multiple worksheets in my workbook.

I want to my users are not allowing to see the other sheets in excel.

Since I want to disable the right click option in Excel open event.

I have a piece of code:

```<code>Private Sub Workbook_SheetBeforeRightClick (ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    Cancel = True
    MsgBox ("Sorry Right Click is Disabled for this Workbook")
End Sub
</code>```

The above code runs only after opening the Workbook and run the Macro.

I want to disable right click option the Workbook when opening the Workbook.

答:
you can try the codes below: - Good Luck

```<code>Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.CommandBars("Ply").Enabled = True
End Sub
</code>```

And

```<code>Private Sub Workbook_Open()
    Application.CommandBars("Ply").Enabled = False
End Sub
</code>```

Body:
I have created multiple worksheets in my workbook.

I want to my users are not allowing to see the other sheets in excel.

Since I want to disable the right click option in Excel open event.

I have a piece of code:

Private Sub Workbook_SheetBeforeRightClick (ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    Cancel = True
    MsgBox ("Sorry Right Click is Disabled for this Workbook")
End Sub

The above code runs only after opening the Workbook and run the Macro.

I want to disable right click option the Workbook when opening the Workbook.

Body:
you can try the codes below: - Good Luck

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.CommandBars("Ply").Enabled = True
End Sub

And

Private Sub Workbook_Open()
    Application.CommandBars("Ply").Enabled = False
End Sub


问:
How can I keep a W3.CSS container margin consistent with a Bootsrap alert margin?
Question Information

Here I have a Bootstrap (Version 4.0.0 beta 2) alert with a margin of 5% on each side. I also have three W3.CSS cards nested inside a w3 container that are each 31% of the container size and a 1% margin on each side per card.

Desired Result:

I want the card's container to have a 5% margin on each side with each of the cards having a 1% margin in between each. So far the two cards on the left and right do not have the same margin with the alert on top.

Current Result:

Expected Result:

HTML:

```<code><div class="alert alert-success" role="alert" style="overflow: hidden;">
  This is the bootsrap alert I want the column's container to have the same 5% margin on both sides as.
</div>
<div class="w3-container">
  <div class="w3-panel w3-card w3-yellow">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis dapibus aliquam. Nam ornare mollis sodales. In mollis in elit ac eleifend. Integer ac volutpat nisl, id cursus lorem. Aenean pellentesque volutpat tortor in porttitor. Cras ultrices
      augue sit amet scelerisque hendrerit. Cras vel neque et justo posuere tempus volutpat pharetra lectus. Nam luctus condimentum bibendum.</p>
  </div>
  <div class="w3-panel w3-card-2 w3-yellow">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis dapibus aliquam. Nam ornare mollis sodales. In mollis in elit ac eleifend. Integer ac volutpat nisl, id cursus lorem. Aenean pellentesque volutpat tortor in porttitor. Cras ultrices
      augue sit amet scelerisque hendrerit. Cras vel neque et justo posuere tempus volutpat pharetra lectus. Nam luctus condimentum bibendum.</p>
  </div>
  <div class="w3-panel w3-card-4 w3-yellow">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis dapibus aliquam. Nam ornare mollis sodales. In mollis in elit ac eleifend. Integer ac volutpat nisl, id cursus lorem. Aenean pellentesque volutpat tortor in porttitor. Cras ultrices
      augue sit amet scelerisque hendrerit. Cras vel neque et justo posuere tempus volutpat pharetra lectus. Nam luctus condimentum bibendum.</p>
  </div>
</div>
</code>```

CSS:

```<code> .alert {
    margin-top: 10px;
    margin-right: 5%;
    margin-left: 5%;
    color: #fff;
    border: none;
    background-color: #2ecc71;
  }

  .w3-container {
    margin: 0 5%;
  }

  .w3-card,
  .w3-card-2,
  .w3-card-4 {
    float: left;
    width: 31%;
    margin: 0 1%;
    padding: 20px;
  }
</code>```

I have also provided a JSFiddle Demo

答:
Since you'r targeting the .w3-container, which is a parent of the w3-cards, you should be using padding instead of a margin:

```<code>.w3-container {
  padding: 0 4%;
}
</code>```

I've set 4% for the left/right padding because of the 1% left/right margin of the w3-cards.

I've also changed the width of the w3-cards to 31.33% for accuracy and to remove the undesired space.

Updated fiddle

Body:
Question Information

Here I have a Bootstrap (Version 4.0.0 beta 2) alert with a margin of 5% on each side. I also have three W3.CSS cards nested inside a w3 container that are each 31% of the container size and a 1% margin on each side per card.

Desired Result:

I want the card's container to have a 5% margin on each side with each of the cards having a 1% margin in between each. So far the two cards on the left and right do not have the same margin with the alert on top.

Current Result:

Expected Result:

HTML:

  This is the bootsrap alert I want the column's container to have the same 5% margin on both sides as.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis dapibus aliquam. Nam ornare mollis sodales. In mollis in elit ac eleifend. Integer ac volutpat nisl, id cursus lorem. Aenean pellentesque volutpat tortor in porttitor. Cras ultrices
      augue sit amet scelerisque hendrerit. Cras vel neque et justo posuere tempus volutpat pharetra lectus. Nam luctus condimentum bibendum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis dapibus aliquam. Nam ornare mollis sodales. In mollis in elit ac eleifend. Integer ac volutpat nisl, id cursus lorem. Aenean pellentesque volutpat tortor in porttitor. Cras ultrices
      augue sit amet scelerisque hendrerit. Cras vel neque et justo posuere tempus volutpat pharetra lectus. Nam luctus condimentum bibendum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis dapibus aliquam. Nam ornare mollis sodales. In mollis in elit ac eleifend. Integer ac volutpat nisl, id cursus lorem. Aenean pellentesque volutpat tortor in porttitor. Cras ultrices
      augue sit amet scelerisque hendrerit. Cras vel neque et justo posuere tempus volutpat pharetra lectus. Nam luctus condimentum bibendum.

CSS:

 .alert {
    margin-top: 10px;
    margin-right: 5%;
    margin-left: 5%;
    color: #fff;
    border: none;
    background-color: #2ecc71;
  }

  .w3-container {
    margin: 0 5%;
  }

  .w3-card,
  .w3-card-2,
  .w3-card-4 {
    float: left;
    width: 31%;
    margin: 0 1%;
    padding: 20px;
  }

I have also provided a JSFiddle Demo

Body:
Since you'r targeting the .w3-container, which is a parent of the w3-cards, you should be using padding instead of a margin:

.w3-container {
  padding: 0 4%;
}

I've set 4% for the left/right padding because of the 1% left/right margin of the w3-cards.

I've also changed the width of the w3-cards to 31.33% for accuracy and to remove the undesired space.

Updated fiddle


问:
Matrix with integer random rows
The command

```<code> matrix(sample.int(12, 9*12, TRUE), 9, 12)
</code>```

generates an integer random matrix (9 rows and 12 columns) with integer values from 1 to 12. I wonder if there is a version of this code that generates a matrix whose rows are integer random rows with value from 1 to 12 (without repetition). I was able to find a "trivial" answer to this question; with

```<code>matrix(sample.int(m, 1*12), 9, 12, byrow=TRUE)
</code>```

I obtain a matrix of this kind, but the rows are all equal to each other (this is the same row repeated 9 times).

Title: Matrix with integer random rows

Body:
The command

 matrix(sample.int(12, 9*12, TRUE), 9, 12)

generates an integer random matrix (9 rows and 12 columns) with integer values from 1 to 12. I wonder if there is a version of this code that generates a matrix whose rows are integer random rows with value from 1 to 12 (without repetition). I was able to find a "trivial" answer to this question; with

matrix(sample.int(m, 1*12), 9, 12, byrow=TRUE)

I obtain a matrix of this kind, but the rows are all equal to each other (this is the same row repeated 9 times).

Body:
The replicate function (which repeats an operation like sample(12) a specified number of times) returns a matrix whose column major orientation can be flipped to your desired row orientation with t:

t( replicate(9, {sample(12)} ) )
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]    9   11    5    3    4    6    2    8   10    12     7     1
 [2,]    4    5   12    6    8    2    9    1   11    10     7     3
 [3,]    9    8   10   12    2    6    3    7    4     1    11     5
 [4,]    4    9    1    2    6   11    8    5    7     3    12    10
 [5,]    1    2    4    5   11    6    3    8   10     9    12     7
 [6,]    4    8   10   12    5    9    2    7   11     1     3     6
 [7,]    5    7    8    4    1    6   10   11    2     3    12     9
 [8,]    2    4   10    1   12    5    7    6   11     3     8     9
 [9,]    2    7    9   11    8    1   12   10    6     5     3     4

The replicate function is used in a lot of simulation code.


问:
How do I automatically see incoming commits in Intellij IDEA with git?
We just switched from svn to git. The svn plugin in idea has this very nice feature to automatically check the repository for incoming commits every x minutes.

In the idea git plugin, I didn't find this feature - is this possible somehow to check my origin for new commits automatically and list them in the log?

(Would it make sense to automatically fetch the origin every x minutes with some automated workflow somehow?)

答:
You can check gittoolbox from jetbrain

Gittoolbox


问:
why using support vector machine?
I have some questions about SVM :
1- Why using SVM? or in other words,  what causes it to appear?
2- The state Of art (2017)
3- What improvements have they made?

答:
SVM works very well. In many applications, they are still among the best performing algorithms.

We've seen some progress in particular on linear SVMs, that can be trained much faster than kernel SVMs.

Read more literature. Don't expect an exhaustive answer in this QA format. Show more effort on your behalf.

Title: why using support vector machine?


问:
passing multidimensional arrays to function when the dimension size is not clear
I have a function in my class which should get a multi-dimensional array. the problem is that the value of these dimensions is calculated in the class, using another function and is stored in some public variables. so all the other functions within the class can read the value stored in these vars.
the definition of function is like this:

```<code>double calcSS(double tfpairexp[][max_ctrl_no][max_rep_no])
</code>```

where max_ctrl_no and max_rep_no are those public variables.
and I call the function like this:

```<code>calcSS(tfpairexp);
</code>```

but the compiler gives error for the definition of the function. and if I put some constant numbers instead of those vars, there is no error. But I don't know the dimension when the program begins.
what should I do?

Update

```<code>void tripleofgenes(int begind,int endind) {
            for (int tf1=0; tf1<tfact; ++tf1)
            {
                    for (int tf2=tf1+1; tf2<tfact; ++tf2)
                    {
                        double tfpairexp[cchips][max_ctrl_no][max_rep_no];
                        double w,d;
                        int ctrl_no;int c, ctr;
                        for (int j = 0; j < cchips ; j += c)
                        {
                            c = chips[j].crepls;
                            int ctrl_no=0;
                            for (int *p = chips[j].ctrl ; p && (ctr=*p)>=0; ++p,ctrl_no++) {
                                for (int k = 0; k < c; ++k)
                                {
                                    double tf1exp=chips[k+j].vals[tf1].val-((chips[k+j].useextra) ? chips[ctr].extra[tf1] : chips[ctr].mean[tf1].val);
                                    double tf2exp=chips[k+j].vals[tf2].val-((chips[k+j].useextra) ? chips[ctr].extra[tf2] : chips[ctr].mean[tf2].val);
                                    tfpairexp[j][ctrl_no][k]=interactionFunc(tf1exp,tf2exp,1);
                                }
                            }
                        }
                        for (int tg=begind; tg<=endind; ++tg)
                            if (tf1!=tg){

                        calcSS(tfpairexp);

                        }

                    }
            }
        fclose(f);
    }

    double calcSS(double ***tfpairexp)
    {
    for (int row = 0; row <= 1 ; row++)
                for (int col = 0; col <= 1 ; col++) {
                    int cond=0;
                    for (int j = 0; j < cchips; j += c) {
                        c = chips[j].crepls; // the number of replicants
                        int ctrl_no=0;
                        for (int *p = chips[j].ctrl; p && (ctr=*p)>=0; ++p,ctrl_no++) {
    a = tfpairexp[j][ctrl_no][k];}
    }
    }
    }
    }
</code>```

答:
```<code>double calcSS(double tfpairexp[][max_ctrl_no][max_rep_no])
</code>```

One solution is to change the function signature to,

```<code>double calcSS(double ***tfpairexp, int M, int N, int P);
</code>```

where M, N and P are dimensions of the arrray!

Or you can pass the instance of your class itself. After all, you've made the dimensions public in your class. And if this function is a member function of the class, then you don't even need to pass anything; you can access them from the function itself like this:

```<code>double calcSS(double ***tfpairexp)
{

      for(int i = 0 ; i < cchips ; i++ )
      {
           for(int j = 0 ; j < max_ctrl_no ; j++ )
          {
                for(int k = 0 ; k < max_rep_no ; k++ )
                {
                       //access elements as tfpairexp[i][j][k]
                }
          }
      }

}
</code>```

You can see this answer if it solves your problem: using a function template

Body:
I have a function in my class which should get a multi-dimensional array. the problem is that the value of these dimensions is calculated in the class, using another function and is stored in some public variables. so all the other functions within the class can read the value stored in these vars.
the definition of function is like this:

double calcSS(double tfpairexp[][max_ctrl_no][max_rep_no])

where max_ctrl_no and max_rep_no are those public variables.
and I call the function like this:

calcSS(tfpairexp);

but the compiler gives error for the definition of the function. and if I put some constant numbers instead of those vars, there is no error. But I don't know the dimension when the program begins.
what should I do?

Update

void tripleofgenes(int begind,int endind) {
            for (int tf1=0; tf1<tfact; ++tf1)
            {
                    for (int tf2=tf1+1; tf2<tfact; ++tf2)
                    {
                        double tfpairexp[cchips][max_ctrl_no][max_rep_no];
                        double w,d;
                        int ctrl_no;int c, ctr;
                        for (int j = 0; j < cchips ; j += c)
                        {
                            c = chips[j].crepls;
                            int ctrl_no=0;
                            for (int *p = chips[j].ctrl ; p && (ctr=*p)>=0; ++p,ctrl_no++) {
                                for (int k = 0; k < c; ++k)
                                {
                                    double tf1exp=chips[k+j].vals[tf1].val-((chips[k+j].useextra) ? chips[ctr].extra[tf1] : chips[ctr].mean[tf1].val);
                                    double tf2exp=chips[k+j].vals[tf2].val-((chips[k+j].useextra) ? chips[ctr].extra[tf2] : chips[ctr].mean[tf2].val);
                                    tfpairexp[j][ctrl_no][k]=interactionFunc(tf1exp,tf2exp,1);
                                }
                            }
                        }
                        for (int tg=begind; tg<=endind; ++tg)
                            if (tf1!=tg){

                        calcSS(tfpairexp);

                        }

                    }
            }
        fclose(f);
    }

    double calcSS(double ***tfpairexp)
    {
    for (int row = 0; row <= 1 ; row++)
                for (int col = 0; col <= 1 ; col++) {
                    int cond=0;
                    for (int j = 0; j < cchips; j += c) {
                        c = chips[j].crepls; // the number of replicants
                        int ctrl_no=0;
                        for (int *p = chips[j].ctrl; p && (ctr=*p)>=0; ++p,ctrl_no++) {
    a = tfpairexp[j][ctrl_no][k];}
    }
    }
    }
    }

Body:
double calcSS(double tfpairexp[][max_ctrl_no][max_rep_no])

One solution is to change the function signature to,

double calcSS(double ***tfpairexp, int M, int N, int P);

where M, N and P are dimensions of the arrray!

Or you can pass the instance of your class itself. After all, you've made the dimensions public in your class. And if this function is a member function of the class, then you don't even need to pass anything; you can access them from the function itself like this:

double calcSS(double ***tfpairexp)
{

      for(int i = 0 ; i < cchips ; i++ )
      {
           for(int j = 0 ; j < max_ctrl_no ; j++ )
          {
                for(int k = 0 ; k < max_rep_no ; k++ )
                {
                       //access elements as tfpairexp[i][j][k]
                }
          }
      }

}

You can see this answer if it solves your problem: using a function template


问:
PhotoPicker discovery error: Error Domain=PlugInKit Code=13
I'm trying to display an image from the photo library in a UIImageView

The full error is:

2017-06-09 21:55:59.063307+0200 firstapp2.0[12873:1120778] PhotoPicker
  discovery error: Error Domain=PlugInKit Code=13 "query cancelled"
  UserInfo={NSLocalizedDescription=query cancelled}

My code is included below:

```<code>import UIKit

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    @IBOutlet weak var pic: UIImageView!
    @IBOutlet weak var text: UILabel!

    var chosenImage : UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        pic.isUserInteractionEnabled = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any]) {
        var chosenImage = info[UIImagePickerControllerEditedImage]
        self.pic!.image = chosenImage as! UIImage
        picker.dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

    @IBAction func tap(_ sender: Any) {
        self.text.text = "Kreason"
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}
</code>```

答:
This might not be the most directly helpful answer - but hopefully it will help!  I'm 99% sure that this particular error message isn't actually pointing you to the real problem.  I spent hours pulling my hair out over this same exact issue.

1) I had authorization for photos printing to the console when I'd launch my picker, 2) I could navigate and pick a photo easy enough, and 3) when I would return me to my view upon dismissing the picker, my button image wasn't updated with the new photo... and the only hint that I had to the problem was the exact same error message that you are receiving.

Turns out I was hard-coding a placeholder image in ViewWillAppear instead of ViewDidLoad. Every time the picker was dismissing, it was calling ViewWillAppear and replacing my chosen image with my hard coded image.  I fixed that issue and sure enough - everything is working fine now... and I'm still seeing that error message every time I return from the picker.

I recommend looking somewhere other than the ImagePicker for your problem and you'll likely find it.

Body:
I'm trying to display an image from the photo library in a UIImageView

The full error is:

2017-06-09 21:55:59.063307+0200 firstapp2.0[12873:1120778] PhotoPicker
  discovery error: Error Domain=PlugInKit Code=13 "query cancelled"
  UserInfo={NSLocalizedDescription=query cancelled}

My code is included below:

import UIKit

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    @IBOutlet weak var pic: UIImageView!
    @IBOutlet weak var text: UILabel!

    var chosenImage : UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        pic.isUserInteractionEnabled = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any]) {
        var chosenImage = info[UIImagePickerControllerEditedImage]
        self.pic!.image = chosenImage as! UIImage
        picker.dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

    @IBAction func tap(_ sender: Any) {
        self.text.text = "Kreason"
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}


问:
Convert JSON array into CSV using jq
I have JSON file called temp.json.

```<code>{
  "users": [
    {
      "username": "jack",
      "email": "jack@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    },
    {
      "username": "jill",
      "email": "jill@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    }
  ]
}
</code>```

i want to convert this JSON into CSV lilke this,

```<code>username email              total running apps api-mock-app flogo ipaas nodejs-app
jack     jack@somewhere.com 1                  0            1     0     0
jill     jill@somewhere.com 1                  0            1     0     0
</code>```

I tried this

```<code>jq -r '.users[] | keys[0] [.username, .email, ."total running apps", ."api-mock-app", .flogo, .ipaas, ."nodejs-app"] | join(", ") | @csv' temp.json`
</code>```

But i am getting error

```<code>q: error (at temp.json:22): Cannot index string with string "jack"`
</code>```

Can anyone explain where am i making mistake and please let me know the correct answer.

答:
I tried this, and it worked perfectly,

```<code>jq -r '(.users[0] | keys), (.users[] | [.username, .email, ."total running apps", ."api-mock-app", .flogo, .ipaas, ."nodejs-app"]) | @csv' temp.json
</code>```

output format is.

```<code>"api-mock-app","email","flogo","ipaas","nodejs-app","total running apps","username"
"jack","jack@somewhere.com","1","0","1","0","0"
"jill","jill@somewhere.com","1","0","1","0","0"
</code>```

Title: Convert JSON array into CSV using jq

Body:
I have JSON file called temp.json.

{
  "users": [
    {
      "username": "jack",
      "email": "jack@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    },
    {
      "username": "jill",
      "email": "jill@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    }
  ]
}

i want to convert this JSON into CSV lilke this,

username email              total running apps api-mock-app flogo ipaas nodejs-app
jack     jack@somewhere.com 1                  0            1     0     0
jill     jill@somewhere.com 1                  0            1     0     0

I tried this

jq -r '.users[] | keys[0] [.username, .email, ."total running apps", ."api-mock-app", .flogo, .ipaas, ."nodejs-app"] | join(", ") | @csv' temp.json`

But i am getting error

q: error (at temp.json:22): Cannot index string with string "jack"`

Can anyone explain where am i making mistake and please let me know the correct answer.

Body:
I tried this, and it worked perfectly,

jq -r '(.users[0] | keys), (.users[] | [.username, .email, ."total running apps", ."api-mock-app", .flogo, .ipaas, ."nodejs-app"]) | @csv' temp.json

output format is.

"api-mock-app","email","flogo","ipaas","nodejs-app","total running apps","username"
"jack","jack@somewhere.com","1","0","1","0","0"
"jill","jill@somewhere.com","1","0","1","0","0"


问:
Is there a way to pass data from beforeSave() to afterSave() in cakePHP?
I am working in CakePHP. In the beforeSave() I am making a comparison of a column value in the database to the updated column value that is about to be saved. I would like to pass this data to the afterSave() callback to determine what the callback does. Is there a way to pass data from the beforeSave() to the afterSave()?

答:
You can pass arguments to your callbacks beforeSave(array $options = array()) and afterSave(boolean $created, array $options = array()) from the save(array $data = null, array $params = array()) function of the model.

Here is an example

```<code>//In your controller
$this->Post->save($data, array('arg1' => $value));

//In the Post Model
beforeSave($options = array()){
   // $options contains the arg1 param
}

afterSave($created, $options = array()){
   // $options contains the arg1 param
}
</code>```

Try it :)

Body:
You can pass arguments to your callbacks beforeSave(array $options = array()) and afterSave(boolean $created, array $options = array()) from the save(array $data = null, array $params = array()) function of the model.

Here is an example

//In your controller
$this->Post->save($data, array('arg1' => $value));

//In the Post Model
beforeSave($options = array()){
   // $options contains the arg1 param
}

afterSave($created, $options = array()){
   // $options contains the arg1 param
}

Try it :)


问:
Add last column in csv file
I have csv file with separator tab and I want modify each row with value. can I got the reference for this case? I already search in google but I can't get the good reference. what is the best practice? what kind of library java to use easily for this case? for example I have csv file contains:

```<code>value1 value2 value3
value4 value5 value6
value7 value8 value9
</code>```

and I want to modify become:

```<code>value1 value2 value3 new_value1
value4 value5 value6 new_value2
value7 value8 value9 new_value3
</code>```

and my csv file have around 10.000 rows. what kind of logic for effective to modify each row? thanks.

答:
If you are simply modifying each row and adding a new column with a tab separator, you can do something similar to the following by using BufferedReader and BufferedWriter : -

```<code>BufferedReader br=null;
BufferedWriter bw=null;

try {
    File file = new File("csv file path");
    File newfile = new File("new output csv file path");

    br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile)));

    String line = null;

    while((line = br.readLine())!=null){
        String addedColumn = "\t"+"newstring";
        bw.write(line+addedColumn+System.lineSeparator());
    }
} catch(Exception e){
    System.out.println(e);
} finally  {
    br.close();
    bw.close();
}
</code>```

If your new column text is changing on every row, keep modifying this code accordingly. Hope this helps.

Title: Add last column in csv file

Body:
I have csv file with separator tab and I want modify each row with value. can I got the reference for this case? I already search in google but I can't get the good reference. what is the best practice? what kind of library java to use easily for this case? for example I have csv file contains:

value1 value2 value3
value4 value5 value6
value7 value8 value9

and I want to modify become:

value1 value2 value3 new_value1
value4 value5 value6 new_value2
value7 value8 value9 new_value3

and my csv file have around 10.000 rows. what kind of logic for effective to modify each row? thanks.

Body:
If you are simply modifying each row and adding a new column with a tab separator, you can do something similar to the following by using BufferedReader and BufferedWriter : -

BufferedReader br=null;
BufferedWriter bw=null;

try {
    File file = new File("csv file path");
    File newfile = new File("new output csv file path");

    br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile)));

    String line = null;

    while((line = br.readLine())!=null){
        String addedColumn = "\t"+"newstring";
        bw.write(line+addedColumn+System.lineSeparator());
    }
} catch(Exception e){
    System.out.println(e);
} finally  {
    br.close();
    bw.close();
}

If your new column text is changing on every row, keep modifying this code accordingly. Hope this helps.


问:
NodeJS and MySQL. Why the field makes an error in the query statement?
Using NodeJS and MySQL I had an error in my query statement of database fields called user_name.

Why user_name makes an error and what is the solution?

```<code>function get_role(callback) {
    tempCont.query('SELECT * from `users` where `user_name` = ahmed' , function (error, results) {
        if (error) callback(null);
        callback(results[0].password);
        console.log("from query = " + results[0].password);
    });
}
</code>```

答:
You have a bare keyword (ahmed) which should be quoted:

```<code>function get_role(callback) {
    tempCont.query("SELECT * from `users` where `user_name` = 'ahmed'" , function (error, results) {
        if (error) callback(null);
        callback(results[0].password);
        console.log("from query = " + results[0].password);
    });
}
</code>```

Body:
Using NodeJS and MySQL I had an error in my query statement of database fields called user_name.

Why user_name makes an error and what is the solution?

function get_role(callback) {
    tempCont.query('SELECT * from `users` where `user_name` = ahmed' , function (error, results) {
        if (error) callback(null);
        callback(results[0].password);
        console.log("from query = " + results[0].password);
    });
}

Body:
You have a bare keyword (ahmed) which should be quoted:

function get_role(callback) {
    tempCont.query("SELECT * from `users` where `user_name` = 'ahmed'" , function (error, results) {
        if (error) callback(null);
        callback(results[0].password);
        console.log("from query = " + results[0].password);
    });
}


问:
What is a good .gitignore to use with Rails on Heroku?
What is a good .gitignore to use with Rails on Heroku?

```<code>*.log
*.sqlite3
</code>```

what else?

答:
https://github.com/github/gitignore/blob/master/Rails.gitignore

```<code>*.rbc
capybara-*.html
.rspec
/log
/tmp
/db/*.sqlite3
/db/*.sqlite3-journal
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
pickle-email-*.html

# TODO Comment out this rule if you are OK with secrets being uploaded to the repo
config/initializers/secret_token.rb

# Only include if you have production secrets in this file, which is no longer a Rails default
# config/secrets.yml

# dotenv
# TODO Comment out this rule if environment variables can be committed
.env

## Environment normalization:
/.bundle
/vendor/bundle

# these should all be checked in to normalize the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc

# if using bower-rails ignore default bower_components path bower.json files
/vendor/assets/bower_components
*.bowerrc
bower.json

# Ignore pow environment settings
.powenv

# Ignore Byebug command history file.
.byebug_history
</code>```

Body:
What is a good .gitignore to use with Rails on Heroku?

*.log
*.sqlite3

what else?

Body:
https://github.com/github/gitignore/blob/master/Rails.gitignore

*.rbc
capybara-*.html
.rspec
/log
/tmp
/db/*.sqlite3
/db/*.sqlite3-journal
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
pickle-email-*.html

# TODO Comment out this rule if you are OK with secrets being uploaded to the repo
config/initializers/secret_token.rb

# Only include if you have production secrets in this file, which is no longer a Rails default
# config/secrets.yml

# dotenv
# TODO Comment out this rule if environment variables can be committed
.env

## Environment normalization:
/.bundle
/vendor/bundle

# these should all be checked in to normalize the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc

# if using bower-rails ignore default bower_components path bower.json files
/vendor/assets/bower_components
*.bowerrc
bower.json

# Ignore pow environment settings
.powenv

# Ignore Byebug command history file.
.byebug_history