问:
Understanding the behavior of dbms_random.value in where clause
I have a table with two columns(Using oracle 11g database) : Country, IndexNumber. Table contains 10 rows(10 different cities and with its unique index number.)

For example:

```<code>Country      IndexNUmber
India         1
Australia     2
.             .
.             .
.             .
.             .
US            10
</code>```

Now i want to fetch a random row from above table by generating random number using dbms_random.value(1,10). To achieve that i am using below query:

```<code>select * from tab_name where indexnumber = dbms_random.value(1,10);
</code>```

I am not able to understand the output of this query as some time it is fetching one row, some time zero rows and some time more that one row.

Can someone please make me understand how oracle is evaluating this query.

Thanks
Ankit

答:
When you run your original query:

```<code>select * from tab_name where indexnumber = dbms_random.value(1,10);
</code>```

it appears that the call to dbms_random is happening for each record's where clause.  In other words, there is a chance that every record in your table might be returned if the random number chosen happen to match the index for every record.  If you want to retrieve a single random record, then follow this pattern:

```<code>select *
from
( select * from tab_name order by DBMS_RANDOM.VALUE )
where rownum < 2;
</code>```

Body:
I have a table with two columns(Using oracle 11g database) : Country, IndexNumber. Table contains 10 rows(10 different cities and with its unique index number.)

For example:

Country      IndexNUmber
India         1
Australia     2
.             .
.             .
.             .
.             .
US            10

Now i want to fetch a random row from above table by generating random number using dbms_random.value(1,10). To achieve that i am using below query:

select * from tab_name where indexnumber = dbms_random.value(1,10);

I am not able to understand the output of this query as some time it is fetching one row, some time zero rows and some time more that one row.

Can someone please make me understand how oracle is evaluating this query.

Thanks
Ankit

Body:
When you run your original query:

select * from tab_name where indexnumber = dbms_random.value(1,10);

it appears that the call to dbms_random is happening for each record's where clause.  In other words, there is a chance that every record in your table might be returned if the random number chosen happen to match the index for every record.  If you want to retrieve a single random record, then follow this pattern:

select *
from
( select * from tab_name order by DBMS_RANDOM.VALUE )
where rownum < 2;


来源: stackexchange

问:
How to insert a list to dataframe using different forms?
How to transform the elements in the list and insert to dataframe ?

It's my data:

```<code>df = pd.DataFrame(columns=['country','date','value'])
data = ['Japan',(t1,123), (t2,456), (t3,789)]
</code>```

It's my expected result :

```<code>    country  date  value
0   'Japan'   t1    123
1   'Japan'   t2    456
2   'Japan'   t3    789
</code>```

Thanks your help !!

答:
Plan

I want to zip the all column names from the second one on with the relevant components in the list of tuples.  I can pass this to dict and get

```<code>dict(zip(df.columns[1:], zip(*data[1:])))

{'date': ('t1', 't2', 't3'), 'value': (123, 456, 789)}
</code>```

By unpacking this I can pass the resulting key/value pairs to pd.DataFrame.assign and get

```<code>df.assign(**dict(zip(df.columns[1:], zip(*data[1:]))))

  country date  value
0     NaN   t1    123
1     NaN   t2    456
2     NaN   t3    789
</code>```

I'm just missing my country and since I've already established an index with the length of the other columns, I can pass a scalar value to pd.DataFrame.assign for the finishing touch

Solution

```<code>df.assign(**dict(zip(df.columns[1:], zip(*data[1:])))).assign(country=data[0])

  country date  value
0   Japan   t1    123
1   Japan   t2    456
2   Japan   t3    789
</code>```

Setup

```<code>df = pd.DataFrame(columns=['country', 'date', 'value'])
data = ['Japan', ('t1', 123), ('t2', 456), ('t3', 789)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to transform the elements in the list and insert to dataframe ?

It's my data:

df = pd.DataFrame(columns=['country','date','value'])
data = ['Japan',(t1,123), (t2,456), (t3,789)]

It's my expected result :

    country  date  value
0   'Japan'   t1    123
1   'Japan'   t2    456
2   'Japan'   t3    789

Thanks your help !!

Body:
Plan

I want to zip the all column names from the second one on with the relevant components in the list of tuples.  I can pass this to dict and get

dict(zip(df.columns[1:], zip(*data[1:])))

{'date': ('t1', 't2', 't3'), 'value': (123, 456, 789)}

By unpacking this I can pass the resulting key/value pairs to pd.DataFrame.assign and get

df.assign(**dict(zip(df.columns[1:], zip(*data[1:]))))

  country date  value
0     NaN   t1    123
1     NaN   t2    456
2     NaN   t3    789

I'm just missing my country and since I've already established an index with the length of the other columns, I can pass a scalar value to pd.DataFrame.assign for the finishing touch

Solution

df.assign(**dict(zip(df.columns[1:], zip(*data[1:])))).assign(country=data[0])

  country date  value
0   Japan   t1    123
1   Japan   t2    456
2   Japan   t3    789

Setup

df = pd.DataFrame(columns=['country', 'date', 'value'])
data = ['Japan', ('t1', 123), ('t2', 456), ('t3', 789)]


问:
Debug Notification Extensions
I'm building a set of Notification Extensions (Service/Content).
I'm unable to connect to Xcode debugger or even log out to the device log or console.

Is there any way to see any kind of output?

答:
I have tried as per brendan's Answer but is not working for me at all!

I am getting below error in console

```<code>Program ended with exit code: 0
</code>```

Then after searching on google i have checked  this answer. however this also not worked for me for while!

Then i have tried same steps again as given in answer, After stopping my current running app. then follow same steps.For clarity i am writing this steps as below:

After running the app that contains the extension,

```<code>1) Set your breakpoint in the extension
2) Select Debug / Attach to Process by PID or name
3) Enter the name of the extension target
4) Trigger the push notification
</code>```

Before step 2 make sure to stop your current running app.

Title: Debug Notification Extensions

Body:
I have tried as per brendan's Answer but is not working for me at all!

I am getting below error in console

Program ended with exit code: 0

Then after searching on google i have checked  this answer. however this also not worked for me for while!

Then i have tried same steps again as given in answer, After stopping my current running app. then follow same steps.For clarity i am writing this steps as below:

After running the app that contains the extension,

1) Set your breakpoint in the extension
2) Select Debug / Attach to Process by PID or name
3) Enter the name of the extension target
4) Trigger the push notification

Before step 2 make sure to stop your current running app.


问:
Is UserExtendedProperties.GetValue user-specific or device-specific?
I'd like to use UserExtendedProperties.GetValue to associate a user with a high score table in a game I'm working on. Reading Microsoft's own API description I cannot work out whether this applies to a user (blah@live.com) or a physical device. Does anyone know?

Chris

答: UserExtendedProperties.GetValue("ANID") is an anonymous ID based on the user's Live ID. So, the same Live ID logged in from multiple WP7 devices will have the same ANID. </p>

ContentLicense: CC BY-SA 2.5


问:
is there a faster way to write similar test cases for Django views?
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

```<code>from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])
</code>```

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

答:
Projects I work on we sometimes use mixin + "customization hooks" when a test needs to repeated. (and endpoints like the "shape-list-create" is subject to change/refactored)

Example for question:

```<code>class TestUpdateWithOnly1FieldMixin(object):
    some_model = None
    some_field = None
    some_model2 = None

    def get_some_model(self):
        return self.some_model

    def get_some_field(self):
        return self.some_field

    def get_some_model2(self):
        return self.some_model2

    def test_update_with_only_1_field(self):
        some_model = self.get_some_model()
        # represents some-model in example
        some_model2 = self.get_some_model2()
        some_field = self.get_some_field()

        shape_data = {
            'name': 'test shape',
            'name_en': 'test shape en',
            'name_zh_hans': 'test shape zh hans',
            'serial_number': 'test shape serial number',
            'model_name': {
                some_field: '123'
            }
        }

      data = json.dumps(shape_data)
      response = self.client.post(reverse('shape-list-create'), data, 'application/json')
      self.assertEqual(response.status_code, status.HTTP_201_CREATED)

      some_model_data = response.data[some_model]

class SomeModelApiTests(base_tests.BaseApiTest, TestUpdateWithOnly1FieldMixin):
    some_model = 'choose your model'
    some_field = 'some_field'
    some_model2 = 'some-model'

    def get_some_field(self):
        # Do customization
        return 'some-field after customize'
</code>```

How to split the customization hooks and what to put in mixin etc is based on the situation.
In my opinion the goal is to have the actual test case easy to follow. (Maybe move the "post shape-list-create" into a separate function as it might not really be relevant for that test case)

Another example, going a bit overboard with customizations but just to give an idea.

```<code>class TestWithGoodNameMixin(object):
    some_model = None
    some_field = None

    # "Customization hooks"

    def get_shape_data(self):
        return {self.some_field: 'x'}

    def create_model(self, shape_data):
        response = self.client.post(reverse('shape-list-create'), shape_data,
                                    'application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        return response[self.some_model]

    def create_put_data(self, some_model_data):
        # Add default implementation
        pass

    # .....

    def test_update_with_only_1_field(self):
        shape_data = self.get_shape_data()
        some_model_data = self.create_model(shape_data)

        data = self.create_put_data(some_model_data)
        response = self.put_data(data)

        self.assert_put_response(response)
</code>```

Body:
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

Body:
Projects I work on we sometimes use mixin + "customization hooks" when a test needs to repeated. (and endpoints like the "shape-list-create" is subject to change/refactored)

Example for question:

class TestUpdateWithOnly1FieldMixin(object):
    some_model = None
    some_field = None
    some_model2 = None

    def get_some_model(self):
        return self.some_model

    def get_some_field(self):
        return self.some_field

    def get_some_model2(self):
        return self.some_model2

    def test_update_with_only_1_field(self):
        some_model = self.get_some_model()
        # represents some-model in example
        some_model2 = self.get_some_model2()
        some_field = self.get_some_field()

        shape_data = {
            'name': 'test shape',
            'name_en': 'test shape en',
            'name_zh_hans': 'test shape zh hans',
            'serial_number': 'test shape serial number',
            'model_name': {
                some_field: '123'
            }
        }

      data = json.dumps(shape_data)
      response = self.client.post(reverse('shape-list-create'), data, 'application/json')
      self.assertEqual(response.status_code, status.HTTP_201_CREATED)

      some_model_data = response.data[some_model]

class SomeModelApiTests(base_tests.BaseApiTest, TestUpdateWithOnly1FieldMixin):
    some_model = 'choose your model'
    some_field = 'some_field'
    some_model2 = 'some-model'

    def get_some_field(self):
        # Do customization
        return 'some-field after customize'

How to split the customization hooks and what to put in mixin etc is based on the situation.
In my opinion the goal is to have the actual test case easy to follow. (Maybe move the "post shape-list-create" into a separate function as it might not really be relevant for that test case)

Another example, going a bit overboard with customizations but just to give an idea.

class TestWithGoodNameMixin(object):
    some_model = None
    some_field = None

    # "Customization hooks"

    def get_shape_data(self):
        return {self.some_field: 'x'}

    def create_model(self, shape_data):
        response = self.client.post(reverse('shape-list-create'), shape_data,
                                    'application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        return response[self.some_model]

    def create_put_data(self, some_model_data):
        # Add default implementation
        pass

    # .....

    def test_update_with_only_1_field(self):
        shape_data = self.get_shape_data()
        some_model_data = self.create_model(shape_data)

        data = self.create_put_data(some_model_data)
        response = self.put_data(data)

        self.assert_put_response(response)


问:
java.util.NoSuchElementException while getting ArrayList from HashMap using Iterator
My code goes like this:

```<code>HashMap<Integer, ArrayList<DebtCollectionReport>> mapOfAccounts = new HashMap<Integer, ArrayList<DebtCollectionReport>>();
  Set<String> agencyNames = agencyWiseAccountMap.keySet();
  Iterator iter = agencyNames.iterator();
  while (iter.hasNext()) {
    String agency = (String) iter.next();
    HashMap<Integer, ArrayList<DebtCollectionReport>> tempAccountsMap = agencyWiseAccountMap.get(agency);
    Set<Integer> accountSet = tempAccountsMap.keySet();
    Iterator itr = accountSet.iterator();
    while (itr.hasNext()) {
      mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
    }
  }
</code>```

I am getting exception trace:

>

```<code> java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextNode(Unknown Source)
    at java.util.HashMap$KeyIterator.next(Unknown Source)
    at com.cerillion.debtcollection.collector.CollectionExecutor.execute(CollectionExecutor.java:56)
    at com.cerillion.debtcollection.collector.CollectionExecutor.main(CollectionExecutor.java:24)
2017-11-14 05:00:43,733 ERROR  CollectionExecutor             [main      ] Exception occurred while executing Debt Collection java.util.NoSuchElementException
java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextNode(Unknown Source)
    at java.util.HashMap$KeyIterator.next(Unknown Source)
    at com.cerillion.debtcollection.collector.CollectionExecutor.execute(CollectionExecutor.java:56)
    at com.cerillion.debtcollection.collector.CollectionExecutor.main(CollectionExecutor.java:24)
</code>```

This is occuring for line:

```<code>mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
</code>```

What can be the possible reason and how can i resolve it ?

答:
In the code block below, you called hasNext() once but you have called next() two times. hasNext() will return true if iteration has more values and  next() returns the next element in iteration

```<code>while (itr.hasNext()) {
  mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
}
</code>```

You can change this line accordingly:

```<code>while (itr.hasNext()) {
  Integer i1 = (Integer) itr.next();
  if(itr.hasNext()){
    mapOfAccounts.put(i1, tempAccountsMap.get((Integer) itr.next()));
  }
}
</code>```

Body:
My code goes like this:

HashMap<Integer, ArrayList<DebtCollectionReport>> mapOfAccounts = new HashMap<Integer, ArrayList<DebtCollectionReport>>();
  Set<String> agencyNames = agencyWiseAccountMap.keySet();
  Iterator iter = agencyNames.iterator();
  while (iter.hasNext()) {
    String agency = (String) iter.next();
    HashMap<Integer, ArrayList<DebtCollectionReport>> tempAccountsMap = agencyWiseAccountMap.get(agency);
    Set<Integer> accountSet = tempAccountsMap.keySet();
    Iterator itr = accountSet.iterator();
    while (itr.hasNext()) {
      mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
    }
  }

I am getting exception trace:

>

 java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextNode(Unknown Source)
    at java.util.HashMap$KeyIterator.next(Unknown Source)
    at com.cerillion.debtcollection.collector.CollectionExecutor.execute(CollectionExecutor.java:56)
    at com.cerillion.debtcollection.collector.CollectionExecutor.main(CollectionExecutor.java:24)
2017-11-14 05:00:43,733 ERROR  CollectionExecutor             [main      ] Exception occurred while executing Debt Collection java.util.NoSuchElementException
java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextNode(Unknown Source)
    at java.util.HashMap$KeyIterator.next(Unknown Source)
    at com.cerillion.debtcollection.collector.CollectionExecutor.execute(CollectionExecutor.java:56)
    at com.cerillion.debtcollection.collector.CollectionExecutor.main(CollectionExecutor.java:24)

This is occuring for line:

mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));

What can be the possible reason and how can i resolve it ?

Body:
In the code block below, you called hasNext() once but you have called next() two times. hasNext() will return true if iteration has more values and  next() returns the next element in iteration

while (itr.hasNext()) {
  mapOfAccounts.put((Integer) itr.next(), tempAccountsMap.get((Integer) itr.next()));
}

You can change this line accordingly:

while (itr.hasNext()) {
  Integer i1 = (Integer) itr.next();
  if(itr.hasNext()){
    mapOfAccounts.put(i1, tempAccountsMap.get((Integer) itr.next()));
  }
}


问:
Drupal 8 / How do i add an extra-class / highlight a 'view item' in a view list if the currentnode is the same?
I show a list of teasers within a view.
This view is included for this content type.
So it shows on every page of this contenttype.

How do i add a class to the view item so i ccan make it active?

答:
Depending of how are you render the view, you should use a preprocessor, example for a grid render

```<code>function MYTHEME_preprocess_views_view_grid(&$variables) {}
</code>```

once you do that you can add some logic into the preprocessor and add the class according this logic

```<code>function MYTHEME_preprocess_views_view_grid(&$variables) {
  $options = $variables['view']->style_plugin->options;
  $item_num = 0;
  $items = [];

  // Iterate over each rendered views result row.
  foreach ($variables['rows'] as $item) {
    // Add item attributes

     $item_attrs = [];
     $item_attrs['class'] = "view-grid__item view-grid__item--{$item_num}";
     $items[$item_num]['attributes'] = new Attribute($item_attrs);

     // Add item.content
     $items[$item_num]['content'] = $item;

     // Increase, decrease or reset appropriate integers.
     $item_num++;

      }

     // Add items to the variables array.
    $variables['items'] = $items;
}
</code>```

See more info here
https://api.drupal.org/api/drupal/core!modules!views!views.theme.inc/function/template_preprocess_views_view/8.2.x

Body:
Depending of how are you render the view, you should use a preprocessor, example for a grid render

function MYTHEME_preprocess_views_view_grid(&$variables) {}

once you do that you can add some logic into the preprocessor and add the class according this logic

function MYTHEME_preprocess_views_view_grid(&$variables) {
  $options = $variables['view']->style_plugin->options;
  $item_num = 0;
  $items = [];

  // Iterate over each rendered views result row.
  foreach ($variables['rows'] as $item) {
    // Add item attributes

     $item_attrs = [];
     $item_attrs['class'] = "view-grid__item view-grid__item--{$item_num}";
     $items[$item_num]['attributes'] = new Attribute($item_attrs);

     // Add item.content
     $items[$item_num]['content'] = $item;

     // Increase, decrease or reset appropriate integers.
     $item_num++;

      }

     // Add items to the variables array.
    $variables['items'] = $items;
}

See more info here
https://api.drupal.org/api/drupal/core!modules!views!views.theme.inc/function/template_preprocess_views_view/8.2.x


问:
How to analyze a JMeter summary report?
I get the following result when I run a load test. Can any one help me to read the report?</p>

```<code>the number of thread = '500 '
ramp up period = '1'

Sample      =       '500'
Avg     =       '20917'
min         =       '820'
max         =       '48158'
Std Deviation   =       '10563.178194669255'
Error %     =       '0.046'
throughput      =       '10.375381295262601'
KB/Sec          =       `247.05023046315702`
Avg. Bytes      =       '24382.664'
</code>```

答:
A Jmeter Test Plan must have listener to showcase the result of performance test execution.

Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.

It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.

Here is the detailed understanding of each parameter in Summary
  report.

By referring to the figure:

image

Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.

Samples: This indicates the number of virtual users per request.

Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.

Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.

Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.

Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.

Error%: Percentage of Failed requests per Label.

Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.

KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.

For more information:
http://www.testingjournals.com/understand-summary-report-jmeter/

Title: How to analyze a JMeter summary report?

Body:
I get the following result when I run a load test. Can any one help me to read the report?

the number of thread = '500 '
ramp up period = '1'

Sample      =       '500'
Avg     =       '20917'
min         =       '820'
max         =       '48158'
Std Deviation   =       '10563.178194669255'
Error %     =       '0.046'
throughput      =       '10.375381295262601'
KB/Sec          =       `247.05023046315702`
Avg. Bytes      =       '24382.664'

ContentLicense: CC BY-SA 4.0


问:
before in Kotlin
I'm trying to set a before filter without a path to apply to all requests.  In kotlin I'm trying to write:

```<code>before { req, resp ->
    // check auth then redirect if not authorized...
}
</code>```

The compiler says:

Cannot infer type for this parameter (req & resp).

How should I set a before filter in Kotlin without a route?

答:
You can use the path * in Spark to match all paths, like this:

```<code>before("*", { req, res ->
    logger.info("${req.requestMethod().toUpperCase()} ${req.fullUri()} by ${req.ip()} (${req.userAgent()})")
})

// or:

before("*") { req, res -> // ...
</code>```

Title: before in Kotlin

Body:
I'm trying to set a before filter without a path to apply to all requests.  In kotlin I'm trying to write:

before { req, resp ->
    // check auth then redirect if not authorized...
}

The compiler says:

Cannot infer type for this parameter (req & resp).

How should I set a before filter in Kotlin without a route?

Body:
You can use the path * in Spark to match all paths, like this:

before("*", { req, res ->
    logger.info("${req.requestMethod().toUpperCase()} ${req.fullUri()} by ${req.ip()} (${req.userAgent()})")
})

// or:

before("*") { req, res -> // ...


问:
jPOS connectivity with Posiflex printer through Java application
I want to integrate a Posiflex printer with my application, where the logical name is "PP Demo" and the device model is PP-8900.

The printer is connected to my system and is able to print with Posiflex software. How can I integrate it with my application?

答:
I just needed to paste the needed dll files into the lib of my java that's it, and the jpos.xml file is mentioned in the code...</p>
```<code>package practice;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;

public class PrintableComponent {

    public static void main(String[] args) {

        PrintableComponent example3 = new PrintableComponent();
        System.exit(0);
    }

    // --- Private instances declarations
    private final static int POINTS_PER_INCH = 72;

    /**
     * Constructor: Example3
     * <p>
     *
     */
    public PrintableComponent() {

        // --- Create a new PrinterJob object
        PrinterJob printJob = PrinterJob.getPrinterJob();

        // --- Create a new book to add pages to
        Book book = new Book();

        // --- Add the cover page using the default page format for this print
        // job
        book.append(new IntroPage(), printJob.defaultPage());

        // --- Add the document page using a landscape page format
        PageFormat documentPageFormat = new PageFormat();
        documentPageFormat.setOrientation(PageFormat.LANDSCAPE);
        book.append(new Document(), documentPageFormat);

        // --- Add a third page using the same painter
        book.append(new Document(), documentPageFormat);

        // --- Tell the printJob to use the book as the pageable object
        printJob.setPageable(book);

        // --- Show the print dialog box. If the user click the
        // --- print button we then proceed to print else we cancel
        // --- the process.
        if (printJob.printDialog()) {
            try {
                printJob.print();
            } catch (Exception PrintException) {
                PrintException.printStackTrace();
            }
        }

    }

    /**
     * Class: IntroPage
     * <p>
     *
     * This class defines the painter for the cover page by implementing the
     * Printable interface.
     * <p>
     *
     * @author Jean-Pierre Dube <jpdube@videotron.ca>
     * @version 1.0
     * @since 1.0
     * @see Printable
     */
    private class IntroPage implements Printable {

        /**
         * Method: print
         * <p>
         *
         * @param g
         *            a value of type Graphics
         * @param pageFormat
         *            a value of type PageFormat
         * @param page
         *            a value of type int
         * @return a value of type int
         */
        public int print(Graphics g, PageFormat pageFormat, int page) {

            // --- Create the Graphics2D object
            Graphics2D g2d = (Graphics2D) g;

            // --- Translate the origin to 0,0 for the top left corner
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // --- Set the default drawing color to black
            g2d.setPaint(Color.black);

            // --- Draw a border arround the page
            Rectangle2D.Double border = new Rectangle2D.Double(0, 0, pageFormat.getImageableWidth(),
                    pageFormat.getImageableHeight());
            g2d.draw(border);

            // --- Print the title
            String titleText = "Printing in Java Part 2";
            Font titleFont = new Font("helvetica", Font.BOLD, 36);
            g2d.setFont(titleFont);

            // --- Compute the horizontal center of the page
            FontMetrics fontMetrics = g2d.getFontMetrics();
            double titleX = (pageFormat.getImageableWidth() / 2) - (fontMetrics.stringWidth(titleText) / 2);
            double titleY = 3 * POINTS_PER_INCH;
            g2d.drawString(titleText, (int) titleX, (int) titleY);

            return (PAGE_EXISTS);
        }
    }

    /**
     * Class: Document
     * <p>
     *
     * This class is the painter for the document content.
     * <p>
     *
     *
     * @author Jean-Pierre Dube <jpdube@videotron.ca>
     * @version 1.0
     * @since 1.0
     * @see Printable
     */
    private class Document implements Printable {

        /**
         * Method: print
         * <p>
         *
         * @param g
         *            a value of type Graphics
         * @param pageFormat
         *            a value of type PageFormat
         * @param page
         *            a value of type int
         * @return a value of type int
         */
        public int print(Graphics g, PageFormat pageFormat, int page) {

            // --- Create the Graphics2D object
            Graphics2D g2d = (Graphics2D) g;

            // --- Translate the origin to 0,0 for the top left corner
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // --- Set the drawing color to black
            g2d.setPaint(Color.black);

            // --- Draw a border arround the page using a 12 point border
            g2d.setStroke(new BasicStroke(12));
            Rectangle2D.Double border = new Rectangle2D.Double(0, 0, pageFormat.getImageableWidth(),
                    pageFormat.getImageableHeight());

            g2d.draw(border);

            // --- Print page 1
            if (page == 1) {
                // --- Print the text one inch from the top and laft margins
                g2d.drawString("This the content page of page: " + page, POINTS_PER_INCH, POINTS_PER_INCH);
                return (PAGE_EXISTS);
            }

            // --- Print page 2
            else if (page == 2) {
                // --- Print the text one inch from the top and laft margins
                g2d.drawString("This the content of the second page: " + page, POINTS_PER_INCH, POINTS_PER_INCH);
                return (PAGE_EXISTS);
            }

            // --- Validate the page
            return (NO_SUCH_PAGE);

        }
    }

} // Example3
</code>```

Body:
I just needed to paste the needed dll files into the lib of my java that's it, and the jpos.xml file is mentioned in the code...

package practice;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;

public class PrintableComponent {

    public static void main(String[] args) {

        PrintableComponent example3 = new PrintableComponent();
        System.exit(0);
    }

    // --- Private instances declarations
    private final static int POINTS_PER_INCH = 72;

    /**
     * Constructor: Example3
     * <p>
     *
     */
    public PrintableComponent() {

        // --- Create a new PrinterJob object
        PrinterJob printJob = PrinterJob.getPrinterJob();

        // --- Create a new book to add pages to
        Book book = new Book();

        // --- Add the cover page using the default page format for this print
        // job
        book.append(new IntroPage(), printJob.defaultPage());

        // --- Add the document page using a landscape page format
        PageFormat documentPageFormat = new PageFormat();
        documentPageFormat.setOrientation(PageFormat.LANDSCAPE);
        book.append(new Document(), documentPageFormat);

        // --- Add a third page using the same painter
        book.append(new Document(), documentPageFormat);

        // --- Tell the printJob to use the book as the pageable object
        printJob.setPageable(book);

        // --- Show the print dialog box. If the user click the
        // --- print button we then proceed to print else we cancel
        // --- the process.
        if (printJob.printDialog()) {
            try {
                printJob.print();
            } catch (Exception PrintException) {
                PrintException.printStackTrace();
            }
        }

    }

    /**
     * Class: IntroPage
     * <p>
     *
     * This class defines the painter for the cover page by implementing the
     * Printable interface.
     * <p>
     *
     * @author Jean-Pierre Dube <jpdube@videotron.ca>
     * @version 1.0
     * @since 1.0
     * @see Printable
     */
    private class IntroPage implements Printable {

        /**
         * Method: print
         * <p>
         *
         * @param g
         *            a value of type Graphics
         * @param pageFormat
         *            a value of type PageFormat
         * @param page
         *            a value of type int
         * @return a value of type int
         */
        public int print(Graphics g, PageFormat pageFormat, int page) {

            // --- Create the Graphics2D object
            Graphics2D g2d = (Graphics2D) g;

            // --- Translate the origin to 0,0 for the top left corner
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // --- Set the default drawing color to black
            g2d.setPaint(Color.black);

            // --- Draw a border arround the page
            Rectangle2D.Double border = new Rectangle2D.Double(0, 0, pageFormat.getImageableWidth(),
                    pageFormat.getImageableHeight());
            g2d.draw(border);

            // --- Print the title
            String titleText = "Printing in Java Part 2";
            Font titleFont = new Font("helvetica", Font.BOLD, 36);
            g2d.setFont(titleFont);

            // --- Compute the horizontal center of the page
            FontMetrics fontMetrics = g2d.getFontMetrics();
            double titleX = (pageFormat.getImageableWidth() / 2) - (fontMetrics.stringWidth(titleText) / 2);
            double titleY = 3 * POINTS_PER_INCH;
            g2d.drawString(titleText, (int) titleX, (int) titleY);

            return (PAGE_EXISTS);
        }
    }

    /**
     * Class: Document
     * <p>
     *
     * This class is the painter for the document content.
     * <p>
     *
     *
     * @author Jean-Pierre Dube <jpdube@videotron.ca>
     * @version 1.0
     * @since 1.0
     * @see Printable
     */
    private class Document implements Printable {

        /**
         * Method: print
         * <p>
         *
         * @param g
         *            a value of type Graphics
         * @param pageFormat
         *            a value of type PageFormat
         * @param page
         *            a value of type int
         * @return a value of type int
         */
        public int print(Graphics g, PageFormat pageFormat, int page) {

            // --- Create the Graphics2D object
            Graphics2D g2d = (Graphics2D) g;

            // --- Translate the origin to 0,0 for the top left corner
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            // --- Set the drawing color to black
            g2d.setPaint(Color.black);

            // --- Draw a border arround the page using a 12 point border
            g2d.setStroke(new BasicStroke(12));
            Rectangle2D.Double border = new Rectangle2D.Double(0, 0, pageFormat.getImageableWidth(),
                    pageFormat.getImageableHeight());

            g2d.draw(border);

            // --- Print page 1
            if (page == 1) {
                // --- Print the text one inch from the top and laft margins
                g2d.drawString("This the content page of page: " + page, POINTS_PER_INCH, POINTS_PER_INCH);
                return (PAGE_EXISTS);
            }

            // --- Print page 2
            else if (page == 2) {
                // --- Print the text one inch from the top and laft margins
                g2d.drawString("This the content of the second page: " + page, POINTS_PER_INCH, POINTS_PER_INCH);
                return (PAGE_EXISTS);
            }

            // --- Validate the page
            return (NO_SUCH_PAGE);

        }
    }

} // Example3


问:
Editing .sol-files
I am looking for a way to edit .sol-files (LSO/Local Shared Object). I have tried searching quite a bit, but I have not been able to find any program that can edit AS3-files properly. Is there a solution for me out there?</p>

答:
I typically use Sol Editor, but I have run into a few .sol files that it won't read.

Flash Develop has(?) a .sol reader, but not an editor.

Title: Editing .sol-files


问:
FROM keyword now found where expected Oralce SQL (Multiple joins)
```<code>SELECT s.sales_date "Date of Sale", s.sales_id "Invoice Number',  a.category "Artwork Type",
         a.title "Artwork Title", c.last_name "Customer Last Name", e.last_name "Sales Person Last Name",
         p.purchase_amount "Price Cayucos Paid ($)", s.sales_amount "Selling Price ($)",
         s.sales_amount-p.purchase_amount "Profit ($)", e.commission_pct*s.sales_amount "Sales Person Commission ($)"
  FROM cayucos_sales s INNER JOIN cayucos_artworks a
      ON (s.artwork_id=a.artwork_id)
  INNER JOIN cayucos_employees e
      ON (s.salesperson_id=e.salesperson_id)
  INNER JOIN cayucos_purchases p
      ON (a.purchase_id=p.purchase_id)
  WHERE s.sales_date=TO_DATE('2017-&month', 'YYYY-MM');
</code>```

答:
Identifier <code>"Invoice Number'</code> should be closed using double quotes </p>

```<code>SELECT s.sales_date "Date of Sale", s.sales_id "Invoice Number"
</code>```

Body:
Identifier "Invoice Number' should be closed using double quotes

SELECT s.sales_date "Date of Sale", s.sales_id "Invoice Number"


问:
Function to add followers automatiically in odoo10
i have a problem I'm not sure how i could add automatically a followers. I tried to use this function but it doesn't work </p>

```<code>def add_follower_id(self, res_id, model, partner_id):
  follower_id = False
  reg = {
   'res_id': res_id,
   'res_model': 'my.model',
   'partner_id': self.field_id
  }
  try:
    follower_id = self.env['mail.followers'].create(reg)
  except:
     return False
  return follower_id
</code>```

答:
Inherit mail.thread model and override the create function of current model to add followers. Try below code.

```<code>class yourClassName(model.Model):
   _name = 'your.model'
   _inherit = ['mail.thread']

   @api.model
   def create(self,vals):
       result = super(yourClassName,self).create(vals)
       follower_ids = [add user_ids here]
       for f_id in follower_ids:
          result.self.message_subscribe_users(user_ids=your ids)
</code>```

hope it will help you.

Body:
i have a problem I'm not sure how i could add automatically a followers. I tried to use this function but it doesn't work

def add_follower_id(self, res_id, model, partner_id):
  follower_id = False
  reg = {
   'res_id': res_id,
   'res_model': 'my.model',
   'partner_id': self.field_id
  }
  try:
    follower_id = self.env['mail.followers'].create(reg)
  except:
     return False
  return follower_id

Body:
Inherit mail.thread model and override the create function of current model to add followers. Try below code.

class yourClassName(model.Model):
   _name = 'your.model'
   _inherit = ['mail.thread']

   @api.model
   def create(self,vals):
       result = super(yourClassName,self).create(vals)
       follower_ids = [add user_ids here]
       for f_id in follower_ids:
          result.self.message_subscribe_users(user_ids=your ids)

hope it will help you.


问:
Pass database data multiple pages though php
I have one main page which list alot of different products. What i want is to be able to click on a product and that products information to be passed to a template item page, so information can be displayed.

```<code><?php while($product = mysqli_fetch_assoc($featured)) :?>

    <div class="col_1_of_3 span_1_of_3 simpleCart_shelfItem">
       <a href="product.php?id=<? echo $product['ProductID']; ?>">

        <div class="product_image">

            <img src="images/allsupplementsImages/<?php echo $product['ProductImage1'];?>_0001_1.jpg" class="img-responsive" alt=""/>
            <!--<a href="" class="button item_add item_1"> </a> -->
            <div class="product_container">

                <div class="cart-left">
                    <p class="title"><?php echo $product['Vendor']; ?> </p>
                    <p class="title"><?php echo $product['ProductName']; ?> </p>
                </div>

                <br>
                <span class="amount item_price"><?php echo $product['ProductPrice']; ?></span></a>
                <br>

                <span>
                    <button class="button item_add item_1 " type="button" onclick="location.href='';"> Add to Cart</button>
                </span>

            </div>

        </div>

    </div>

<?php endwhile; ?>
</code>```

And in my product.php i have

```<code>$getproduct = $_GET['id'];
echo "$getproduct";
</code>```

The URL that is displaying is "http://localhost/example/product.php?id=%3C?%20echo%20$product[%27ProductID%27];%20?%3E"

The above is not displaying product id, and how can i also bring up other information about this product. such as $product['price'],['department'].

答: Pass the database value into a $_session variable and serve them across pages and use the session_start() in the header</p>

Body:
I have one main page which list alot of different products. What i want is to be able to click on a product and that products information to be passed to a template item page, so information can be displayed.

<?php while($product = mysqli_fetch_assoc($featured)) :?>

       <a href="product.php?id=<? echo $product['ProductID']; ?>">

            <img src="images/allsupplementsImages/<?php echo $product['ProductImage1'];?>_0001_1.jpg" class="img-responsive" alt=""/>

<?php echo $product['Vendor']; ?>

<?php echo $product['ProductName']; ?>

                <?php echo $product['ProductPrice']; ?>

                    <button class="button item_add item_1 " type="button" onclick="location.href='';"> Add to Cart</button>

<?php endwhile; ?>

And in my product.php i have

$getproduct = $_GET['id'];
echo "$getproduct";

The URL that is displaying is "http://localhost/example/product.php?id=%3C?%20echo%20$product[%27ProductID%27];%20?%3E"

The above is not displaying product id, and how can i also bring up other information about this product. such as $product['price'],['department'].


问:
NSArrayController NSTableView Core Data Binding integers
I have an NSTableView bound to an NSArrayController, which in turn is bound to Core Data. The table displays integer values from core data nicely, but if I edit the numbers in the table I get an error:

```<code>Unacceptable type of value for attribute: property = "armorclass"; desired type = NSNumber; given type = NSTaggedPointerString; value = 10.
</code>```

Any suggestions of how I can convert this pointer string back to an Int16 before the Array Controller tries to save it back to Core Data?

I wrote the following ValueTransformer but it's not working properly. I always get the error: Cannot find value transformer with name StringIntegerValueTransformer

```<code>class StringIntegerValueTransformer: ValueTransformer {

    override class func transformedValueClass() -> AnyClass { //What do I transform
        return String.self as! AnyClass
    }

    override class func allowsReverseTransformation() -> Bool { //Can I transform back?
        return false
    }

    override func transformedValue(_ value: Any?) -> Any? {
        if let val = value {
            return String(describing: val)
        }
        return "nil"
    }

    override func reverseTransformedValue(_ value: Any?) -> Any? { //Revert transformation
        if let val = value {
            return val as? Int16
        }
        return nil
    }
}
</code>```

fff

答:
To register the value transformer override init in AppDelegate

```<code>override init()
{
   let stringIntegerValueTransformer = StringIntegerValueTransformer()
   ValueTransformer.setValueTransformer(stringIntegerValueTransformer, forName:NSValueTransformerName(rawValue: "StringIntegerValueTransformer"))
   super.init()
 }
</code>```

And consider this note from the documentation

Your NSValueTransformer subclasses are not automatically listed in the Interface Builder bindings inspector. When inspecting a binding you can enter the name that the value transformer is registered with, but the functionality will not be present in Interface Builder’s test mode. When your application is compiled and run the transformer will be used

Body:
I have an NSTableView bound to an NSArrayController, which in turn is bound to Core Data. The table displays integer values from core data nicely, but if I edit the numbers in the table I get an error:

Unacceptable type of value for attribute: property = "armorclass"; desired type = NSNumber; given type = NSTaggedPointerString; value = 10.

Any suggestions of how I can convert this pointer string back to an Int16 before the Array Controller tries to save it back to Core Data?

I wrote the following ValueTransformer but it's not working properly. I always get the error: Cannot find value transformer with name StringIntegerValueTransformer

class StringIntegerValueTransformer: ValueTransformer {

    override class func transformedValueClass() -> AnyClass { //What do I transform
        return String.self as! AnyClass
    }

    override class func allowsReverseTransformation() -> Bool { //Can I transform back?
        return false
    }

    override func transformedValue(_ value: Any?) -> Any? {
        if let val = value {
            return String(describing: val)
        }
        return "nil"
    }

    override func reverseTransformedValue(_ value: Any?) -> Any? { //Revert transformation
        if let val = value {
            return val as? Int16
        }
        return nil
    }
}

fff

Body:
To register the value transformer override init in AppDelegate

override init()
{
   let stringIntegerValueTransformer = StringIntegerValueTransformer()
   ValueTransformer.setValueTransformer(stringIntegerValueTransformer, forName:NSValueTransformerName(rawValue: "StringIntegerValueTransformer"))
   super.init()
 }

And consider this note from the documentation

Your NSValueTransformer subclasses are not automatically listed in the Interface Builder bindings inspector. When inspecting a binding you can enter the name that the value transformer is registered with, but the functionality will not be present in Interface Builder’s test mode. When your application is compiled and run the transformer will be used


问:
Can we make an array containing pairs?
I am new to stl and i came across a question where it is required to store a lot of pairs having same characteristics (like:- (string,int)) together. Can we store pairs in array and if so how? Thanks in advance..</p>

答:
You want ...

to store a lot of pairs having same characteristics

The terminology is a bit wrong. You want to store many pairs of the same type (not "characteristics").

You could define your own struct as answered by Nipun, or use

```<code>std::array<std::pair<std::string,int>, 10> arr;
</code>```

for an array of 10 pairs of strings and ints.

Spend more time on reading a documentation on standard containers and standard utilities. Perhaps you want some other existing thing (e.g. std::set with std::tuple, maybe with your own comparator).

Templates can (and often should) be combined since they are compositional. Be also aware of the rule of five.

Title: Can we make an array containing pairs?

Body:
You want ...

to store a lot of pairs having same characteristics

The terminology is a bit wrong. You want to store many pairs of the same type (not "characteristics").

You could define your own struct as answered by Nipun, or use

std::array<std::pair<std::string,int>, 10> arr;

for an array of 10 pairs of strings and ints.

Spend more time on reading a documentation on standard containers and standard utilities. Perhaps you want some other existing thing (e.g. std::set with std::tuple, maybe with your own comparator).

Templates can (and often should) be combined since they are compositional. Be also aware of the rule of five.


问:
How to remove key in graphs
How should i remove key in graphs. I am using mpAndroid library version 2.0.9

Skack-overflow has generated the link of the image as it is not allowing me to add the image

答:
try</p>

```<code>chart.getLegend().setEnabled(false);
</code>```

Title: How to remove key in graphs

Body:
try

chart.getLegend().setEnabled(false);


问:
jenkins integration with artifactory 5.5.2
Currently I am using JFrog OSS version 5.5.2 for my artifacts which is integrated with Jenkins version 2.19.4. The artifactory plugin version is 2.13.1. I created a free-style software project. The repository type is “generic-local”. I am able to run build successfully and builds are saved in repository but the artifacts are not saved.Also, there is no option called “deploy artifacts to artifactory” in Jenkins configuration.

Do I have change my settings or update Jenkins?

Please advice me what changes has to be done.

答:
Do I need to upgrade jenkins?

No: the Artifactory plugin requires a Jenkins Core 1.521.

But you would need to define a Maven 2/3 build instead.

Maven 3 Support for Jenkins Free-style Jobs

The Jenkins Artifactory plugin supports running Maven 3 builds from free-style jobs by using a Maven 3 build step + a build environment section for the Artifactory Maven 3 integration (artifact and build information deployment).

For Maven 3 builds users are encouraged to configure the Artifactory integration using Jenkins' native Maven 2/3 build projects.


问:
Distributing iOS Application to staff within an Organisation
Intro

My company has built an application and we are ready to move it into production. The application built must be private and should be available to staff only. So this rules out iTunes and leaves us with Apple Enterprise Developer Program and Apple B2B. Now when we export the application out using the Enterprise option in Xcode, after installation we get a pop up saying Untrusted Enterprise Developer. We can't distribute this application and have all of our users go through settings to trust this app, that is too much to ask.

With the B2B, we would have to collect UDIDS of every iOS user and add them to a list of approved users. Dealing with over 200 users, this could become frustrating.

Question

So what I would like to know is, is there a way for a company to distribute iOS applications via a private link that once shared with employees all they would have to do is download the app, install and enjoy it without being asked to Trust the app or without collecting their UDID.

Thanks in advance!

答:
An alternate approach you might consider would be to use the B2B store (to keep your app hidden from general visibility), join the Business Volume Purchase Plan / VPP and then "purchase" your 200 licenses there (at zero cost) which would generate a spreadsheet of redemption codes that you can send to individual users to redeem in the Store app on their devices.

From a user perspective, that may be a much better experience as you don't have to explain what trust is and why it's required; especially if you include the redemption code in a link in an email.

Yes, you have to go through Store submission/approval rounds and lose some of the flexibility of enterprise deployment but you gain automatic updates and sidestep the problems associated with trust during installation and the periodic re-validation of credentials.

If you want further control you could add a prohibitive cost per install at the B2B Store which none of your users will ever pay because you issue them free codes (as you control the sale price) and even withdraw your app from sale other than when you are using redemption codes for installation.


问:
pyqt4 QtGui.QFileDialog.getSaveFileName clicke cancel Button
I'm using PyQt4.

```<code> filename = QtGui.QFileDialog.getSaveFileName(self, "Save file", "", "CSV files (*.csv)|*.csv")
</code>```

Now when I click cancel button,the next code is executing. But, I don't want this instead I want it to do nothing. How can I achieve this?

```<code>If filename is None:

stop excute code.
</code>```

答:
If the user presses Cancel, getSaveFileName returns a null string.

You can use the fact that empty sequences are false. So, you should use:

```<code>if filename:
</code>```

or

```<code>if not filename:
</code>```

Body:
I'm using PyQt4.

 filename = QtGui.QFileDialog.getSaveFileName(self, "Save file", "", "CSV files (*.csv)|*.csv")

Now when I click cancel button,the next code is executing. But, I don't want this instead I want it to do nothing. How can I achieve this?

If filename is None:

stop excute code.

Body:
If the user presses Cancel, getSaveFileName returns a null string.

You can use the fact that empty sequences are false. So, you should use:

if filename:

or

if not filename:


问:
How to redirect to the signin page and display message in that page
In this code, OTPVerficationHTML() function having condition that data.rval == 2, where it should redirect to signin page and display the message in that page only

```<code>var flag = 0;
   $("#successPrimary").on('click', function(e) {
     e.preventDefault()
     user_name = $('#Login_UserName').val();
     password = $('#Login_Password').val();
     captcha = $('#Login_captcha').val();

     var PostData = {};
     PostData['put'] = true;
     PostData['form_login_username'] = user_name;
     PostData['form_login_password'] = password;
     PostData['form_login_captcha'] = captcha;

     Application.Post("/ajax/ajax_login", PostData, function(data){
        if(data.rval == 1){
          window.location = "/offerletter/index";
          Application.PageAlertBox.Show('Sucess', ['Login Successfully.']);
        }else if(data.rval == 2){
          OTPVerficationHTML()
          Application.PageAlertBox.Show('info', ['Enter OTP to Verify.']);
        }else{
          Application.PageAlertBox.Show('error',[data.Message]);
        }
      });
   });

   var OTPVerficationHTML = function () {
     initial_html = $('#otpfromlogin').html();
     $('#otpfromlogin').empty();
     $('#buttons').empty();
     $('#otpfromlogin').append(final_html);
     $('#Login_UserName').val(user_name);
     $('#Login_UserName').attr('readonly', 'true');
     $('#Login_UserName').focus();
   }

   $('#otpfromlogin').on('click', '#otp-verify', function(e) {
      e.preventDefault()
      otp = $('#form_otp').val();
       var PostData = {};
       PostData['put'] = true;
       PostData['form_login_otp'] = otp;

     Application.Post("/ajax/ajax_loginwithotp", PostData, function(data) {
        if(data.rval == 1) {
            window.location = "/offerletter/index";
            Application.PageAlertBox.Show('Sucess', ['Successfully Loggedin.']);
        } else if(data.rval == 2) {
            window.location = "/signin";
            Application.PageAlertBox.Show('info', ['OTP is Expired, Pleasem login with new OTP.']);
        } else if(data.rval == -4) {
            Application.PageAlertBox.Show('error', ['OTP is Invalid. Please Enter correct OTP.']);
        } else {
            Application.PageAlertBox.Show('error', [data.Message]);
        }
      });
   });
</code>```

It is not displaying the message on signin page. I don't know how to deal with this kind of situation.

答:
If the redirection is working fine, you can change the below code:

```<code>window.location = "/signin";
</code>```

to

```<code>window.location = "/signin?q=1";
</code>```

And in your signin page, you can receive this using $_POST['q']. Based on this value, you can perform next set of activities in your signin page.

Body:
In this code, OTPVerficationHTML() function having condition that data.rval == 2, where it should redirect to signin page and display the message in that page only

var flag = 0;
   $("#successPrimary").on('click', function(e) {
     e.preventDefault()
     user_name = $('#Login_UserName').val();
     password = $('#Login_Password').val();
     captcha = $('#Login_captcha').val();

     var PostData = {};
     PostData['put'] = true;
     PostData['form_login_username'] = user_name;
     PostData['form_login_password'] = password;
     PostData['form_login_captcha'] = captcha;

     Application.Post("/ajax/ajax_login", PostData, function(data){
        if(data.rval == 1){
          window.location = "/offerletter/index";
          Application.PageAlertBox.Show('Sucess', ['Login Successfully.']);
        }else if(data.rval == 2){
          OTPVerficationHTML()
          Application.PageAlertBox.Show('info', ['Enter OTP to Verify.']);
        }else{
          Application.PageAlertBox.Show('error',[data.Message]);
        }
      });
   });

   var OTPVerficationHTML = function () {
     initial_html = $('#otpfromlogin').html();
     $('#otpfromlogin').empty();
     $('#buttons').empty();
     $('#otpfromlogin').append(final_html);
     $('#Login_UserName').val(user_name);
     $('#Login_UserName').attr('readonly', 'true');
     $('#Login_UserName').focus();
   }

   $('#otpfromlogin').on('click', '#otp-verify', function(e) {
      e.preventDefault()
      otp = $('#form_otp').val();
       var PostData = {};
       PostData['put'] = true;
       PostData['form_login_otp'] = otp;

     Application.Post("/ajax/ajax_loginwithotp", PostData, function(data) {
        if(data.rval == 1) {
            window.location = "/offerletter/index";
            Application.PageAlertBox.Show('Sucess', ['Successfully Loggedin.']);
        } else if(data.rval == 2) {
            window.location = "/signin";
            Application.PageAlertBox.Show('info', ['OTP is Expired, Pleasem login with new OTP.']);
        } else if(data.rval == -4) {
            Application.PageAlertBox.Show('error', ['OTP is Invalid. Please Enter correct OTP.']);
        } else {
            Application.PageAlertBox.Show('error', [data.Message]);
        }
      });
   });

It is not displaying the message on signin page. I don't know how to deal with this kind of situation.

Body:
If the redirection is working fine, you can change the below code:

window.location = "/signin";

to

window.location = "/signin?q=1";

And in your signin page, you can receive this using $_POST['q']. Based on this value, you can perform next set of activities in your signin page.


问:
How to merge 2 xpath in one
Html

```<code><li class="wdappchrome-ai" data-automation-id="searchInputAutoCompleteResult" tabindex="-2" aria-posinset="1" aria-setsize="3">
<span data-automation-id="searchInputAutoCompleteResultFullText">
    <span style="font-weight:500">
        <span data-automation-id="searchInputAutoCompleteResultToken" style="font-weight:400">mike</span>
        <span data-automation-id="searchInputAutoCompleteResultToken" style="font-weight:400">diana</span>
    </span>
</span>
</li>
</code>```

I am getting user full name divided into spans so I want to build xpath which returns me combine text of both/multiple span from single list.

For now I am using 2 or more xpath based on name of user divided into span.

I use : //li[.//span[text()='mike']]  //li[.//span[text()='diana']]

Then I do gettext() for above both xpath and merge using java grammatically. So I am looking for solution which give me full text of all span within particular li tag from above.

答:
To get the full text of all span within particular li tag in a single line you can use the following code block :</p>

```<code>ArrayList<String> nameList = new ArrayList<String>();
List<WebElement> firstName_lastname = driver.findElements(By.xpath("//li[@class='wdappchrome-ai']//span[@data-automation-id='searchInputAutoCompleteResultToken']"));
for (WebElement fN_lN:firstName_lastname)
    nameList.add(fN_lN.getAttribute("innerHTML"));
System.out.println(nameList);
</code>```

Title: How to merge 2 xpath in one

Body:
Html

        mike
        diana

I am getting user full name divided into spans so I want to build xpath which returns me combine text of both/multiple span from single list.

For now I am using 2 or more xpath based on name of user divided into span.

I use : //li[.//span[text()='mike']]  //li[.//span[text()='diana']]

Then I do gettext() for above both xpath and merge using java grammatically. So I am looking for solution which give me full text of all span within particular li tag from above.

Body:
To get the full text of all span within particular li tag in a single line you can use the following code block :

ArrayList<String> nameList = new ArrayList<String>();
List<WebElement> firstName_lastname = driver.findElements(By.xpath("//li[@class='wdappchrome-ai']//span[@data-automation-id='searchInputAutoCompleteResultToken']"));
for (WebElement fN_lN:firstName_lastname)
    nameList.add(fN_lN.getAttribute("innerHTML"));
System.out.println(nameList);


问:
Getting “<NULL>” data from core data and app crashed when we save in NSUserDefaults?
In app version 1.0 my core data has 5 attributes like attribute1, attribute2, attribute3, attribute4, attribute5 (All attributes type is transformable). It’s currently available in App Store. In app version 2.0 i updated my core data DB. I added one more attribute like attribute6. I changed core data version from core data to core data2 and i changed in persistentStoreCoordinator like this.

```<code>NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
</code>```

It’s working fine, but at the time of app update from version 1.0 to 2.0 (first installation of new version) I’m getting “NULL” data from attribute6 (when i get data from DB) and i’m trying to save attribute6 data in NSUserDefaults, but app crashed and getting below error.

```<code>[User Defaults] Attempt to set a non-property-list object <null> as an NSUserDefaults/CFPreferences value for key MyKeyName
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object null for key MyKeyName'
</code>```

答:
Make sure you have data for attribute6 written in the DB before reading if you want it to be not empty. If you want to just save the value directly after reading from DB, and allow attribute6 to be empty, then you have to check the value for [NSNull null] before trying to save it in NSUserDefaults, NSUserDefaults doesn't accept [NSNull null] objects.

Edit:
Judging from your comments, the value will be initially [NSNull null]. So you can handle it this way:

```<code>//assuming the object is named attribute
if (attribute != [NSNull null]) {
       [[NSUserDefaults standardUserDefaults] setObject:attribute forKey:MyKeyName];
}
</code>```

Body:
In app version 1.0 my core data has 5 attributes like attribute1, attribute2, attribute3, attribute4, attribute5 (All attributes type is transformable). It’s currently available in App Store. In app version 2.0 i updated my core data DB. I added one more attribute like attribute6. I changed core data version from core data to core data2 and i changed in persistentStoreCoordinator like this.

NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];

It’s working fine, but at the time of app update from version 1.0 to 2.0 (first installation of new version) I’m getting “NULL” data from attribute6 (when i get data from DB) and i’m trying to save attribute6 data in NSUserDefaults, but app crashed and getting below error.

[User Defaults] Attempt to set a non-property-list object <null> as an NSUserDefaults/CFPreferences value for key MyKeyName
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object null for key MyKeyName'

Body:
Make sure you have data for attribute6 written in the DB before reading if you want it to be not empty. If you want to just save the value directly after reading from DB, and allow attribute6 to be empty, then you have to check the value for [NSNull null] before trying to save it in NSUserDefaults, NSUserDefaults doesn't accept [NSNull null] objects.

Edit:
Judging from your comments, the value will be initially [NSNull null]. So you can handle it this way:

//assuming the object is named attribute
if (attribute != [NSNull null]) {
       [[NSUserDefaults standardUserDefaults] setObject:attribute forKey:MyKeyName];
}


问:
How can I escape a double quote inside double quotes?
How can I escape double quotes inside a double string in Bash?

For example, in my shell script

```<code>#!/bin/bash

dbload="load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"
</code>```

I can't get the ENCLOSED BY '\"' with double quote to escape correctly. I can't use single quotes for my variable, because I want to use variable $dbtable.

答:
Store the double quote character in a variable:

```<code>dqt='"'
echo "Double quotes ${dqt}X${dqt} inside a double quoted string"
</code>```

Output:

Double quotes "X" inside a double quoted string
```

Body:
How can I escape double quotes inside a double string in Bash?

For example, in my shell script

#!/bin/bash

dbload="load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"

I can't get the ENCLOSED BY '\"' with double quote to escape correctly. I can't use single quotes for my variable, because I want to use variable $dbtable.

Body:
Store the double quote character in a variable:

dqt='"'
echo "Double quotes ${dqt}X${dqt} inside a double quoted string"

Output:

Double quotes "X" inside a double quoted string


问:
How to insert a list to dataframe using different forms?
How to transform the elements in the list and insert to dataframe ?

It's my data:

```<code>df = pd.DataFrame(columns=['country','date','value'])
data = ['Japan',(t1,123), (t2,456), (t3,789)]
</code>```

It's my expected result :

```<code>    country  date  value
0   'Japan'   t1    123
1   'Japan'   t2    456
2   'Japan'   t3    789
</code>```

Thanks your help !!

答:
```<code>import pandas as pd

dict ={"country":["Japan","Japan","Japan"],
       "date":["t1","t2","t3"],
       "value":[123,456,789]}

df = pd.DataFrame(dict)
print(df)
</code>```

Body:
How to transform the elements in the list and insert to dataframe ?

It's my data:

df = pd.DataFrame(columns=['country','date','value'])
data = ['Japan',(t1,123), (t2,456), (t3,789)]

It's my expected result :

    country  date  value
0   'Japan'   t1    123
1   'Japan'   t2    456
2   'Japan'   t3    789

Thanks your help !!


问:
Of subtitles & lag times (yet another C overflow doubt)
I'm trying to calculate the time offset to be added to subtitle files to correct the lag. The part shown below is after tokenizing the hh:mm:ss,uuu (uuu stands for microseconds) into the time[] array. I'm converting the time into microseconds then adding the actual & lag time to get the final time.

The program computes the actual & lag time properly. However, it gives the wrong final hour time. Have I hit upon some overflow condition that can't be handled by the code below?

Edit: I have realized the error. I should be dividing rather than taking remainder for hour time.

```<code>int i;
int time[4];
unsigned long totalTime,totalLagTime;
...
for(i=0;i<4;i++)
{
    printf("time[%d] = %d\n",i,time[i]);
}

for(i=0;i<4;i++)
{
printf("lag time[%d] = %d\n",i,lagTime[i]);
}

totalTime = 1000*(3600*time[0] + 60*time[1] + time[2]) + time[3];

printf("total time is %u in milliseconds\n",totalTime);

totalLagTime = 1000*(3600*lagTime[0] + 60*lagTime[1] + lagTime[2]) + lagTime[3];

printf("total lag time is %u in milliseconds\n",totalLagTime);

totalTime += totalLagTime;

printf("Now, total time is %u in milliseconds\n",totalTime);

time[0] = totalTime % 3600000;

printf("hour time is %d\n",time[0]);
</code>```

Test case:

```<code>00:01:24,320

time[0] = 0
time[1] = 1
time[2] = 24
time[3] = 320
lag time[0] = 10
lag time[1] = 10
lag time[2] = 10
lag time[3] = 10
total time is 84320 in milliseconds
total lag time is 36610010 in milliseconds
Now, total time is 36694330 in milliseconds
hour time is 694330
</code>```

答:
Shouldn't that be </p>

```<code>time[0] = totalTime / 3600000;
</code>```

Body:
I'm trying to calculate the time offset to be added to subtitle files to correct the lag. The part shown below is after tokenizing the hh:mm:ss,uuu (uuu stands for microseconds) into the time[] array. I'm converting the time into microseconds then adding the actual & lag time to get the final time.

The program computes the actual & lag time properly. However, it gives the wrong final hour time. Have I hit upon some overflow condition that can't be handled by the code below?

Edit: I have realized the error. I should be dividing rather than taking remainder for hour time.

int i;
int time[4];
unsigned long totalTime,totalLagTime;
...
for(i=0;i<4;i++)
{
    printf("time[%d] = %d\n",i,time[i]);
}

for(i=0;i<4;i++)
{
printf("lag time[%d] = %d\n",i,lagTime[i]);
}

totalTime = 1000*(3600*time[0] + 60*time[1] + time[2]) + time[3];

printf("total time is %u in milliseconds\n",totalTime);

totalLagTime = 1000*(3600*lagTime[0] + 60*lagTime[1] + lagTime[2]) + lagTime[3];

printf("total lag time is %u in milliseconds\n",totalLagTime);

totalTime += totalLagTime;

printf("Now, total time is %u in milliseconds\n",totalTime);

time[0] = totalTime % 3600000;

printf("hour time is %d\n",time[0]);

Test case:

00:01:24,320

time[0] = 0
time[1] = 1
time[2] = 24
time[3] = 320
lag time[0] = 10
lag time[1] = 10
lag time[2] = 10
lag time[3] = 10
total time is 84320 in milliseconds
total lag time is 36610010 in milliseconds
Now, total time is 36694330 in milliseconds
hour time is 694330

Body:
Shouldn't that be

time[0] = totalTime / 3600000;


问:
Custom method submit in form component container
I have a component Angular containing my header and footer of all of my form like this :

```<code> <div class="layout vertical">
  <header class="layout horizontal center">
    <h2> {{enterData?.title}} </h2>
  </header>

  <!-- Form -->
  <form [formGroup]="formName" #form="ngForm" (ngSubmit)="submit()"
        class="layout vertical">
   <ng-content></ng-content>

  </form>

  <footer class="layout space-between horizontal">
    <div class="buttons-footer-layout">
      <!-- buttons -->
      <paper-button class="btn-cancel-alt" type="reset" (click)="close()" id="cancelInc">{{labels.BTN_ANNULER}}
      </paper-button>
      <paper-button class="btn-action"
                    [disabled]="!formName.valid || formName.pristine
                    (click)="submit()"
                    id="saveInc">
        {{labels.BTN_CREER}}
      </paper-button>
    </div>
  </footer>
</div>
</code>```

and the TS file :

```<code>    @Component({
      selector: 'enter-data-container',
      templateUrl: './enter-data-container.component.html',
      styleUrls: ['./enter-data-container.component.scss']
    })
    export class EnterDataContainerComponent {
  @Input() enterData: EnterData<any>;
  @Input() formName: FormGroup;

    constructor(private store: Store<AppState>,
                  private  location: Location) {
      }
    /**
       * On submit du form
       */
      submit() {
     // Send Data to service

    }
    /**
       * on click cancel
       */
      close(): void {
          this.location.back();
      }
    }
</code>```

In many form I have in my app, the submit is always the same, but sometimes, it's slightly different.
So I want to give the possibility to override the submit function when it's needed.
How can I achieve that with Angular 2/4 ?

答:
Use $event.preventDefault()  </p>

```<code><paper-button class="btn-cancel-alt" type="reset" (click)="close(); $event.preventDefault()" id="cancelInc">{{labels.BTN_ANNULER}}
      </paper-button>
</code>```

Body:
I have a component Angular containing my header and footer of all of my form like this :

 {{enterData?.title}}

  <form [formGroup]="formName" #form="ngForm" (ngSubmit)="submit()"
        class="layout vertical">
   <ng-content></ng-content>

  </form>

      <paper-button class="btn-cancel-alt" type="reset" (click)="close()" id="cancelInc">{{labels.BTN_ANNULER}}
      </paper-button>
      <paper-button class="btn-action"
                    [disabled]="!formName.valid || formName.pristine
                    (click)="submit()"
                    id="saveInc">
        {{labels.BTN_CREER}}
      </paper-button>

and the TS file :

    @Component({
      selector: 'enter-data-container',
      templateUrl: './enter-data-container.component.html',
      styleUrls: ['./enter-data-container.component.scss']
    })
    export class EnterDataContainerComponent {
  @Input() enterData: EnterData<any>;
  @Input() formName: FormGroup;

    constructor(private store: Store<AppState>,
                  private  location: Location) {
      }
    /**
       * On submit du form
       */
      submit() {
     // Send Data to service

    }
    /**
       * on click cancel
       */
      close(): void {
          this.location.back();
      }
    }

In many form I have in my app, the submit is always the same, but sometimes, it's slightly different.
So I want to give the possibility to override the submit function when it's needed.
How can I achieve that with Angular 2/4 ?

Body:
Use $event.preventDefault()

<paper-button class="btn-cancel-alt" type="reset" (click)="close(); $event.preventDefault()" id="cancelInc">{{labels.BTN_ANNULER}}
      </paper-button>


问:
How do I determine if my python shell is executing in 32bit or 64bit?
How can I tell what mode the shell is in, from within the shell?

I've tried looking at the platform module, but it seems only to tell you about "the bit architecture and the linkage format used for the executable". My binary is compiled as 64bit (I'm running on OS X 10.6), so it seems to always report 64bit even though I'm using the methods described here to force 32bit mode.

答:
Platform Architecture is not the reliable way.
Instead us:</p>

```<code>$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)
</code>```

Body:
Platform Architecture is not the reliable way.
Instead us:

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)


问:
Identifying different date formats in Python
I am reading a column from a csv file that contains dates in different formats.

I am trying to write each unique date format to a text file. Some examples of the unique data formats are shown below.

2006

09/12/12

12-24-07

April 10, 2013

29 April 1993

September 2011

March 7

1830s

Friday, 12 February 2010

Thursday, April 19

12th May 2011

413 BC

My Code:

from datetime import datetime

import csv

with open('train.csv', 'rb') as f_input, open('sample.txt', 'wb') as f_output:

```<code>csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
header = next(csv_input)

for row in csv_input:
    for date_format in ['%Y','%m/%d/%y']:
        try:
            converted = datetime.strptime(row[3], date_format)
            csv_output.writerow([row[0], row[1], converted.strftime(date_format)])
        except ValueError:
            pass
</code>```

Now, I have figured out the first two formats so far in the line:
 for date_format in ['%Y','%m/%d/%y']:

I am now sure how the other formats are going to be translated. Any suggestions ?

答:
Example using dateutil</p>

```<code>from dateutil.parser import *

dates = ["2005","2006","4 March 2013","5 April 2012","14th February 2012","7th
January 2014","April 10, 2014","March 3, 2017","October 1st, 1943","Dec 23rd,
1978"]

for date in dates:
  print(dateutil.parser.parse(date))
</code>```

Body:
I am reading a column from a csv file that contains dates in different formats.

I am trying to write each unique date format to a text file. Some examples of the unique data formats are shown below.

2006

09/12/12

12-24-07

April 10, 2013

29 April 1993

September 2011

March 7

1830s

Friday, 12 February 2010

Thursday, April 19

12th May 2011

413 BC

My Code:

from datetime import datetime

import csv

with open('train.csv', 'rb') as f_input, open('sample.txt', 'wb') as f_output:

csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
header = next(csv_input)

for row in csv_input:
    for date_format in ['%Y','%m/%d/%y']:
        try:
            converted = datetime.strptime(row[3], date_format)
            csv_output.writerow([row[0], row[1], converted.strftime(date_format)])
        except ValueError:
            pass

Now, I have figured out the first two formats so far in the line:
 for date_format in ['%Y','%m/%d/%y']:

I am now sure how the other formats are going to be translated. Any suggestions ?

Body:
Example using dateutil

from dateutil.parser import *

dates = ["2005","2006","4 March 2013","5 April 2012","14th February 2012","7th
January 2014","April 10, 2014","March 3, 2017","October 1st, 1943","Dec 23rd,
1978"]

for date in dates:
  print(dateutil.parser.parse(date))


问:
how to set layout in multiple screen size in android
```<code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="2">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/increment_5x"
            android:paddingLeft="@dimen/baseline_grid_7x"
            android:paddingRight="@dimen/baseline_grid_7x"
            android:paddingTop="@dimen/baseline_grid_7x">

            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/textView"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
            android:addOnPageChangeListener="@{landingLoginViewModel.pageChangeListener}"
                app:adapter="@{imageSlideradapter}"
                app:currentItem="@{landingLoginViewModel.currentPage}" />            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/indicator"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:lineSpacingExtra="@dimen/text_land_spacing"
                android:paddingTop="@dimen/layout_padding_top"
                android:text="@string/label_businesscard_title"
                android:textColor="#3e4360"
                android:textSize="@dimen/businees_card_textmessage_size"
                android:textStyle="normal" />
                <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:paddingTop="@dimen/padding_top_15dp"
                app:centered="true"
                app:fillColor="@color/colorTurquoiseBlue"
                app:pageColor="@color/colorPager"
                app:radius="@{landingLoginViewModel.pagerIndicatorCircle}"
                app:snap="false" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/relativelayout_top_height_350_dp"
            android:paddingLeft="@dimen/baseline_grid_2.5x"
            android:paddingRight="@dimen/baseline_grid_2.5x"
            android:paddingTop="@dimen/baseline_grid_5x">

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btn_signin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/buttonbackroudnd"
                android:onClick="@{()->landingLoginViewModel.onSignIn()}"
                android:text="@string/label_sign_in"
                android:textColor="#ffffff" />

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btn_signup"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btn_signin"
                android:layout_marginTop="@dimen/baseline_grid_3.5x"
                android:background="@drawable/roundbuttonborder"
                android:onClick="@{()->landingLoginViewModel.onSignUp()}"
                android:text="@string/label_sign_up"
                android:textColor="#00becc" />

            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/oRtextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btn_signup"
                android:layout_marginTop="@dimen/baseline_grid_5.5x"
                android:gravity="center"
                android:text="@string/label_or"
                android:textColor="@color/colorDarkGrey"
                style="@style/Regular.Body2"
                />
            <ImageView
                android:id="@+id/faceBookIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/fb_icon"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/oRtextLabel"
                android:layout_marginTop="@dimen/baseline_grid_5x"
                android:gravity="center"
                android:layout_marginLeft="75dp"
                />

            <android.support.v7.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:paddingLeft="@dimen/baseline_grid_1x"
                android:text="@string/label_fcebook"
                android:textColor="@color/facebookTextColor"
                android:textSize="@dimen/baseline_grid_2x"
                android:textStyle="normal"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/oRtextLabel"
                android:layout_toRightOf="@+id/faceBookIcon"
                android:layout_marginTop="@dimen/baseline_grid_5x"
                android:gravity="center"
                android:onClick="@{()->landingLoginViewModel.onFacebook()}"
                />

        </RelativeLayout>
    </LinearLayout>
</ScrollView>
</code>```

this is my Screen size i have created folder for differnet screen size in valued folder the screen which i have is designed in xhdpi but i have to support in all screen without scrolling i tried with different size in value   accrding this formula

mdpi=56/2=28dp
hdpif=42dp
xhdpi-56 dp
xxhdpi=84dp
xxxhdpi=112 dp

but this is not working still scrolling is there can any one please suggest me how to fix it how to set layout in all screen size

答:
I think you should try to design 5 layouts for one screen and make sure if you don't want to give scroll then remove one from 5 layouts

1.mdpi: // suppose i am giving scroll for small devices

2.hdpi

3.xhdpi    // up to this , i don't need scroll

4.xxhdpi

5.xxxhdpi

Note: resources and id , if you are using in main Activity keep same in all layouts otherwise you can get null pointer exception.

Body:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="2">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/increment_5x"
            android:paddingLeft="@dimen/baseline_grid_7x"
            android:paddingRight="@dimen/baseline_grid_7x"
            android:paddingTop="@dimen/baseline_grid_7x">

            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/textView"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
            android:addOnPageChangeListener="@{landingLoginViewModel.pageChangeListener}"
                app:adapter="@{imageSlideradapter}"
                app:currentItem="@{landingLoginViewModel.currentPage}" />            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/indicator"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:lineSpacingExtra="@dimen/text_land_spacing"
                android:paddingTop="@dimen/layout_padding_top"
                android:text="@string/label_businesscard_title"
                android:textColor="#3e4360"
                android:textSize="@dimen/businees_card_textmessage_size"
                android:textStyle="normal" />
                <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/indicator"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:paddingTop="@dimen/padding_top_15dp"
                app:centered="true"
                app:fillColor="@color/colorTurquoiseBlue"
                app:pageColor="@color/colorPager"
                app:radius="@{landingLoginViewModel.pagerIndicatorCircle}"
                app:snap="false" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/relativelayout_top_height_350_dp"
            android:paddingLeft="@dimen/baseline_grid_2.5x"
            android:paddingRight="@dimen/baseline_grid_2.5x"
            android:paddingTop="@dimen/baseline_grid_5x">

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btn_signin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/buttonbackroudnd"
                android:onClick="@{()->landingLoginViewModel.onSignIn()}"
                android:text="@string/label_sign_in"
                android:textColor="#ffffff" />

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btn_signup"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btn_signin"
                android:layout_marginTop="@dimen/baseline_grid_3.5x"
                android:background="@drawable/roundbuttonborder"
                android:onClick="@{()->landingLoginViewModel.onSignUp()}"
                android:text="@string/label_sign_up"
                android:textColor="#00becc" />

            <android.support.v7.widget.AppCompatTextView
                android:id="@+id/oRtextLabel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btn_signup"
                android:layout_marginTop="@dimen/baseline_grid_5.5x"
                android:gravity="center"
                android:text="@string/label_or"
                android:textColor="@color/colorDarkGrey"
                style="@style/Regular.Body2"
                />
            <ImageView
                android:id="@+id/faceBookIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/fb_icon"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/oRtextLabel"
                android:layout_marginTop="@dimen/baseline_grid_5x"
                android:gravity="center"
                android:layout_marginLeft="75dp"
                />

            <android.support.v7.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-medium"
                android:paddingLeft="@dimen/baseline_grid_1x"
                android:text="@string/label_fcebook"
                android:textColor="@color/facebookTextColor"
                android:textSize="@dimen/baseline_grid_2x"
                android:textStyle="normal"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/oRtextLabel"
                android:layout_toRightOf="@+id/faceBookIcon"
                android:layout_marginTop="@dimen/baseline_grid_5x"
                android:gravity="center"
                android:onClick="@{()->landingLoginViewModel.onFacebook()}"
                />

        </RelativeLayout>
    </LinearLayout>
</ScrollView>

this is my Screen size i have created folder for differnet screen size in valued folder the screen which i have is designed in xhdpi but i have to support in all screen without scrolling i tried with different size in value   accrding this formula

mdpi=56/2=28dp
hdpif=42dp
xhdpi-56 dp
xxhdpi=84dp
xxxhdpi=112 dp

but this is not working still scrolling is there can any one please suggest me how to fix it how to set layout in all screen size