问:
TensorFlow DNNRegressor Retrieve Loss Values from Training Regressor
I would like to capture the loss value for every step that is output in the log when I train a tensorflow.estimator.DNNRegressor model.

Given the trivial nonsense example:

```<code>In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import tensorflow as tf
In [4]: X = pd.DataFrame({'X1':np.arange(1,10), 'X2':np.arange(11,20)})
In [5]: X
Out[5]:
   X1  X2
0   1  11
1   2  12
2   3  13
3   4  14
4   5  15
5   6  16
6   7  17
7   8  18
8   9  19

In [6]: y = pd.Series(np.arange(1,10)/2)
In [7]: feature_cols = [tf.feature_column.numeric_column(col)
                       for col in X.columns]

In [8]: regressor =
tf.estimator.DNNRegressor(feature_columns=feature_cols,
                          hidden_units=[3,3],
                          model_dir='mymodel')
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_tf_random_seed': 1,
'_save_checkpoints_secs': 600, '_log_step_count_steps': 100,
'_keep_checkpoint_max': 5, '_save_checkpoints_steps': None,
'_session_config': None, '_model_dir': 'mymodel',
'_keep_checkpoint_every_n_hours': 10000, '_save_summary_steps': 100}

In [9]: regressor.train(
          input_fn=tf.estimator.inputs.pandas_input_fn(
                                    x=X,
                                    y=y,
                                    num_epochs=None,
                                    shuffle=True),
                                    steps=1000)
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Saving checkpoints for 1 into mymodel/model.ckpt.
INFO:tensorflow:step = 1, loss = 1090.0
INFO:tensorflow:global_step/sec: 685.57
INFO:tensorflow:step = 101, loss = 580.524 (0.146 sec)
INFO:tensorflow:global_step/sec: 807.454
INFO:tensorflow:step = 201, loss = 423.964 (0.124 sec)
INFO:tensorflow:global_step/sec: 875.857
INFO:tensorflow:step = 301, loss = 353.421 (0.114 sec)
INFO:tensorflow:global_step/sec: 788.649
INFO:tensorflow:step = 401, loss = 297.249 (0.127 sec)
INFO:tensorflow:global_step/sec: 649.258
INFO:tensorflow:step = 501, loss = 254.237 (0.154 sec)
INFO:tensorflow:global_step/sec: 803.059
INFO:tensorflow:step = 601, loss = 303.544 (0.125 sec)
INFO:tensorflow:global_step/sec: 674.359
INFO:tensorflow:step = 701, loss = 234.27 (0.148 sec)
INFO:tensorflow:global_step/sec: 818.35
INFO:tensorflow:step = 801, loss = 259.353 (0.122 sec)
INFO:tensorflow:global_step/sec: 672.83
INFO:tensorflow:step = 901, loss = 208.319 (0.149 sec)
INFO:tensorflow:Saving checkpoints for 1000 into mymodel/model.ckpt.
INFO:tensorflow:Loss for final step: 200.45.
Out[9]: <tensorflow.python.estimator.canned.dnn.DNNRegressor at 0x1076d5470>
</code>```

So, in the output above I would like to capture the step = N, and loss = value so I can plot and otherwise further analyze it.

Appreciate any help here

答:
Ok, so I didn't necessarily figure out a way to retrieve the training loss values but, I did find a way to capture and plot the loss function values returned from the evaluate() function which pretty much gets me the info I need to determine if I am over fitting my data.

Staying consistent with my trivial example above it goes something like this.

```<code>In [1]: import tensorflow as tf
In [2]: from sklearn.model_selection import train_test_split
In [3]: import pandas as pd
In [4]: import numpy as np
In [5]: X = pd.DataFrame({'X1':np.arange(1,10), 'X2':np.arange(11,20)})
In [6]: y = pd.Series(np.arange(1,10)/2)
In [7]: X_train, X_validate, y_train, y_validate = train_test_split(X, y, test_size=0.2, random_state=23)
In [8]: feature_cols = [tf.feature_column.numeric_column(col)
...:                 for col in X.columns]
...:
In [9]: regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols,
...:                                     hidden_units=[3,3],
...:                                     model_dir='fake_model')
In [10]: validation_losses = []
In [11]: for _ in range(10):
...:      regressor.train(input_fn=tf.estimator.inputs.pandas_input_fn(
                   x=X_train,
                   y=y_train,
                   num_epochs=None,
                   shuffle=True), steps=10)
...:     validation_losses.append(regressor.evaluate(
             input_fn=tf.estimator.inputs.pandas_input_fn(
                 x=X_validate,
                 y=y_validate,
                 num_epochs=1,
                 shuffle=False)))
In [12]: import matplotlib.pyplot as plt
In [13]: losses = [l['loss'] for l in validation_losses]
In [14]: steps = [s for s in range(10)]
In [15]: plt.scatter(x=steps, y=losses)
Out[15]: <matplotlib.collections.PathCollection at 0x1114e7048>
In [16]: plt.show()
</code>```

Body:
I would like to capture the loss value for every step that is output in the log when I train a tensorflow.estimator.DNNRegressor model.

Given the trivial nonsense example:

In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: import tensorflow as tf
In [4]: X = pd.DataFrame({'X1':np.arange(1,10), 'X2':np.arange(11,20)})
In [5]: X
Out[5]:
   X1  X2
0   1  11
1   2  12
2   3  13
3   4  14
4   5  15
5   6  16
6   7  17
7   8  18
8   9  19

In [6]: y = pd.Series(np.arange(1,10)/2)
In [7]: feature_cols = [tf.feature_column.numeric_column(col)
                       for col in X.columns]

In [8]: regressor =
tf.estimator.DNNRegressor(feature_columns=feature_cols,
                          hidden_units=[3,3],
                          model_dir='mymodel')
INFO:tensorflow:Using default config.
INFO:tensorflow:Using config: {'_tf_random_seed': 1,
'_save_checkpoints_secs': 600, '_log_step_count_steps': 100,
'_keep_checkpoint_max': 5, '_save_checkpoints_steps': None,
'_session_config': None, '_model_dir': 'mymodel',
'_keep_checkpoint_every_n_hours': 10000, '_save_summary_steps': 100}

In [9]: regressor.train(
          input_fn=tf.estimator.inputs.pandas_input_fn(
                                    x=X,
                                    y=y,
                                    num_epochs=None,
                                    shuffle=True),
                                    steps=1000)
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Saving checkpoints for 1 into mymodel/model.ckpt.
INFO:tensorflow:step = 1, loss = 1090.0
INFO:tensorflow:global_step/sec: 685.57
INFO:tensorflow:step = 101, loss = 580.524 (0.146 sec)
INFO:tensorflow:global_step/sec: 807.454
INFO:tensorflow:step = 201, loss = 423.964 (0.124 sec)
INFO:tensorflow:global_step/sec: 875.857
INFO:tensorflow:step = 301, loss = 353.421 (0.114 sec)
INFO:tensorflow:global_step/sec: 788.649
INFO:tensorflow:step = 401, loss = 297.249 (0.127 sec)
INFO:tensorflow:global_step/sec: 649.258
INFO:tensorflow:step = 501, loss = 254.237 (0.154 sec)
INFO:tensorflow:global_step/sec: 803.059
INFO:tensorflow:step = 601, loss = 303.544 (0.125 sec)
INFO:tensorflow:global_step/sec: 674.359
INFO:tensorflow:step = 701, loss = 234.27 (0.148 sec)
INFO:tensorflow:global_step/sec: 818.35
INFO:tensorflow:step = 801, loss = 259.353 (0.122 sec)
INFO:tensorflow:global_step/sec: 672.83
INFO:tensorflow:step = 901, loss = 208.319 (0.149 sec)
INFO:tensorflow:Saving checkpoints for 1000 into mymodel/model.ckpt.
INFO:tensorflow:Loss for final step: 200.45.
Out[9]: <tensorflow.python.estimator.canned.dnn.DNNRegressor at 0x1076d5470>

So, in the output above I would like to capture the step = N, and loss = value so I can plot and otherwise further analyze it.

Appreciate any help here

Body:
Ok, so I didn't necessarily figure out a way to retrieve the training loss values but, I did find a way to capture and plot the loss function values returned from the evaluate() function which pretty much gets me the info I need to determine if I am over fitting my data.

Staying consistent with my trivial example above it goes something like this.

In [1]: import tensorflow as tf
In [2]: from sklearn.model_selection import train_test_split
In [3]: import pandas as pd
In [4]: import numpy as np
In [5]: X = pd.DataFrame({'X1':np.arange(1,10), 'X2':np.arange(11,20)})
In [6]: y = pd.Series(np.arange(1,10)/2)
In [7]: X_train, X_validate, y_train, y_validate = train_test_split(X, y, test_size=0.2, random_state=23)
In [8]: feature_cols = [tf.feature_column.numeric_column(col)
...:                 for col in X.columns]
...:
In [9]: regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols,
...:                                     hidden_units=[3,3],
...:                                     model_dir='fake_model')
In [10]: validation_losses = []
In [11]: for _ in range(10):
...:      regressor.train(input_fn=tf.estimator.inputs.pandas_input_fn(
                   x=X_train,
                   y=y_train,
                   num_epochs=None,
                   shuffle=True), steps=10)
...:     validation_losses.append(regressor.evaluate(
             input_fn=tf.estimator.inputs.pandas_input_fn(
                 x=X_validate,
                 y=y_validate,
                 num_epochs=1,
                 shuffle=False)))
In [12]: import matplotlib.pyplot as plt
In [13]: losses = [l['loss'] for l in validation_losses]
In [14]: steps = [s for s in range(10)]
In [15]: plt.scatter(x=steps, y=losses)
Out[15]: <matplotlib.collections.PathCollection at 0x1114e7048>
In [16]: plt.show()


来源: stackexchange

问:
Replace strings in a string by a substring of those strings
Let's say I have a string like this:

```<code>s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
</code>```

and I want to turn it into

```<code>'(xy09 and foobar or (abc123 and something))'
</code>```

then - in this particular case - I could simply do

```<code>s.replace('X_', "")
</code>```

which gives the desired output.

However, in my actual data there might be not only X_ but also other prefixes, so the above replace statement does not work.

What I would need instead is a replacement of

a capital letter followed by an underscore and an arbitrary sequence of letters and numbers

by

everything after the first underscore.

So, to extract the desired elements I could use:

```<code>import re
print(re.findall('[A-Z]{1}_[a-zA-Z0-9]+', s))
</code>```

which prints

```<code>['X_xy09', 'X_foobar', 'X_abc123', 'X_something']
</code>```

how can I now replace those elements so that I obtain

```<code>'(xy09 and foobar or (abc123 and something))'
</code>```

?

答:
If you just need to replace a capital letter followed by an underscore, you can use the regular expression r'[A-Z]_'.

```<code>s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
re.sub(r'[A-Z]_', '', s)
</code>```

You may need to add to it if you have other criteria not mentioned. (For example, some of your target values follow a word boundary and some follow parentheses.) The above might give you the wrong output if you have input like XY_something. It depends on what you expect the output to be.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have a string like this:

s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'

and I want to turn it into

'(xy09 and foobar or (abc123 and something))'

then - in this particular case - I could simply do

s.replace('X_', "")

which gives the desired output.

However, in my actual data there might be not only X_ but also other prefixes, so the above replace statement does not work.

What I would need instead is a replacement of

a capital letter followed by an underscore and an arbitrary sequence of letters and numbers

by

everything after the first underscore.

So, to extract the desired elements I could use:

import re
print(re.findall('[A-Z]{1}_[a-zA-Z0-9]+', s))

which prints

['X_xy09', 'X_foobar', 'X_abc123', 'X_something']

how can I now replace those elements so that I obtain

'(xy09 and foobar or (abc123 and something))'

?

Body:
If you just need to replace a capital letter followed by an underscore, you can use the regular expression r'[A-Z]_'.

s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
re.sub(r'[A-Z]_', '', s)

You may need to add to it if you have other criteria not mentioned. (For example, some of your target values follow a word boundary and some follow parentheses.) The above might give you the wrong output if you have input like XY_something. It depends on what you expect the output to be.


答:
If you need to remove an uppercase ASCII letter with an underscore after it, only when not preceded with a word char and when followed with an alphanumeric char, you may use

```<code>import re
s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
print(re.sub(r'\b[A-Z]_([a-zA-Z0-9])', r'\1', s))
</code>```

See the Python demo and a regex demo.

Pattern details

\b - a leading word boundary

[A-Z]_ - an ASCII uppercase letter and _

([a-zA-Z0-9]) - Group 1 (later referenced to with \1 from the replacement pattern): 1 alphanumeric char.

Title: Replace strings in a string by a substring of those strings

Body:
If you need to remove an uppercase ASCII letter with an underscore after it, only when not preceded with a word char and when followed with an alphanumeric char, you may use

import re
s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
print(re.sub(r'\b[A-Z]_([a-zA-Z0-9])', r'\1', s))

See the Python demo and a regex demo.

Pattern details

\b - a leading word boundary

[A-Z]_ - an ASCII uppercase letter and _

([a-zA-Z0-9]) - Group 1 (later referenced to with \1 from the replacement pattern): 1 alphanumeric char.


问:
How to pass country code when using jquery autocomplete plugin
i am using jquery auto complete to show country name when user type any character.
when user click button then i like to know how could i send country code to server side action instead of country name.

this is just a sample of jquery autocomplete.

```<code><input type="text" class="form-control" id="plugins" name="plugins" />

var myData =[
    {"name": "Afghanistan", "code": "AF"},
    {"name": "Aland Islands", "code": "AL"},
    {"name": "Bahamas", "code": "BM"},
    {"name": "Bahrain", "code": "BH"},
    {"name": "Cambodia", "code": "CM"},
    {"name": "Cameroon", "code": "CN"},
    {"name": "Zambia", "code": "ZA"},
    {"name": "Zimbabwe", "code": "ZB"}
];

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.toLowerCase().indexOf(req.term.toLowerCase()) == 0) {
          results.push(v.name)
          return;
        }
      });
      resp(results);
    },
        select: function( event , ui ) {
            alert( "You selected: " + ui.item.label+' values '+ ui.item.value );
            return false
        }
  });
});
</code>```

i know country code is not there in json. i will write there later country code in json. just tell me the way to send country code to action.

now issue is fixed. working version of jsfiddle is https://jsfiddle.net/urtkxo46/8/

答:
Try something like this:

$( function() {
    var projects = [
        {
            value: "1",
            label: "jQuery"
        },
        {
            value: "2",
            label: "jQuery UI"
        },
        {
            value: "3",
            label: "Sizzle JS"
        }
    ];

    $( "#project" ).autocomplete({
        minLength: 0,
        source: projects,
        focus: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            return false;
        },
        select: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            $( "#project-id" ).val( ui.item.value );
            return false;
        }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "
" )
        .append( "
" + item.label + "
" )
        .appendTo( ul );
    };
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="project-label">Select a project (type "j" for a start):</div>

<input id="project">

<input type="text" id="project-id">  <!-- change it to hidden and get its value --></code>```

Working Fiddle

Body:
i am using jquery auto complete to show country name when user type any character.
when user click button then i like to know how could i send country code to server side action instead of country name.

this is just a sample of jquery autocomplete.

<input type="text" class="form-control" id="plugins" name="plugins" />

var myData =[
    {"name": "Afghanistan", "code": "AF"},
    {"name": "Aland Islands", "code": "AL"},
    {"name": "Bahamas", "code": "BM"},
    {"name": "Bahrain", "code": "BH"},
    {"name": "Cambodia", "code": "CM"},
    {"name": "Cameroon", "code": "CN"},
    {"name": "Zambia", "code": "ZA"},
    {"name": "Zimbabwe", "code": "ZB"}
];

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.toLowerCase().indexOf(req.term.toLowerCase()) == 0) {
          results.push(v.name)
          return;
        }
      });
      resp(results);
    },
        select: function( event , ui ) {
            alert( "You selected: " + ui.item.label+' values '+ ui.item.value );
            return false
        }
  });
});

i know country code is not there in json. i will write there later country code in json. just tell me the way to send country code to action.

now issue is fixed. working version of jsfiddle is https://jsfiddle.net/urtkxo46/8/

Body:
Try something like this:

$( function() {
    var projects = [
        {
            value: "1",
            label: "jQuery"
        },
        {
            value: "2",
            label: "jQuery UI"
        },
        {
            value: "3",
            label: "Sizzle JS"
        }
    ];

    $( "#project" ).autocomplete({
        minLength: 0,
        source: projects,
        focus: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            return false;
        },
        select: function( event, ui ) {
            $( "#project" ).val( ui.item.label );
            $( "#project-id" ).val( ui.item.value );
            return false;
        }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<div>" + item.label + "</div>" )
        .appendTo( ul );
    };
  } );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="project-label">Select a project (type "j" for a start):</div>

<input id="project">

<input type="text" id="project-id">  <!-- change it to hidden and get its value -->

Working Fiddle


问:
How to create rhombus described on rectangle
Let's say I have a rectangle of width w and height h centered at coordinate origin. How I can create rhombus described on this rectangle? Additional requirement is that rhombus width should be twice as height.
Any ideas?</p>

答:
Clue: you need that rectangle corner point (w/2, h/2) belongs to segment (0, a)-(2*a, 0).

So write line equation for this segment, substitute corner coordinates into that equation, solve it for unknown a parameter (half of vertical diagonal of the rhombus)


问:
Why this thread is blocking my Android APP?
im making an Android app, i have a service, that update my local DB in background, by downloading data from the remote DB.

i have to put a thread on the service, because i dont know why, when i use a simple handle style bucle on the service it frozen my app during some secs when it is updating the local db. (i have my local db in a dbAdapter on MyApplication class)

OK, then i put a thread on the service, but i dont know why, if i start the service, the  thread of the service is frezzing my APP :S. it's suposed that when u use services and threads code is executed in background and doesnt froze nothing, but in this case is frezzing my app. ¿how to avoid it?

this is the code of my service:

```<code>public class MyServiceLocalDB extends Service implements Runnable{

RemoteConnection con; //conexion remota
//para almacenar la config local de mi app
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
boolean serviceStopped;

private static MyDbAdapter         mDb;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {

    serviceStopped=false;
    settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
    configEditor = settings.edit();
    con = new RemoteConnection();
    mDb = new MyDbAdapter(this);
    mDb.open();
}

@Override
public void onDestroy() {
    //player.stop();
    serviceStopped=true;
}

@Override
public void onStart(Intent intent, int startid) {
    //player.start();
    this.run();
}
public void updateDB()
{

    mDb.clearDB();
    List<Friend> myFriends=con.RetrieveFriends(settings.getString("login",""));
    List<Permission> myPermissions=con.RetrievePermissions(settings.getString("login",""));

    Permission p1 = null;
    for (int i=0;i<myFriends.size();i++)
    {
        mDb.createUser(myFriends.get(i).getEmail(),myFriends.get(i).getFullName(),myFriends.get(i).getMovilephone(),myFriends.get(i).getMovileOperatingSystem(),myFriends.get(i).getPermission());
        //p1=con.RetrievePermissionWithUser("pablo@upv.es", myFriends.get(i).getEmail());
    }
    for (int i=0;i<myPermissions.size();i++)
    {
        p1=myPermissions.get(i);
        String hour1=formatHourFromTime(p1.getHour1());
        String hour2=formatHourFromTime(p1.getHour2());
        mDb.createPermission(p1.getFk_email1(),p1.getFk_email2(),""+p1.getValidated(),hour1,hour2,p1.getDate1Formated(),p1.getDate2Formated(),""+p1.getWeekend(),p1.getFk_type());
        p1=null;
    }

    //MyApplication.getDatabaseAdapter().clearDB();
    MyApplication.setDatabaseAdapter(mDb);

}

public String formatHourFromTime(Time time)
{
    String hour1;
    if (time.getHours()<10)
        hour1="0"+time.getHours();
    else
        hour1=""+time.getHours();
    if (time.getMinutes()<10)
        hour1=hour1+":0"+time.getMinutes()+":00";
    else
        hour1=hour1+":"+time.getMinutes()+":00";
    return hour1;
}

public void run() {
    while (serviceStopped==false)
    {
        //handler.sendEmptyMessage(0);
        try {
           Thread.sleep(25000);// sleeps
        } catch (InterruptedException e) {}
        updateDB();
    }
}
</code>```

}

答:
The onStart is called by the OS on a main UI thread, that's why you got stuck there (you block the main UI thread in the run()). Instead of this.run(); you should start a new Thread here - new Thread(this).start();.

BTW, onStart is deprecated. Implement onStartCommand instead.

ContentLicense: CC BY-SA 2.5

Body:
im making an Android app, i have a service, that update my local DB in background, by downloading data from the remote DB.

i have to put a thread on the service, because i dont know why, when i use a simple handle style bucle on the service it frozen my app during some secs when it is updating the local db. (i have my local db in a dbAdapter on MyApplication class)

OK, then i put a thread on the service, but i dont know why, if i start the service, the  thread of the service is frezzing my APP :S. it's suposed that when u use services and threads code is executed in background and doesnt froze nothing, but in this case is frezzing my app. ¿how to avoid it?

this is the code of my service:

public class MyServiceLocalDB extends Service implements Runnable{

RemoteConnection con; //conexion remota
//para almacenar la config local de mi app
static SharedPreferences settings;
static SharedPreferences.Editor configEditor;
boolean serviceStopped;

private static MyDbAdapter         mDb;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {

    serviceStopped=false;
    settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
    configEditor = settings.edit();
    con = new RemoteConnection();
    mDb = new MyDbAdapter(this);
    mDb.open();
}

@Override
public void onDestroy() {
    //player.stop();
    serviceStopped=true;
}

@Override
public void onStart(Intent intent, int startid) {
    //player.start();
    this.run();
}
public void updateDB()
{

    mDb.clearDB();
    List<Friend> myFriends=con.RetrieveFriends(settings.getString("login",""));
    List<Permission> myPermissions=con.RetrievePermissions(settings.getString("login",""));

    Permission p1 = null;
    for (int i=0;i<myFriends.size();i++)
    {
        mDb.createUser(myFriends.get(i).getEmail(),myFriends.get(i).getFullName(),myFriends.get(i).getMovilephone(),myFriends.get(i).getMovileOperatingSystem(),myFriends.get(i).getPermission());
        //p1=con.RetrievePermissionWithUser("pablo@upv.es", myFriends.get(i).getEmail());
    }
    for (int i=0;i<myPermissions.size();i++)
    {
        p1=myPermissions.get(i);
        String hour1=formatHourFromTime(p1.getHour1());
        String hour2=formatHourFromTime(p1.getHour2());
        mDb.createPermission(p1.getFk_email1(),p1.getFk_email2(),""+p1.getValidated(),hour1,hour2,p1.getDate1Formated(),p1.getDate2Formated(),""+p1.getWeekend(),p1.getFk_type());
        p1=null;
    }

    //MyApplication.getDatabaseAdapter().clearDB();
    MyApplication.setDatabaseAdapter(mDb);

}

public String formatHourFromTime(Time time)
{
    String hour1;
    if (time.getHours()<10)
        hour1="0"+time.getHours();
    else
        hour1=""+time.getHours();
    if (time.getMinutes()<10)
        hour1=hour1+":0"+time.getMinutes()+":00";
    else
        hour1=hour1+":"+time.getMinutes()+":00";
    return hour1;
}

public void run() {
    while (serviceStopped==false)
    {
        //handler.sendEmptyMessage(0);
        try {
           Thread.sleep(25000);// sleeps
        } catch (InterruptedException e) {}
        updateDB();
    }
}

}


问:
SqlBulkCopy and SQL Server trigger Issues
I have following code in my application. I use SqlBulkCopy to upload Excel data into a SQL Server table. Now, I have a trigger on that table. I have changed my existing code like this but I am getting an error.

The error is

Argument 1: cannot convert from 'System.Data.SqlClient.SqlConnection' to 'string'

I changed the code as

```<code>oSqlBulk = new SqlBulkCopy("cn", SqlBulkCopyOptions.FireTriggers);
</code>```

Then I am getting an error

Format of the initialization string does not conform to specification starting at index 0.

Please check my code:

```<code>public static string ExecuteBulkCopy(string connectionString, string TableName, string Paths)
{
    SqlBulkCopy oSqlBulk = null;
    string error = null;

    OleDbConnection myExcelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " +
                       "Data Source=" + Paths +
                       ";Extended Properties=Excel 12.0;");

    try
    {
        myExcelConn.Open();

        // GET DATA FROM EXCEL SHEET.
        OleDbCommand objOleDB = new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);

        // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
        OleDbDataReader objBulkReader = null;
        objBulkReader = objOleDB.ExecuteReader();

        using (SqlConnection cn = new SqlConnection(connectionString))
        {
            // cn.Open();
            oSqlBulk = new SqlBulkCopy(cn,SqlBulkCopyOptions.FireTriggers);

            oSqlBulk.DestinationTableName = TableName; // TABLE NAME.
            oSqlBulk.WriteToServer(objBulkReader);
            // return 1;

            //call the overload that takes a connection in place of the connection string
            // return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
        }
    }
    catch (Exception ex)
    {
        error = ex.Message;
    }
    finally
    {
        oSqlBulk.Close();
        oSqlBulk = null;
        myExcelConn.Close();
        myExcelConn = null;
    }

    return error;
}
</code>```

答:
If you check the valid constructors for SqlBulkCopy:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.sqlbulkcopy(v=vs.110).aspx

You'll notice that the overload using SqlBulkCopyOptions does not accept SqlConnection directly.
Just the ConnectionString

Since SqlBulkCopy implements IDisposable

You should replace the SqlConnection entirely:

```<code>using (var oSqlBulk = new SqlBulkCopy(connectionString,SqlBulkCopyOptions.FireTriggers))
{
    oSqlBulk.DestinationTableName = TableName;
    oSqlBulk.WriteToServer(objBulkReader);
}
</code>```

Body:
I have following code in my application. I use SqlBulkCopy to upload Excel data into a SQL Server table. Now, I have a trigger on that table. I have changed my existing code like this but I am getting an error.

The error is

Argument 1: cannot convert from 'System.Data.SqlClient.SqlConnection' to 'string'

I changed the code as

oSqlBulk = new SqlBulkCopy("cn", SqlBulkCopyOptions.FireTriggers);

Then I am getting an error

Format of the initialization string does not conform to specification starting at index 0.

Please check my code:

public static string ExecuteBulkCopy(string connectionString, string TableName, string Paths)
{
    SqlBulkCopy oSqlBulk = null;
    string error = null;

    OleDbConnection myExcelConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; " +
                       "Data Source=" + Paths +
                       ";Extended Properties=Excel 12.0;");

    try
    {
        myExcelConn.Open();

        // GET DATA FROM EXCEL SHEET.
        OleDbCommand objOleDB = new OleDbCommand("SELECT *FROM [Sheet1$]", myExcelConn);

        // READ THE DATA EXTRACTED FROM THE EXCEL FILE.
        OleDbDataReader objBulkReader = null;
        objBulkReader = objOleDB.ExecuteReader();

        using (SqlConnection cn = new SqlConnection(connectionString))
        {
            // cn.Open();
            oSqlBulk = new SqlBulkCopy(cn,SqlBulkCopyOptions.FireTriggers);

            oSqlBulk.DestinationTableName = TableName; // TABLE NAME.
            oSqlBulk.WriteToServer(objBulkReader);
            // return 1;

            //call the overload that takes a connection in place of the connection string
            // return ExecuteNonQuery(cn, commandType, commandText, commandParameters);
        }
    }
    catch (Exception ex)
    {
        error = ex.Message;
    }
    finally
    {
        oSqlBulk.Close();
        oSqlBulk = null;
        myExcelConn.Close();
        myExcelConn = null;
    }

    return error;
}

Body:
If you check the valid constructors for SqlBulkCopy:
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.sqlbulkcopy(v=vs.110).aspx

You'll notice that the overload using SqlBulkCopyOptions does not accept SqlConnection directly.
Just the ConnectionString

Since SqlBulkCopy implements IDisposable

You should replace the SqlConnection entirely:

using (var oSqlBulk = new SqlBulkCopy(connectionString,SqlBulkCopyOptions.FireTriggers))
{
    oSqlBulk.DestinationTableName = TableName;
    oSqlBulk.WriteToServer(objBulkReader);
}


答:
jquery autocomplete can take an object with label value keys. just set the name as label and country code as value

var myData =[
    {"name": "Uganda", "code": "UG"},
    {"name": "Kenya", "code": "KY"},
    {"name": "Tanzania", "code": "TZ"},

];

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.toLowerCase().indexOf(req.term.toLowerCase()) == 0) {
          results.push({"label": v.name, "value": v.code})
          return;
        }
      });
      resp(results);
    },
    select: function( event, ui ) {
      alert(ui.item.label) //when selected the label shows in alert
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" class="form-control" id="plugins" name="plugins" /></code>```

Title: How to pass country code when using jquery autocomplete plugin

Body:
jquery autocomplete can take an object with label value keys. just set the name as label and country code as value

var myData =[
    {"name": "Uganda", "code": "UG"},
    {"name": "Kenya", "code": "KY"},
    {"name": "Tanzania", "code": "TZ"},

];

$(function() {
  $("#plugins").autocomplete({
    source: function(req, resp) {
      var results = [];
      $.each(myData, function(k, v) {
        // Make a pass for names
        if (v.name.toLowerCase().indexOf(req.term.toLowerCase()) == 0) {
          results.push({"label": v.name, "value": v.code})
          return;
        }
      });
      resp(results);
    },
    select: function( event, ui ) {
      alert(ui.item.label) //when selected the label shows in alert
    }
  });
});

<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" class="form-control" id="plugins" name="plugins" />


问:
Show hide multiple divs based on select value
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

```<code><form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div data-response="op1">
      This is content for option 1.
    </div>
    <div data-response="op2">
      This is content for option 2.
    </div>
    <div data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>
</code>```

答:
I have shown show/hide using Class . Initially hide all div's , shown on drop down selection (only matches div).Here is how.I have created two classes hide
to hide the element and show to show the element.

$('[data-response^=op]').attr('class',"hide");//Initially set all div hidden
$("#select-box").on("change",function(){
  var value = $(this).val();
  if(value !="" && value<=3 && value !=0){
    console.clear();// to clear older logs.
    console.log('Selected value'+$(this).val());
    $('[data-response^=op]').attr('class',"hide");//On change hide all div's
    var selector = "op"+value;
    $(document).find("[data-response='"+selector+"']").attr('class',"show");
    $("#other-questions").attr('class',"show");//Show matching div.
  }else{
   $("#other-questions").attr('class',"hide");
   $('[data-response^=op]').attr('class',"hide");
  }

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hide{
display:none;
}

.show{
display:block;
}</code>```

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>```

Body:
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>

Body:
I have shown show/hide using Class . Initially hide all div's , shown on drop down selection (only matches div).Here is how.I have created two classes hide
to hide the element and show to show the element.

$('[data-response^=op]').attr('class',"hide");//Initially set all div hidden
$("#select-box").on("change",function(){
  var value = $(this).val();
  if(value !="" && value<=3 && value !=0){
    console.clear();// to clear older logs.
    console.log('Selected value'+$(this).val());
    $('[data-response^=op]').attr('class',"hide");//On change hide all div's
    var selector = "op"+value;
    $(document).find("[data-response='"+selector+"']").attr('class',"show");
    $("#other-questions").attr('class',"show");//Show matching div.
  }else{
   $("#other-questions").attr('class',"hide");
   $('[data-response^=op]').attr('class',"hide");
  }

})

.hide{
display:none;
}

.show{
display:block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div data-response="op1">
      This is content for option 1.
    </div>
    <div data-response="op2">
      This is content for option 2.
    </div>
    <div data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions" class="hide">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>


问:
Ruby 2.3 - Add strings after and before certain regexp match
I have a string

```<code>text 6ffdfd <a href="http://worldnews.com" target="_blank">toto</a> sdsdsd
</code>```

I would like to find a regex that would

add a opening span tag just after the end of the a tag html link (that is to say to be precise after the string "target="_blank">"

add a closing span tag just before the a tag closing

The desired end result would be:

```<code> <a href="http://worldnews.com" target="_blank"><span>toto</span></a> sdsdsd
</code>```

For the moment , I don't find how to achieve 1, and I only partially managed 2. because my current code is wrongly adding white space that I don't want between /span and the closing a tag

Current code

```<code>orig_string = 'text 6ffdfd <a href="http://example.com" target="_blank">toto</a> sdsdsd'
end_result = orig_string.gsub(/<\/a>/, '</span> \\0')
print end_result
</code>```

I have a set up a online editable DEMO here: https://repl.it/repls/SecondCapitalPika

答:
```<code>orig_string =~ /(?<=>)([^<]*)(?=<\/a>)/
if $1.present?
  end_result = orig_strig.gsub(/(?<=>)([^<]*)(?=<\/a>)/, '<span>\1</span>')
end
</code>```

Break down

```<code>(?<=>) # to have character >  before
([^<]*) # match everything until character <, match everything in a tag
(?=<\/a>) # to have </a> after
</code>```

Will result in

```<code>print end_result
'text 6ffdfd <a href="http://example.com" target="_blank"><span>toto</span></a> sdsdsd'
</code>```

Body:
I have a string

text 6ffdfd toto sdsdsd

I would like to find a regex that would

add a opening span tag just after the end of the a tag html link (that is to say to be precise after the string "target="_blank">"

add a closing span tag just before the a tag closing

The desired end result would be:

 toto sdsdsd

For the moment , I don't find how to achieve 1, and I only partially managed 2. because my current code is wrongly adding white space that I don't want between /span and the closing a tag

Current code

orig_string = 'text 6ffdfd toto sdsdsd'
end_result = orig_string.gsub(/<\/a>/, ' \\0')
print end_result

I have a set up a online editable DEMO here: https://repl.it/repls/SecondCapitalPika

Body:
orig_string =~ /(?<=>)([^<]*)(?=<\/a>)/
if $1.present?
  end_result = orig_strig.gsub(/(?<=>)([^<]*)(?=<\/a>)/, '<span>\1</span>')
end

Break down

(?<=>) # to have character >  before
([^<]*) # match everything until character <, match everything in a tag
(?=<\/a>) # to have </a> after

Will result in

print end_result
'text 6ffdfd <a href="http://example.com" target="_blank"><span>toto</span></a> sdsdsd'


问:
Linux backup script won't run
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

```<code>TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/
</code>```

The cronjob is;

```<code>30 7 * * * /home/centos/backupfile/runbackup
</code>```

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?

答:
Have you tried to specify the user who executes the command? Like this: </p>

```<code># Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
30 7 * * * root /home/centos/backupfile/runbackup
</code>```

Title: Linux backup script won't run

Body:
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/

The cronjob is;

30 7 * * * /home/centos/backupfile/runbackup

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?

Body:
Have you tried to specify the user who executes the command? Like this:

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
30 7 * * * root /home/centos/backupfile/runbackup


问:
java - iterating a linked list
if I use a for-each loop on a linked list in java,
is it guaranteed that I will iterate on the elements in the order
in which they appear in the list?</p>

答:
Linked list is guaranteed to act in sequential order.

From the documentation

An ordered collection (also known as a
  sequence). The user of this interface
  has  precise control over where in the
  list each element is inserted. The
  user can  access elements by their
  integer index (position in the list),
  and search for  elements in the list.

iterator()
Returns an iterator over the elements in this list in proper sequence.

Title: java - iterating a linked list


问:
Set data type in the php excel in column level
I am using PHPExcel and using fromArray I have added the vales to the cells. Now I want to set the data type of certain cells as string.

Some columns are having specific type of values (e.g numeric or dates or text). Using string data type is more than enough for this purpose otherwise digits with length more than 12 are showing with exponential E and leading zeros are truncated .

I found how to set the data type per specific cell programmatically  when setting a value in a cell. However how is it possible to set a data-type in column level in the final spreadsheet (so new values entered by a user in Excel, are automatically in that type, e.g string so leading zeros are not truncated). Also I want to know in the function

```<code>$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '1234567890', PHPExcel_Cell_DataType::TYPE_STRING);
</code>```

after inserting the value first using fromArray and giving cell id and data type later in the function is possible

Or is there any method available to set data type as string like  we format the cell

```<code>$objPHPExcel->getActiveSheet()
->getStyle('A3:A123')
->getNumberFormat()
->setFormatCode('0000');
</code>```

I have tried the code

```<code>$worksheet->getCell('A1:A50')->setDataType(PHPExcel_Cell_DataType::TYPE_STRING);
</code>```

But it is not working

答:
Setting the datatype after setting the data won't change the data; it's type in real terms is defined when you call setCellValue() or setCellValueExplicit() in the first place.

If you are using setCellValueExplicit(), you're explicitly telling PHPExcel what datatype to use. If you use setCellValue(), you're telling PHPExcel to work out what datatype it should use. The rules for working this out are defined in a "Value Binder". The fromArray() method uses setCellValue(), so it uses the "Value binder" to identify datatypes, and sets the cell values accordingly. How this works is explained in the PHPExcel Documentation in the section on "Excel DataTypes".

Unless you have specified otherwise, PHPExcel uses rules in the the Default Value Binder, which contains some very basic and simple rules. The Library also provides an AdvancedValueBinder with more sophisticated rules, such as converting a string like 5% to a float value of 0.05 and setting a format mask for the cell so that it will still be displayed as 5%, in much the same way that MS Excel does. You can also create your own "Value Binder" with your own rules, and use that instead of the "Default Value Binder".

Body:
I am using PHPExcel and using fromArray I have added the vales to the cells. Now I want to set the data type of certain cells as string.

Some columns are having specific type of values (e.g numeric or dates or text). Using string data type is more than enough for this purpose otherwise digits with length more than 12 are showing with exponential E and leading zeros are truncated .

I found how to set the data type per specific cell programmatically  when setting a value in a cell. However how is it possible to set a data-type in column level in the final spreadsheet (so new values entered by a user in Excel, are automatically in that type, e.g string so leading zeros are not truncated). Also I want to know in the function

$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '1234567890', PHPExcel_Cell_DataType::TYPE_STRING);

after inserting the value first using fromArray and giving cell id and data type later in the function is possible

Or is there any method available to set data type as string like  we format the cell

$objPHPExcel->getActiveSheet()
->getStyle('A3:A123')
->getNumberFormat()
->setFormatCode('0000');

I have tried the code

$worksheet->getCell('A1:A50')->setDataType(PHPExcel_Cell_DataType::TYPE_STRING);

But it is not working


答:
If you don't necessarily need a regex, then you could use Nokogiri:</p>

```<code>require 'nokogiri'

text = <<-TEXT
  text 6ffdfd <a href="http://worldnews.com" target="_blank">toto</a> sdsdsd
  6ffdfd text <a href="http://worldnews.com" target="_blank">tete</a> sdsdsd
  6ffdfd text <a href="http://worldnews.com">titi</a> sdsdsd
TEXT

doc = Nokogiri.HTML text
doc.css('a[target="_blank"]').each { |anchor| anchor.add_next_sibling '<span>span</span>' }
</code>```

Title: Ruby 2.3 - Add strings after and before certain regexp match

Body:
If you don't necessarily need a regex, then you could use Nokogiri:

require 'nokogiri'

text = <<-TEXT
  text 6ffdfd <a href="http://worldnews.com" target="_blank">toto</a> sdsdsd
  6ffdfd text <a href="http://worldnews.com" target="_blank">tete</a> sdsdsd
  6ffdfd text <a href="http://worldnews.com">titi</a> sdsdsd
TEXT

doc = Nokogiri.HTML text
doc.css('a[target="_blank"]').each { |anchor| anchor.add_next_sibling '<span>span</span>' }


问:
Filling in hourly buckets of activity time - Python
I have a list of devices and their activity time (start time and end time). A device can have one or more activity logs. What I am trying to do is to create a distribution for each device of when the device was active.

My current dataframe looks something like this:

```<code>device_id start_time end_time
1 03:53 10:54
1 06:00 14:00
2 20:29 06:17
</code>```

To create a distribution of activity time for each device, I thought I would create hourly buckets (corresponding to hours from 00 to 23) and fill in the buckets where the device was active. So for device 1, for example, the first row would be

```<code>[0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]
</code>```

and the second row

```<code>[0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0]
</code>```

adding them up to create a distribution of activity for device 1 would give:

```<code>[0,0,0,1,1,1,2,2,2,2,2,1,1,1,1,0,0,0,0,0,0,0,0,0]
</code>```

I had the following attempt to create the needed lists, however, it only works if end time is greater than start time (e.g. the first two rows in the data sample above) and won't work for start time greater than end time (e.g. row 3 in the data sample above).

```<code>for start, end in zip(df[df['start_time'].notnull() & df['end_time'].notnull()]['start_time'],df[df['start_time'].notnull() & df['end_time'].notnull()]['end_time']) :
    start_time = pd.to_datetime(start, format ='%H:%M')
    end_time = pd.to_datetime(end, format ='%H:%M')
    activity = [0]*24
    i = (start_time + dt.timedelta(minutes=((start_time.minute // 60 + (1 if start_time.minute>30 else 0) ) * 60) - start_time.minute)).hour
    rounded_end_time = (end_time + dt.timedelta(minutes=((end_time.minute // 60 + (1 if end_time.minute>30 else 0) ) * 60) - end_time.minute)).hour
    while i < rounded_end_time:
        activity[i] = 1
        i = i + 1
    print activity
</code>```

Any suggestions for a fix? (or a smarter way to accomplish the task in the first place?)

答:
Taking rows of start/end times and binning them into time buckets (total duration of minutes in this case)

Note: not all edge cases have been covered but you can expand on the code if you find it useful

```<code>#your imports
import numpy as np
import pandas as pd
from pandas.tseries.offsets import Hour, Minute
#optional
from IPython.core.debugger import set_trace

# construct a sample raw data dataframe
start_times = ['2000-01-01 09:00', '2000-01-01 10:00']
end_times = ['2000-01-01 17:00', '2000-01-01 18:00']
index = ['Timeframe ' + str(i) for i in range(len(start_times))]
df = pd.DataFrame({'Start Time': pd.to_datetime(start_times),
              'End Time' : pd.to_datetime(end_times)}, index=index)
</code>```

The dataframe df will look similar to below

```<code>               End Time               Start Time
</code>```

Timeframe 0   2000-01-01 17:00:00   2000-01-01 09:00:00

Timeframe 1   2000-01-01 18:00:00   2000-01-01 10:00:00

```<code>#Construct your dataframe for time buckets
rng = pd.date_range('2000-01-01 09:00', periods=9, freq='H')
ts = pd.DataFrame(0, index=rng, columns=['minutes'], dtype='float')
</code>```

The dataframe ts will look similar to below

```<code>                     minutes
</code>```

2000-01-01 09:00:00   0.0

2000-01-01 10:00:00   0.0

2000-01-01 11:00:00   0.0

2000-01-01 12:00:00   0.0

2000-01-01 13:00:00   0.0

2000-01-01 14:00:00   0.0

2000-01-01 15:00:00   0.0

2000-01-01 16:00:00   0.0

2000-01-01 17:00:00   0.0

```<code>for index, row in ts.iterrows():
    #set_trace()
    start_boundary = index
    end_boundary = index + Hour()
    time_count = pd.Timedelta('0 m')
        for _, raw_data in df.iterrows():
            #set_trace()
            start_time = raw_data['Start Time']
            end_time = raw_data['End Time']
            if end_time > start_boundary:
                if start_time < end_boundary:
                    if start_time <= start_boundary:
                        if end_time >= end_boundary:
                            time_count = time_count + (end_boundary - start_boundary)
                        else:
                            time_count = time + (end_time - start_boundary)
                    else:
                        if end_time >= end_boundary:
                            time_count = time_count + (end_boundary - start_time)
                        else:
                            time_count = time_count + (end_time - start_time)
    #set_trace()
    ts.at[index, 'minutes'] = time_count.seconds / 60
</code>```

Run the code above and your ts dataframe (see below) should have total duration in minutes binned based on the raw data in the df dataframe

```<code>                     minutes
</code>```

2000-01-01 09:00:00   60.0

2000-01-01 10:00:00   120.0

2000-01-01 11:00:00   120.0

2000-01-01 12:00:00   120.0

2000-01-01 13:00:00   120.0

2000-01-01 14:00:00   120.0

2000-01-01 15:00:00   120.0

2000-01-01 16:00:00   120.0

2000-01-01 17:00:00   60.0

Body:
I have a list of devices and their activity time (start time and end time). A device can have one or more activity logs. What I am trying to do is to create a distribution for each device of when the device was active.

My current dataframe looks something like this:

device_id start_time end_time
1 03:53 10:54
1 06:00 14:00
2 20:29 06:17

To create a distribution of activity time for each device, I thought I would create hourly buckets (corresponding to hours from 00 to 23) and fill in the buckets where the device was active. So for device 1, for example, the first row would be

[0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]

and the second row

[0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0]

adding them up to create a distribution of activity for device 1 would give:

[0,0,0,1,1,1,2,2,2,2,2,1,1,1,1,0,0,0,0,0,0,0,0,0]

I had the following attempt to create the needed lists, however, it only works if end time is greater than start time (e.g. the first two rows in the data sample above) and won't work for start time greater than end time (e.g. row 3 in the data sample above).

for start, end in zip(df[df['start_time'].notnull() & df['end_time'].notnull()]['start_time'],df[df['start_time'].notnull() & df['end_time'].notnull()]['end_time']) :
    start_time = pd.to_datetime(start, format ='%H:%M')
    end_time = pd.to_datetime(end, format ='%H:%M')
    activity = [0]*24
    i = (start_time + dt.timedelta(minutes=((start_time.minute // 60 + (1 if start_time.minute>30 else 0) ) * 60) - start_time.minute)).hour
    rounded_end_time = (end_time + dt.timedelta(minutes=((end_time.minute // 60 + (1 if end_time.minute>30 else 0) ) * 60) - end_time.minute)).hour
    while i < rounded_end_time:
        activity[i] = 1
        i = i + 1
    print activity

Any suggestions for a fix? (or a smarter way to accomplish the task in the first place?)

Body:
Taking rows of start/end times and binning them into time buckets (total duration of minutes in this case)

Note: not all edge cases have been covered but you can expand on the code if you find it useful

#your imports
import numpy as np
import pandas as pd
from pandas.tseries.offsets import Hour, Minute
#optional
from IPython.core.debugger import set_trace

# construct a sample raw data dataframe
start_times = ['2000-01-01 09:00', '2000-01-01 10:00']
end_times = ['2000-01-01 17:00', '2000-01-01 18:00']
index = ['Timeframe ' + str(i) for i in range(len(start_times))]
df = pd.DataFrame({'Start Time': pd.to_datetime(start_times),
              'End Time' : pd.to_datetime(end_times)}, index=index)

The dataframe df will look similar to below

               End Time               Start Time

Timeframe 0   2000-01-01 17:00:00   2000-01-01 09:00:00

Timeframe 1   2000-01-01 18:00:00   2000-01-01 10:00:00

#Construct your dataframe for time buckets
rng = pd.date_range('2000-01-01 09:00', periods=9, freq='H')
ts = pd.DataFrame(0, index=rng, columns=['minutes'], dtype='float')

The dataframe ts will look similar to below

                     minutes

2000-01-01 09:00:00   0.0

2000-01-01 10:00:00   0.0

2000-01-01 11:00:00   0.0

2000-01-01 12:00:00   0.0

2000-01-01 13:00:00   0.0

2000-01-01 14:00:00   0.0

2000-01-01 15:00:00   0.0

2000-01-01 16:00:00   0.0

2000-01-01 17:00:00   0.0

for index, row in ts.iterrows():
    #set_trace()
    start_boundary = index
    end_boundary = index + Hour()
    time_count = pd.Timedelta('0 m')
        for _, raw_data in df.iterrows():
            #set_trace()
            start_time = raw_data['Start Time']
            end_time = raw_data['End Time']
            if end_time > start_boundary:
                if start_time < end_boundary:
                    if start_time <= start_boundary:
                        if end_time >= end_boundary:
                            time_count = time_count + (end_boundary - start_boundary)
                        else:
                            time_count = time + (end_time - start_boundary)
                    else:
                        if end_time >= end_boundary:
                            time_count = time_count + (end_boundary - start_time)
                        else:
                            time_count = time_count + (end_time - start_time)
    #set_trace()
    ts.at[index, 'minutes'] = time_count.seconds / 60

Run the code above and your ts dataframe (see below) should have total duration in minutes binned based on the raw data in the df dataframe

                     minutes

2000-01-01 09:00:00   60.0

2000-01-01 10:00:00   120.0

2000-01-01 11:00:00   120.0

2000-01-01 12:00:00   120.0

2000-01-01 13:00:00   120.0

2000-01-01 14:00:00   120.0

2000-01-01 15:00:00   120.0

2000-01-01 16:00:00   120.0

2000-01-01 17:00:00   60.0


问:
Mac not opening .jar files
I am trying to download a few programs that are written in java and have the extension of .jar.

I am having two types of failures:

The Java program launches (I can see it launched from applications) but nothing displays.

The Java Jar file "..." could not be launched. Check the console for possible error messages

This is the message I receive in the console:

I can't see an error being displayed but what do you think it is saying?

New Error:

```<code>Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1328)
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1303)
    at java.desktop/javax.swing.SwingUtilities.invokeAndWait(SwingUtilities.java:1475)
    at com.epicbot.iIIiiIiiIIiIi.main(ihc:263)
    at com.epicbot.Boot.main(imc:404)
Caused by: java.lang.NoClassDefFoundError: com/apple/eawt/QuitHandler
    at com.epicbot.IIIiIIiiiIIIi.ALLATORIxDEMO(dzb:459)
    at com.epicbot.iiIIIIiiiIIiI.run(ihc:315)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:303)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.desktop/java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:717)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:711)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:89)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:199)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: com.apple.eawt.QuitHandler
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
</code>```

答:
It means, that your current java does not support the used methods in the jar.

These methods were removed:

https://docs.oracle.com/javase/9/migrate/toc.htm#JSMIG-GUID-97C1D0BB-D5D3-4CAD-B17D-03A87A0AAF3B

Maybe you can try to install an older JRE and try again

See more informations about installing JRE here: https://www.java.com/en/download/faq/java_mac.xml

Title: Mac not opening .jar files

Body:
I am trying to download a few programs that are written in java and have the extension of .jar.

I am having two types of failures:

The Java program launches (I can see it launched from applications) but nothing displays.

The Java Jar file "..." could not be launched. Check the console for possible error messages

This is the message I receive in the console:

I can't see an error being displayed but what do you think it is saying?

New Error:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1328)
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1303)
    at java.desktop/javax.swing.SwingUtilities.invokeAndWait(SwingUtilities.java:1475)
    at com.epicbot.iIIiiIiiIIiIi.main(ihc:263)
    at com.epicbot.Boot.main(imc:404)
Caused by: java.lang.NoClassDefFoundError: com/apple/eawt/QuitHandler
    at com.epicbot.IIIiIIiiiIIIi.ALLATORIxDEMO(dzb:459)
    at com.epicbot.iiIIIIiiiIIiI.run(ihc:315)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:303)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    at java.desktop/java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:717)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:711)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:89)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:199)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: com.apple.eawt.QuitHandler
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)


问:
New line in react
I'm trying to send following code to a child component in React js:

```<code>{
    carPhoto: "../../images/small-logo.jpg",
    make: "Mercedes",
    price: "€20000",
    desc: "Vivamus gravida magna massa in cursus mi"
}
</code>```

Now I'm trying to split desc in two lines.
I tried with \n, \r, \r\n

```<code>desc: "Vivamus gravida magna<br /> massa in cursus mi"
desc: "Vivamus gravida magna\nmassa in cursus mi"
desc: "Vivamus gravida magna\r\nmassa in cursus mi"
</code>```

But nothing worked. Any advice?

答:
```<code><span>
 Example #1: <br /> newline
</span>
<span style={{ whiteSpace: 'pre-wrap' }}>
 {"Example #2: \r new line or \u000A new line"}
</span>
{/* do not forget add style { white-space: pre-wrap } */}
<Example3 text={"Example #2: \r new line or \u000A new line"} />
</code>```

Title: New line in react

Body:
I'm trying to send following code to a child component in React js:

{
    carPhoto: "../../images/small-logo.jpg",
    make: "Mercedes",
    price: "€20000",
    desc: "Vivamus gravida magna massa in cursus mi"
}

Now I'm trying to split desc in two lines.
I tried with \n, \r, \r\n

desc: "Vivamus gravida magna
 massa in cursus mi"
desc: "Vivamus gravida magna\nmassa in cursus mi"
desc: "Vivamus gravida magna\r\nmassa in cursus mi"

But nothing worked. Any advice?


问:
How to calculate what the sum of these Strings is?
```<code>import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Num2 = "2"
print ("som:", Num1 , Operator , Num2, "= ")
</code>```

I created some variables, one of which is an operator, I printed but now I have to calculate it...
I tried using eval(), but I could not get this to work.

How would I calculate this sum?

答:
In this particular case, you can indeed use eval, although in general you want to avoid using it if possible, as there is no safety check on what string expressions are executed.

Your exercise is s = Num1+Operator+Num2. You can do eval(s) either by intermediate declaration of the string s, or by typing its right-hand-side into the eval..

ContentLicense: CC BY-SA 4.0

Body:
import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Num2 = "2"
print ("som:", Num1 , Operator , Num2, "= ")

I created some variables, one of which is an operator, I printed but now I have to calculate it...
I tried using eval(), but I could not get this to work.

How would I calculate this sum?


问:
How to apply margin-top to card element but not to the entire container-fluid
I'm trying to make this container have a different background picture, but doing margin top to the card element moves everything along the picture. Here's my code using Bootstrap4:

#card.container-fluid {
  background-image: url("../images/picture2.jpg");
  background-position: 12em;
  background-size: cover;
  margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="jumbotron jumbotron-billboard">
  <div class="img"></div>
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1>title</h1>
        <div>
          <a>link</a>
          <a>lnk</a>
          <a>link</a>
          <a>link</a>
          <a>link</a>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="container-fluid" id="card">
  <div class="card" style="width: 50%">
    <div class="card-body" id="bod">
      <h4 class="card-title">title</h4>
      <p class="card-text" style="text-align: justify;">
        text text tex
      </p>
    </div>
    <img class="card-img-bottom" src="image1.jpg" alt="Card image" style="width:100%">
  </div>
</div></code>```

I've tried applying margin-top to .card, to #bod.card, but keeps moving the image as well, thank you in advance!

答:
There are more solutions, you can use for example padding.</p>

```<code>#card.container-fluid {padding-top: 20px;}
</code>```

Body:
I'm trying to make this container have a different background picture, but doing margin top to the card element moves everything along the picture. Here's my code using Bootstrap4:

#card.container-fluid {
  background-image: url("../images/picture2.jpg");
  background-position: 12em;
  background-size: cover;
  margin-bottom: 20px;
}

title

          link
          lnk
          link
          link
          link

title

        text text tex

I've tried applying margin-top to .card, to #bod.card, but keeps moving the image as well, thank you in advance!

Body:
There are more solutions, you can use for example padding.

#card.container-fluid {padding-top: 20px;}


问:
Centimeter to pixel
How do I convert centimeter to pixel in c# ?</p>

答:
Pixel and centimeter are two different Units they are calculated according to the User's DPI setting. To convert correctly you need to know the DPI of the User Screen.

If you have a 12.8 centimeter display showing a 1280x1024 image, then
you have 100 pixels per centimeter.

However you can try using the Graphics.TransformPoints to convert from pixel to cm or opposite.

Title: Centimeter to pixel


问:
Override footernavigationcomponent with addons
I have the footernavigationcomponent.jsp and I want to override it with my hybris addon. But I can't find the controller or the impex file where it is referenced.

Do you know where it is referenced?

答:
The impex which includes the footer component is

/merchandiseinitialdata/resources/merchandiseinitialdata/import/sampledata/contentCatalogs/catalogName/cms-content.impex

The controller that is referenced is determined by a complex algorithm. The controller for the footer component is the DefaultCMSComponentController.


问:
Distinguish between validation exception and Unhandled error in stored procedure
I had written many stored procedures for my application. Some stored procedures return validation exceptions as per project requirement, while in some cases stored procedure return unhandled fatal errors such as

"Foreign key reference error", "expects parameter which was not supplied" etc.

Now I need to distinguish between those errors in my C# code. In case of unhandled fatal errors, I need to insert error log in database.

Any suggestion on how to distinguish between these two types.

NOTE : I am returning validation exceptions using RAISERROR statement like

RAISERROR(@ErrorMsg,16,1)

UPDATE 1:

I guess everyone falsely interprets my actual issue.
I may get either user defined validation exception (returned by RAISERROR stmt) OR fatal error from query execution within SP. I need to distinguish between these two types at my C# code. Both exceptions are caught in

```<code>catch (SqlException ex)
</code>```

block. After some research, I found that ex.Number is 50000 in case of user defined validation exception and in other cases, it is different.

I am thinking of writing condition on that. If any cleaner approach that this, please suggest.

答:
you should set the value of the id for this statement.

This error occurred, because the Id of the foreign key is being excluded or beacuse the id isn't insert on the statement

Body:
I had written many stored procedures for my application. Some stored procedures return validation exceptions as per project requirement, while in some cases stored procedure return unhandled fatal errors such as

"Foreign key reference error", "expects parameter which was not supplied" etc.

Now I need to distinguish between those errors in my C# code. In case of unhandled fatal errors, I need to insert error log in database.

Any suggestion on how to distinguish between these two types.

NOTE : I am returning validation exceptions using RAISERROR statement like

RAISERROR(@ErrorMsg,16,1)

UPDATE 1:

I guess everyone falsely interprets my actual issue.
I may get either user defined validation exception (returned by RAISERROR stmt) OR fatal error from query execution within SP. I need to distinguish between these two types at my C# code. Both exceptions are caught in

catch (SqlException ex)

block. After some research, I found that ex.Number is 50000 in case of user defined validation exception and in other cases, it is different.

I am thinking of writing condition on that. If any cleaner approach that this, please suggest.


问:
Gson deserialize LinkedHashmap with nested Objects
I want to deserialize my Json String with Gson. But deserializing my Json throws me the following error:

Unable to invoke no-args constructor for interface javax.faces.event.BehaviorListener. Registering an InstanceCreator with Gson for this type may fix this problem.

I created the String already with Gson so there should be all the necessary Data.

I have an LinkedHashmap containing an interface of a few different fields. I already wrote a custom serializer and my json code looks alright. Two of my subclasses use an AjaxBehavior(Listener) and I think this is the problem.

I tried creating an InstanceCreator of my subclasses and of the AjaxBehavior, but both did not change anything.

In the following: FormField is my Interface, formMap is my LinkedHashmap with all data (working). formFields should be a clone of formMap after deserialization works. When everything works formMap will not be there and formFields should be filled from an external Json.

```<code>GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(FormField.class, new FormFieldDeserializer());
builder.registerTypeAdapter(FormField.class, new FormFieldSerializer());
builder.registerTypeAdapter(AjaxBehavior.class, new BehaviorListenerInstanceCreator());
builder.registerTypeAdapter(FormField.class, new CalendarInstanceCreator());
builder.setPrettyPrinting();
Gson gson = builder.create();

String myJson = gson.toJson(formMap);
System.out.println(myJson);

Type listType = new TypeToken<LinkedHashMap<String, FormField>>(){}.getType();
formFields = gson.fromJson(myJson, listType);
</code>```

Two of my subclasses use the AjaxBehavior:

```<code>public class CalendarField extends FormField {
    private AjaxBehavior ajax;

    private void setupAjax() {
        FacesContext context = FacesContext.getCurrentInstance();

        ajax = (AjaxBehavior) context.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
        ajax.addAjaxBehaviorListener(new InputListener());
        ajax.setTransient(true);
    }
</code>```

And I tried to make an InstanceCreator for it:

```<code>public class BehaviorListenerInstanceCreator implements InstanceCreator<AjaxBehavior> {
    @Override
    public AjaxBehavior createInstance(Type type) {
        FacesContext context = FacesContext.getCurrentInstance();
        AjaxBehavior ajax;
        ajax = (AjaxBehavior) context.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
        ajax.addAjaxBehaviorListener(new InputListener());
        ajax.setTransient(true);

        return ajax;
    }
}
</code>```

What can I do, to get my objects back in the LinkedHashmap?

My JSON looks like this:

```<code>{
  "MyCal": {
    "type": "CalendarField",
    "ajax": {
      "listeners": [
        {}
      ],
      "transientFlag": true,
      "initialState": false
    },
    "id": "MyCal",
    "label": "Mein Datum",
    "FromTo": false
  },
  "MyNumber": {
    "type": "NumberField",
    "IsYear": false,
    "mask": "999?99",
    "ajax": {
      "listeners": [
        {}
      ],
      "transientFlag": true,
      "initialState": false
    },
    "id": "MyNumber",
    "label": "Eine Nummer",
    "FromTo": false
  },
....
</code>```

答:
I found a solution for my problem.

I have to create a TypeAdapter not for AjaxBehavior but for BehaviorListener

```<code>builder.registerTypeAdapter(BehaviorListener.class, new BehaviorListenerInstanceCreator());
</code>```

And inside I return an object of InputListener (subclass of BehaviorListener). The problem was that he wanted to create an object of BehaviorListener, which is an interface, so he crashed.

```<code>public class BehaviorListenerInstanceCreator implements InstanceCreator<BehaviorListener> {
    @Override
    public BehaviorListener createInstance(Type type) {
        InputListener ajax = new InputListener();

        return ajax;
    }
}
</code>```

Maybe someone can use this information ;)

Body:
I want to deserialize my Json String with Gson. But deserializing my Json throws me the following error:

Unable to invoke no-args constructor for interface javax.faces.event.BehaviorListener. Registering an InstanceCreator with Gson for this type may fix this problem.

I created the String already with Gson so there should be all the necessary Data.

I have an LinkedHashmap containing an interface of a few different fields. I already wrote a custom serializer and my json code looks alright. Two of my subclasses use an AjaxBehavior(Listener) and I think this is the problem.

I tried creating an InstanceCreator of my subclasses and of the AjaxBehavior, but both did not change anything.

In the following: FormField is my Interface, formMap is my LinkedHashmap with all data (working). formFields should be a clone of formMap after deserialization works. When everything works formMap will not be there and formFields should be filled from an external Json.

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(FormField.class, new FormFieldDeserializer());
builder.registerTypeAdapter(FormField.class, new FormFieldSerializer());
builder.registerTypeAdapter(AjaxBehavior.class, new BehaviorListenerInstanceCreator());
builder.registerTypeAdapter(FormField.class, new CalendarInstanceCreator());
builder.setPrettyPrinting();
Gson gson = builder.create();

String myJson = gson.toJson(formMap);
System.out.println(myJson);

Type listType = new TypeToken<LinkedHashMap<String, FormField>>(){}.getType();
formFields = gson.fromJson(myJson, listType);

Two of my subclasses use the AjaxBehavior:

public class CalendarField extends FormField {
    private AjaxBehavior ajax;

    private void setupAjax() {
        FacesContext context = FacesContext.getCurrentInstance();

        ajax = (AjaxBehavior) context.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
        ajax.addAjaxBehaviorListener(new InputListener());
        ajax.setTransient(true);
    }

And I tried to make an InstanceCreator for it:

public class BehaviorListenerInstanceCreator implements InstanceCreator<AjaxBehavior> {
    @Override
    public AjaxBehavior createInstance(Type type) {
        FacesContext context = FacesContext.getCurrentInstance();
        AjaxBehavior ajax;
        ajax = (AjaxBehavior) context.getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
        ajax.addAjaxBehaviorListener(new InputListener());
        ajax.setTransient(true);

        return ajax;
    }
}

What can I do, to get my objects back in the LinkedHashmap?

My JSON looks like this:

{
  "MyCal": {
    "type": "CalendarField",
    "ajax": {
      "listeners": [
        {}
      ],
      "transientFlag": true,
      "initialState": false
    },
    "id": "MyCal",
    "label": "Mein Datum",
    "FromTo": false
  },
  "MyNumber": {
    "type": "NumberField",
    "IsYear": false,
    "mask": "999?99",
    "ajax": {
      "listeners": [
        {}
      ],
      "transientFlag": true,
      "initialState": false
    },
    "id": "MyNumber",
    "label": "Eine Nummer",
    "FromTo": false
  },
....

Body:
I found a solution for my problem.

I have to create a TypeAdapter not for AjaxBehavior but for BehaviorListener

builder.registerTypeAdapter(BehaviorListener.class, new BehaviorListenerInstanceCreator());

And inside I return an object of InputListener (subclass of BehaviorListener). The problem was that he wanted to create an object of BehaviorListener, which is an interface, so he crashed.

public class BehaviorListenerInstanceCreator implements InstanceCreator<BehaviorListener> {
    @Override
    public BehaviorListener createInstance(Type type) {
        InputListener ajax = new InputListener();

        return ajax;
    }
}

Maybe someone can use this information ;)


问:
Java copy file to folder with access permission
Is it possible to copy a file belonging to one user and copy it to a folder belonging to another user in java?</p>

答:
Per John Bollinger:

"Yes, if the machine's access controls permit the particular process to do so. That's substantially independent of the the implementation of the process -- i.e. whether Java is used doesn't really factor in."


问:
How to get language name from language code for google translate in google apps script?
I have a script I'm using with the google translate api. I am translating like this:

```<code>LanguageApp.translate(content, 'en', 'es')
</code>```

I now need to translate content to many more languages, and as languages are added or dropped I don't want to update much, so how can I get the name of a language from its language 'code'?

I'm expecting something like this

```<code>LanguageApp.getNameFromCode('es')
</code>```

and it would return "spanish" in this case.

How can I achieve this?

If it's not possible, I can use JS to on my frontend, or PHP in my backend, but using GAS is the most preferable way for me.

答:
This should be the method you are looking for:

```<code>List<Language> languages = translate.listSupportedLanguages(target);
</code>```

I shared the Java code, but you can have a look at the documentation and choose the one that fits your application better.

Body:
I have a script I'm using with the google translate api. I am translating like this:

LanguageApp.translate(content, 'en', 'es')

I now need to translate content to many more languages, and as languages are added or dropped I don't want to update much, so how can I get the name of a language from its language 'code'?

I'm expecting something like this

LanguageApp.getNameFromCode('es')

and it would return "spanish" in this case.

How can I achieve this?

If it's not possible, I can use JS to on my frontend, or PHP in my backend, but using GAS is the most preferable way for me.

Body:
This should be the method you are looking for:

List<Language> languages = translate.listSupportedLanguages(target);

I shared the Java code, but you can have a look at the documentation and choose the one that fits your application better.


问:
Targeting ARM architecture with .NET compiler
When you compile windows application in .NET you can set "Platform Target" to be x86 or x64. This would optimize your code to a specific architecture of the processor and allow to escape IL.
Does anyone know if there's something that would allow to achieve the same result for Windows Mobile application? I'm only interested in running my application on ARM architecture.</p>

答:
If you want to create ARM based application on Windows Mobile based devices install .NET Compact Framework. You’ll have a new “Smart device” project type in your VS for that.

I don’t know if there is JIT for any other ARM platform WM, there is also .NET Micro Framework but I can’t tell you anything about that, maybe this will solve your questions?

OwnerDisplayName: Ilya Volodin

OwnerDisplayName: michal


问:
Skip Credit Card step - Magento 1.4.1 $0.00 dollar total checkout (due to discount code)
Is there a way to skip the credit card processing step in Magento 1.4.1?

I have a discount that will bring the total to $0 and can't figure out how to let the customer check out without having to input credit card.

答: Enable the "Zero Subtotal Checkout" payment method. It will show only when the total is $0 and your customers can use that.</p>


问:
Checking if python sqlite table is populated
Here is my code:

```<code>dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
if dbContent is None:
    # This should run the nested code if it worked.
</code>```

Instead it runs the else statement which is not what should be happening.

答:
I am not a python expert but I think your code is just not correct. Please try this instead:</p>

```<code>cursor.execute("SELECT COUNT(*) FROM parse")
result=cursor.fetchone()
numRows=result[0]

if numRows == 0:
    # run your code
</code>```

Body:
Here is my code:

dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
if dbContent is None:
    # This should run the nested code if it worked.

Instead it runs the else statement which is not what should be happening.

Body:
I am not a python expert but I think your code is just not correct. Please try this instead:

cursor.execute("SELECT COUNT(*) FROM parse")
result=cursor.fetchone()
numRows=result[0]

if numRows == 0:
    # run your code


问:
NSTableColumn size to fit contents
I am developing in and against Mac OS X 10.6 (Snow Leopard). When I double-click between two of my NSTableView's column headers, the column on the left autosizes, like you would expect.

I want to provide this in a context menu as well, but it seems there is no publicly accessible function to do this. I've Googled, and looked at the documentation for NSTableView, NSTableHeaderView, and NSTableColumn, but found nothing. I find it hard to believe they wouldn't expose something so useful when they obviously have the code written to do it.

I saw the -[NSTableColumn sizeToFit] method, but that only takes the header's size into account. I would also settle for sending the double-click event to the NSTableHeaderView, but couldn't figure out how to do that, either.

Update - I realized it's important to mention I have an NSArrayController (subclass) providing the data to my table, so I don't have an NSTableViewDataSource on which I could call -[tableView: objectValueForTableColumn: row:]. That is the crux of the problem: each column is bound to a keypath of the array controller and that's how it gets its data, so it can't loop through its contents.

答:
You can get the length of each cell by getting the cells from the column.

```<code>NSCell myCell = [column dataCellForRow:i];
</code>```

Then get the width of the cell.

```<code>width = [myCell cellSize].width;
</code>```

After that you can set the width of the cell as the width of the column.

```<code>[column setMinWidth:width];
[column setWidth:width];
</code>```

Title: NSTableColumn size to fit contents

Body:
You can get the length of each cell by getting the cells from the column.

NSCell myCell = [column dataCellForRow:i];

Then get the width of the cell.

width = [myCell cellSize].width;

After that you can set the width of the cell as the width of the column.

[column setMinWidth:width];
[column setWidth:width];


问:
Replace strings in a string by a substring of those strings
Let's say I have a string like this:

```<code>s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
</code>```

and I want to turn it into

```<code>'(xy09 and foobar or (abc123 and something))'
</code>```

then - in this particular case - I could simply do

```<code>s.replace('X_', "")
</code>```

which gives the desired output.

However, in my actual data there might be not only X_ but also other prefixes, so the above replace statement does not work.

What I would need instead is a replacement of

a capital letter followed by an underscore and an arbitrary sequence of letters and numbers

by

everything after the first underscore.

So, to extract the desired elements I could use:

```<code>import re
print(re.findall('[A-Z]{1}_[a-zA-Z0-9]+', s))
</code>```

which prints

```<code>['X_xy09', 'X_foobar', 'X_abc123', 'X_something']
</code>```

how can I now replace those elements so that I obtain

```<code>'(xy09 and foobar or (abc123 and something))'
</code>```

?

答:
Another re.sub() approach:

```<code>import re

s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
result = re.sub(r'[A-Z]_(?=[a-zA-Z0-9]+)', '', s)

print(result)
</code>```

The output:

```<code>(xy09 and foobar or (abc123 and something))
</code>```

[A-Z]_(?=[a-zA-Z0-9]+) - (?=...) positive lookahead assertion, ensures that substituted [A-Z]_ substring is followed by alphanumeric sequence [a-zA-Z0-9]+

Body:
Let's say I have a string like this:

s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'

and I want to turn it into

'(xy09 and foobar or (abc123 and something))'

then - in this particular case - I could simply do

s.replace('X_', "")

which gives the desired output.

However, in my actual data there might be not only X_ but also other prefixes, so the above replace statement does not work.

What I would need instead is a replacement of

a capital letter followed by an underscore and an arbitrary sequence of letters and numbers

by

everything after the first underscore.

So, to extract the desired elements I could use:

import re
print(re.findall('[A-Z]{1}_[a-zA-Z0-9]+', s))

which prints

['X_xy09', 'X_foobar', 'X_abc123', 'X_something']

how can I now replace those elements so that I obtain

'(xy09 and foobar or (abc123 and something))'

?

Body:
Another re.sub() approach:

import re

s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
result = re.sub(r'[A-Z]_(?=[a-zA-Z0-9]+)', '', s)

print(result)

The output:

(xy09 and foobar or (abc123 and something))

[A-Z]_(?=[a-zA-Z0-9]+) - (?=...) positive lookahead assertion, ensures that substituted [A-Z]_ substring is followed by alphanumeric sequence [a-zA-Z0-9]+


问:
Using NancyFx as proxy
Is there a way to use proxy concept with NancyFx? I mean, I would like to access a service and record the response in my Nancy application (as proxy), either on a JSON file (similiar to wiremock) or in memory (similar to mountebank)

Thanks in advance.

答:
Have you considered WireMock.net as it has a proxy feature and saves the results to json files.

Towards the end of this article is an example of using the proxy feature of wiremock.

Title: Using NancyFx as proxy


问:
Limit the number of lines for UITextview
I was wondering how to limit the amount of LINES (not characters as asked in other questions) a user can enter when editing a UITextField.

Ideally, I would like to limit the input to max. 10 lines.

Where would I need to start? Do I do this with a method? In

```<code> - (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView
</code>```

答:
Here's a improved Version of Numereyes answer in Swift 4.2 / Swift 5

I made a little extension so I can reuse the code.
I'm using a While-Loop to check if the size fits. This also works when the user pastes a lot of text at once.

```<code>extension UITextView {
    var numberOfCurrentlyDisplayedLines: Int {
        let size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        //for Swift <=4.0, replace with next line:
        //let size = systemLayoutSizeFitting(UILayoutFittingCompressedSize)

        return Int(((size.height - layoutMargins.top - layoutMargins.bottom) / font!.lineHeight))
    }

    /// Removes last characters until the given max. number of lines is reached
    func removeTextUntilSatisfying(maxNumberOfLines: Int) {
        while numberOfCurrentlyDisplayedLines > (maxNumberOfLines) {
            text = String(text.dropLast())
            layoutIfNeeded()
        }
    }
}

// Use it in UITextView's delegate method:
func textViewDidChange(_ textView: UITextView) {
    textView.removeTextUntilSatisfying(maxNumberOfLines: 10)
}
</code>```

Body:
I was wondering how to limit the amount of LINES (not characters as asked in other questions) a user can enter when editing a UITextField.

Ideally, I would like to limit the input to max. 10 lines.

Where would I need to start? Do I do this with a method? In

 - (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView

Body:
Here's a improved Version of Numereyes answer in Swift 4.2 / Swift 5

I made a little extension so I can reuse the code.
I'm using a While-Loop to check if the size fits. This also works when the user pastes a lot of text at once.

extension UITextView {
    var numberOfCurrentlyDisplayedLines: Int {
        let size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        //for Swift <=4.0, replace with next line:
        //let size = systemLayoutSizeFitting(UILayoutFittingCompressedSize)

        return Int(((size.height - layoutMargins.top - layoutMargins.bottom) / font!.lineHeight))
    }

    /// Removes last characters until the given max. number of lines is reached
    func removeTextUntilSatisfying(maxNumberOfLines: Int) {
        while numberOfCurrentlyDisplayedLines > (maxNumberOfLines) {
            text = String(text.dropLast())
            layoutIfNeeded()
        }
    }
}

// Use it in UITextView's delegate method:
func textViewDidChange(_ textView: UITextView) {
    textView.removeTextUntilSatisfying(maxNumberOfLines: 10)
}


答:
You could use re.sub() with a lookahead assertion:

```<code>>>> import re
>>> s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
>>> re.sub(r'\b[A-Z]_(?=[a-zA-Z0-9])', '', s)
'(xy09 and foobar or (abc123 and something))'
</code>```

from the docs:

(?=...)

      Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

Body:
You could use re.sub() with a lookahead assertion:

>>> import re
>>> s = '(X_xy09 and X_foobar or (X_abc123 and X_something))'
>>> re.sub(r'\b[A-Z]_(?=[a-zA-Z0-9])', '', s)
'(xy09 and foobar or (abc123 and something))'

from the docs:

(?=...)

      Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.


问:
Linux backup script won't run
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

```<code>TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/
</code>```

The cronjob is;

```<code>30 7 * * * /home/centos/backupfile/runbackup
</code>```

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?

答:
I'm assuming that your bucket isn't actually named "backup".

When you run it manually, under which user do you run it? Is it the same as the user that runs it under cron? Also, are you sourcing the profile of that user too (source ~/.profile or similar)? If not, you may be missing some environment variables which are needed for the script which are present when you run it interactively. Another thing to check is how you are passing credentials to S3? For example, when you run it manually, does that user have AWS credentials and profile et al or are you using an IAM role?

And finally, ensuring that the paths to executables in your script at valid; e.g. /usr/local/bin/aws.

One way of debugging it is writing a bunch of logging statements to a file so that you can inspect a little more what is occurring.

Title: Linux backup script won't run

Body:
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/

The cronjob is;

30 7 * * * /home/centos/backupfile/runbackup

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?