问:
My popups are at bottom:0; but after you hover over them 2-3 times they keep going up?
My blog has these popups, and they are at bottom 0. But when you hover over them twice or more times they begin to go up farther each time you hover. Any way to prevent?

Edit: The reason it's doing this is because each time it hovers, the "bottom" resets so it's going -10px from where it last was. I don't know how to stop this.

Answer: I added info.css("bottom', '-10px'); and that fixed it. Thanks to all who answered, though.

答: Are you setting the position on rollover? If so, try setting the position at load and just turning the display on/off at mouseover/mouseout. </p>


来源: stackexchange

问:
If statement based on user input
Trying to run a if statement based off a user input, would this be the correct way? So if the user is on a subscription then isSubscription is true.   </p>

```<code>var subscription = window.alert("Is this a subscription? (Y/N)");
    if (subscription == "Y") {
        isSubscription = true;
      } else {
        isSubscription = false;
        window.alert("No activation key");
      }
</code>```

答:
Try to use window.confirm. It has built in yes/no feature, where value returned are true for yes/ok and false for no/cancel.

So your code would look like

isSubscription = window.confirm("Is this a subscription?")

Read more at:

https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm

ContentLicense: CC BY-SA 3.0

Title: If statement based on user input

Body:
Trying to run a if statement based off a user input, would this be the correct way? So if the user is on a subscription then isSubscription is true.

var subscription = window.alert("Is this a subscription? (Y/N)");
    if (subscription == "Y") {
        isSubscription = true;
      } else {
        isSubscription = false;
        window.alert("No activation key");
      }


问:
Get file url from sharepoint by name
I'm able to save document in Sharepoint documents. Once the document is saved I want to be able to get the url of that document so I can share the url with a user.

This is the code I'm using to save the document:

using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com"))
{
    SecureString passWord = new SecureString();
    foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
    clientContext.Credentials = new SharePointOnlineCredentials("myaccount@mydomain.com", passWord);
    Web web = clientContext.Web;
    FileCreationInformation newFile = new FileCreationInformation();
    //newFile.Content = System.IO.File.ReadAllBytes(filePath);
    byte[] docData = null;
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        docData = ms.ToArray();
    }
    newFile.Content = docData;
    newFile.Url = originalFileName;

    List docs = web.Lists.GetByTitle("DOCUMENTS");
    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
    clientContext.ExecuteQuery();
}
```

How I can get the URL of that document once it's uploaded?

答:
You can use either of the below 3 methods. To share a document, you can generate anonymous link, anon link with expiration date or share and send it via email.

```<code>List docs = web.Lists.GetByTitle("DOCUMENTS");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();

clientContext.Load(uploadFile.ListItemAllFields, item => item["EncodedAbsUrl"]);
clientContext.ExecuteQuery();

var fileUrl = uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString();

string link = clientContext.Web.CreateAnonymousLinkForDocument(fileUrl, ExternalSharingDocumentOption.View);

string linkwithExpiration = clientContext.Web.CreateAnonymousLinkWithExpirationForDocument(fileUrl, ExternalSharingDocumentOption.Edit, DateTime.Now.AddMonths(1));

SharingResult result = clientContext.Web.ShareDocument(fileUrl, "someone@example.com", ExternalSharingDocumentOption.View, true, "Doc shared programmatically");
</code>```

Ensure that external sharing capability is turned on.

Reference - Turn on external sharing in SPO

ContentLicense: CC BY-SA 4.0

Title: Get file url from sharepoint by name

Body:
I'm able to save document in Sharepoint documents. Once the document is saved I want to be able to get the url of that document so I can share the url with a user.

This is the code I'm using to save the document:

using (ClientContext clientContext = new ClientContext("https://mydomain.sharepoint.com"))
{
    SecureString passWord = new SecureString();
    foreach (char c in "mypassword".ToCharArray()) passWord.AppendChar(c);
    clientContext.Credentials = new SharePointOnlineCredentials("myaccount@mydomain.com", passWord);
    Web web = clientContext.Web;
    FileCreationInformation newFile = new FileCreationInformation();
    //newFile.Content = System.IO.File.ReadAllBytes(filePath);
    byte[] docData = null;
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        docData = ms.ToArray();
    }
    newFile.Content = docData;
    newFile.Url = originalFileName;

    List docs = web.Lists.GetByTitle("DOCUMENTS");
    Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
    clientContext.ExecuteQuery();
}

How I can get the URL of that document once it's uploaded?

Body:
You can use either of the below 3 methods. To share a document, you can generate anonymous link, anon link with expiration date or share and send it via email.

List docs = web.Lists.GetByTitle("DOCUMENTS");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();

clientContext.Load(uploadFile.ListItemAllFields, item => item["EncodedAbsUrl"]);
clientContext.ExecuteQuery();

var fileUrl = uploadFile.ListItemAllFields["EncodedAbsUrl"].ToString();

string link = clientContext.Web.CreateAnonymousLinkForDocument(fileUrl, ExternalSharingDocumentOption.View);

string linkwithExpiration = clientContext.Web.CreateAnonymousLinkWithExpirationForDocument(fileUrl, ExternalSharingDocumentOption.Edit, DateTime.Now.AddMonths(1));

SharingResult result = clientContext.Web.ShareDocument(fileUrl, "someone@example.com", ExternalSharingDocumentOption.View, true, "Doc shared programmatically");

Ensure that external sharing capability is turned on.

Reference - Turn on external sharing in SPO


问:
Android Studio 3.0: Unable to delete file
Android Studio 3.0

```<code>classpath 'com.android.tools.build:gradle:3.0.0'
</code>```

Sometimes when I try to start app I get the next error:

```<code>Error:java.io.IOException: Unable to delete file: myproject\common\build\intermediates\intermediate-jars\debug\classes.jar
> Unable to delete file: myproejct\common\build\intermediates\intermediate-jars\debug\classes.jar
</code>```

The proccess java.exe lock this. Why?

答:
You need to go to the source file directly. Close the studio or the project and go to the path the issue is located at and delete the folder there.

If this doesn't work try
Go to the File> Settings> Build,Execution,Deployment> Instant Run > Uncheck this Check box (Enable Instant Run)

And then  gradlew clean in the console

Body:
Android Studio 3.0

classpath 'com.android.tools.build:gradle:3.0.0'

Sometimes when I try to start app I get the next error:

Error:java.io.IOException: Unable to delete file: myproject\common\build\intermediates\intermediate-jars\debug\classes.jar
> Unable to delete file: myproejct\common\build\intermediates\intermediate-jars\debug\classes.jar

The proccess java.exe lock this. Why?


问:
Why can't I pass a const object in a const argument function/method?
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

```<code>int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}
</code>```

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

答:
I think you wanted this instead:</p>

```<code>void SomeClass::f(const MyClass*) const
{ ... }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
EDIT:

Sorry, I'm trying to understand a sample of code, which uses QList::indexOf method, declared as in here.

Actually I'm trying to figure out why I need to use const_cast in this specific case:

int ProjTreeItem::row() const
{
    if (parentItem) {
            // instance of const object to test
        const ProjTreeItem *item = new ProjTreeItem(QList<QVariant>(), NULL);
            // Called indexOf here to test
        parentItem->childItems.indexOf(item);
            // This works fine
        return parentItem->childItems.indexOf(const_cast<ProjTreeItem*>(this));
    }
    return 0;
}

EDIT2:

I was looking at the wrong places, then I started to suspect that the issue had to do with the use of templates and the const modifier. I found this thread here. Please, look at Jon 's answer, which I think clarifies the point I reached. Sorry for the misleadings on my question.

Body:
I think you wanted this instead:

void SomeClass::f(const MyClass*) const
{ ... }


问:
Button with mysql query in action
I created a dropdown list with 6 options.

After select an option and clicking the submit button, the selected value should be inserted into the mysql database. This is code:

```<code><form name="name" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<select id="broj" name="name">
  <option value="0">--Select--</option>
  <option value="2">Option 1</option>
  <option value="3">Option 2</option>
  <option value="4">Option 3</option>
  <option value="5">Option 4</option>
  <option value="6">Option 5</option>
  <option value="7">Option 6</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>

<?php
if($_GET){
   $result= $_GET['name'];
  }
?>
//
After this follows the code that inserts the $result into the mysql database
</code>```

I have two problems with this code:

As soon as the page is opened (before clicking the button) , the value 0 is inserted into the database (value of "Select" option)

After refreshing page, the selected value is re-insert into the database

How to make the selected option inserted into the database only when the submit button is clicked

答:
First visit to the page inserts a 0-value row:

The relevant code for this is excluded from your question, but you should always check that your $_GET (or $_POST, or $_REQUEST, or $_SESSION, etc) array has at least one value (eg if (count($_GET))) before inserting. However, I would suggest that you use the POST method rather than GET. It's one tiny layer of obfuscation for someone trying to force data into your DB, and it makes it a lot harder for accidents/mistyped URLs to insert random data.

Resubmitted data:

This has a few ways to work around it. Most people simply set the POST method for their forms, rather than GET (there are some standards that say you should use POST, but I won't get into that). If the user attempts to refresh a page that a form POSTed to, most modern browsers will pop up a confirmation dialogue box before resubmitting the form data.

Another common technique is to redirect from the form's target page once the data has been inserted into the database. That way the user can't refresh the page. In other words, you would have a blank form response page that simply does the DB insert and then redirects to a page with a "thank you for submitting the form" text, or whatever you want to display after the form is submitted. The user's browser never sits on the URL/page that does the actual DB insert.

You could also do a little validation before doing the insert. If you don't want to query your DB before inserting (or apply a DB-level constraint, like a unique index on the table), you could have each form submit a one-use token with each request. If a form gets submitted with that token a second time, then you know it was a resubmit. A simple example of this might be to add a captcha to your form.

Title: Button with mysql query in action

Body:
I created a dropdown list with 6 options.

After select an option and clicking the submit button, the selected value should be inserted into the mysql database. This is code:

<form name="name" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<select id="broj" name="name">
  <option value="0">--Select--</option>
  <option value="2">Option 1</option>
  <option value="3">Option 2</option>
  <option value="4">Option 3</option>
  <option value="5">Option 4</option>
  <option value="6">Option 5</option>
  <option value="7">Option 6</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>

<?php
if($_GET){
   $result= $_GET['name'];
  }
?>
//
After this follows the code that inserts the $result into the mysql database

I have two problems with this code:

As soon as the page is opened (before clicking the button) , the value 0 is inserted into the database (value of "Select" option)

After refreshing page, the selected value is re-insert into the database

How to make the selected option inserted into the database only when the submit button is clicked


问:
How does TestCafe, the open source tool, relate to DevExpress TestCafe, the $249.99 dollars per year application?
Do the two of them integrate somehow? The relation between the two is confusing and they have the same name.
Can the $249.99 tool be used to run tests written using the open-source API?</p>

答:
TestCafe first appeared as a paid, standalone tool. It had several features besides the test runner: the Control Panel, a visual interface for creating, modifying and running your tests, and the Visual Test Recorder for recording tests by pointing and clicking through the test scenario in the browser.

In 2015 we decided to release the TestCafe core as an open-source project. The last major paid version release (v15.1) was in summer 2015. After that, it switched to a maintenance-only mode. You can find the latest paid version at https://testcafe.devexpress.com.

We released the open-source TestCafe in late 2016. It has the same name but contains lots of new functionality and improvements:

a new API and offers a new approach to writing tests;

no UI to manage and run tests. You can run tests from the CLI or node.js module;

it is more convenient to integrate into node.js development workflow;

es6 support, flexible selectors and smart assertions, authentication features, etc.

You can learn more about the open-source version at https://devexpress.github.io/testcafe.

We have not abandoned our aspirations to create a competitive proprietary product. We plan to release a new commercial version called TestCafe Studio, based on the revised open-source TestCafe.


答:
You need idxmax with
idxmin and then concat:

```<code>#if necessary
#df['Date'] = pd.to_datetime(df['Date'])

df1 = df.loc[df.groupby('Stock')['relativevolatility'].idxmin()].set_index('Stock')
df2 = df.loc[df.groupby('Stock')['relativevolatility'].idxmax()].set_index('Stock')

df = pd.concat([df1, df2], axis=1, keys=('min','max'))
df.columns = df.columns.map('_'.join)
print (df)
           min_Date  min_relativevolatility   max_Date  max_relativevolatility
Stock
AA.csv   2012-11-23                0.010791 2012-11-28                0.030102
ZION.csv 2012-02-14                0.016287 2012-02-15                0.018929
</code>```

and weekday_name with aggregate mean:

```<code>df = (df.groupby(['Stock', df['Date'].dt.weekday_name])['relativevolatility']
        .mean()
        .reset_index(name='means'))
print (df)
      Stock       Date     means
0    AA.csv     Friday  0.016923
1    AA.csv     Monday  0.016428
2    AA.csv   Thursday  0.017448
3    AA.csv    Tuesday  0.018386
4    AA.csv  Wednesday  0.020324
5  ZION.csv    Tuesday  0.016287
6  ZION.csv  Wednesday  0.018929
</code>```

Title: How to find the max/min values using groupby with dates?

Body:
Below is my dataframe. It has multiple stocks. I am trying to find out two things from this data.

1) How can I find the date with the min/max relative volatility for all the stocks. This means the maximum and minimum relative volatility for every stock with the corresponding date.

         Stock   Date              relativevolatility
0        AA.csv 2012-12-31            0.024419
1        AA.csv 2012-12-28            0.012888
2        AA.csv 2012-12-27            0.026482
3        AA.csv 2012-12-26            0.018423
4        AA.csv 2012-12-24            0.013994
5        AA.csv 2012-12-21            0.017422
6        AA.csv 2012-12-20            0.011541
7        AA.csv 2012-12-19            0.026316
8        AA.csv 2012-12-18            0.018120
9        AA.csv 2012-12-17            0.019406
10       AA.csv 2012-12-14            0.018454
11       AA.csv 2012-12-13            0.017411
12       AA.csv 2012-12-12            0.012673
13       AA.csv 2012-12-11            0.019699
14       AA.csv 2012-12-10            0.016442
15       AA.csv 2012-12-07            0.016403
16       AA.csv 2012-12-06            0.014011
17       AA.csv 2012-12-05            0.022340
18       AA.csv 2012-12-04            0.016677
19       AA.csv 2012-12-03            0.011862
20       AA.csv 2012-11-30            0.015458
21       AA.csv 2012-11-29            0.017794
22       AA.csv 2012-11-28            0.030102
23       AA.csv 2012-11-27            0.016888
24       AA.csv 2012-11-26            0.012019
25       AA.csv 2012-11-23            0.010791
26       AA.csv 2012-11-21            0.012092
27       AA.csv 2012-11-20            0.020544
28       AA.csv 2012-11-19            0.016857
29       AA.csv 2012-11-16            0.027044
        ...        ...                 ...
70666  ZION.csv 2012-02-15            0.018929
70667  ZION.csv 2012-02-14            0.016287

Attempt #1
df2.groupby(['Date','Stock'])['relativevolatility'].sum().idxmax()

This gives me a time/stock, but only for one stock and I am not sure i am even getting the maximum relative-volatility for that stock.

Attempt #2
new.groupby(['Stock'])['relativevolatility'].agg([pd.np.min, pd.np.max])

This gives me all the min/max's for the stocks, but I can't figure out how to add a column for when the min and max occurred for each stock.

Question #1

How can I print a table that gives me all of the stock's min/max relative volatility with the dates for when the min/max occurred for the stocks?

Question #2

How can find the average relative volatility, but for each day of the week for all the stocks?

Body:
You need idxmax with
idxmin and then concat:

#if necessary
#df['Date'] = pd.to_datetime(df['Date'])

df1 = df.loc[df.groupby('Stock')['relativevolatility'].idxmin()].set_index('Stock')
df2 = df.loc[df.groupby('Stock')['relativevolatility'].idxmax()].set_index('Stock')

df = pd.concat([df1, df2], axis=1, keys=('min','max'))
df.columns = df.columns.map('_'.join)
print (df)
           min_Date  min_relativevolatility   max_Date  max_relativevolatility
Stock
AA.csv   2012-11-23                0.010791 2012-11-28                0.030102
ZION.csv 2012-02-14                0.016287 2012-02-15                0.018929

and weekday_name with aggregate mean:

df = (df.groupby(['Stock', df['Date'].dt.weekday_name])['relativevolatility']
        .mean()
        .reset_index(name='means'))
print (df)
      Stock       Date     means
0    AA.csv     Friday  0.016923
1    AA.csv     Monday  0.016428
2    AA.csv   Thursday  0.017448
3    AA.csv    Tuesday  0.018386
4    AA.csv  Wednesday  0.020324
5  ZION.csv    Tuesday  0.016287
6  ZION.csv  Wednesday  0.018929


问:
R: divide variable in dataframe by specific value from list or vector
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

```<code>Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3
</code>```

答:
```<code>df1$Response/df2$Sampling_effort[match(df1$Location, df2$Location)]
#[1] 12.500000  9.692308  1.876667
</code>```

Body:
I'm a newb at R, so forgive my ignorance.

I have a dataframe that consists of two variables: Location and response. I have another dataframe that consists of sampling effort at each location. I need to divide the response by the sampling effort using the location as the identifier. I know there is probably an easy solution, but I'm striking out finding it. I would appreciate any help.

Example:
Dataframe 1

Location Response

Loc1     25

Loc2     63

Loc3     5.63

Dataframe2

Location Sampling effort

Loc1     2

Loc2     6.5

Loc3     3


问:
How to insert from two lists into a list of dictionaries with identical keynames in Python 3.6.1
I am a newbie to Python and dictionaries. Using Python 3.6.1. I have googled similar issues, but it seems like solutions that others use involve dictionaries with different keys, and that many answers are related to older versions of Python. Any help is appreciated!

I have the following list of dictionaries that returns this when printed:

```<code>[{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None}]
</code>```

I have the following lists from which I want to insert the values into the above list of dictionaries:

```<code>coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']

coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]

heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']

heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]
</code>```

From these lists I want to insert the values into the list of dictionaries. So that the result follows the following pattern:
the first entry of the first valuelist will correspond to the first value of the second valuelist (where both end up in the same dictionary).
Obviously I would wish to not use the coordkeys, and heightkeys lists if that is possible.

To illlustrate the pattern the end result will have, with all the values from both lists, the end result starts as follows:

[{'Coordinate': [44,33], 'Height': 333},
    {'Coordinate': [55,22], 'Height': 444},
    # And so on until the end of both lists
    ]

I tried to play with only one list as follows:

```<code>geographic_details = dict(list(zip(coordkeys, coordvalues)))
</code>```

But a print of the output returns only the last entry from the coordinate-values list, and not all of the values from the list:

```<code>{'Coordinate': [79, 91]}
</code>```

So obviously only the last key-value pair is kept, because there are several keys with the same name. zip or this way of using zip seems like not the way to go here.

EDIT:

I tried adding from both lists by doing this, but it seems like this is not allowed.:

This last line of code missed an ending parenthesis. Now I added it so it looks like this:

```<code>geographic_details = dict(list(zip(coordkeys, coordvalues), zip(heightkeys, heightvalues)))
</code>```

However a new error is returned:

```<code>TypeError: list() takes at most 1 argument (2 given)
</code>```

答:
Given that there are equal sized lists map function looks like the most elegant way of creating the desired data structure.

```<code>coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']
coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]
heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']
heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]

def convert(c, cval, h, hval):
    return {c:cval, h:hval}

assert list(map(convert, coordkeys, coordvalues, heightkeys, heightvalues)) == [{'Coordinate': [44, 33], 'Height': 333},
    {'Coordinate': [55, 22], 'Height': 444},
    {'Coordinate': [77, 66], 'Height': 555},
    {'Coordinate': [88, 99], 'Height': 666},
    {'Coordinate': [77, 11], 'Height': 777},
    {'Coordinate': [46, 78], 'Height': 888},
    {'Coordinate': [44, 33], 'Height': 999},
    {'Coordinate': [13, 92], 'Height': 222},
    {'Coordinate': [21, 69], 'Height': 2222},
    {'Coordinate': [79, 91], 'Height': 3333}]
</code>```

Body:
I am a newbie to Python and dictionaries. Using Python 3.6.1. I have googled similar issues, but it seems like solutions that others use involve dictionaries with different keys, and that many answers are related to older versions of Python. Any help is appreciated!

I have the following list of dictionaries that returns this when printed:

[{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None}]

I have the following lists from which I want to insert the values into the above list of dictionaries:

coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']

coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]

heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']

heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]

From these lists I want to insert the values into the list of dictionaries. So that the result follows the following pattern:
the first entry of the first valuelist will correspond to the first value of the second valuelist (where both end up in the same dictionary).
Obviously I would wish to not use the coordkeys, and heightkeys lists if that is possible.

To illlustrate the pattern the end result will have, with all the values from both lists, the end result starts as follows:

[{'Coordinate': [44,33], 'Height': 333},
    {'Coordinate': [55,22], 'Height': 444},
    # And so on until the end of both lists
    ]

I tried to play with only one list as follows:

geographic_details = dict(list(zip(coordkeys, coordvalues)))

But a print of the output returns only the last entry from the coordinate-values list, and not all of the values from the list:

{'Coordinate': [79, 91]}

So obviously only the last key-value pair is kept, because there are several keys with the same name. zip or this way of using zip seems like not the way to go here.

EDIT:

I tried adding from both lists by doing this, but it seems like this is not allowed.:

This last line of code missed an ending parenthesis. Now I added it so it looks like this:

geographic_details = dict(list(zip(coordkeys, coordvalues), zip(heightkeys, heightvalues)))

However a new error is returned:

TypeError: list() takes at most 1 argument (2 given)

Body:
Given that there are equal sized lists map function looks like the most elegant way of creating the desired data structure.

coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']
coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]
heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']
heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]

def convert(c, cval, h, hval):
    return {c:cval, h:hval}

assert list(map(convert, coordkeys, coordvalues, heightkeys, heightvalues)) == [{'Coordinate': [44, 33], 'Height': 333},
    {'Coordinate': [55, 22], 'Height': 444},
    {'Coordinate': [77, 66], 'Height': 555},
    {'Coordinate': [88, 99], 'Height': 666},
    {'Coordinate': [77, 11], 'Height': 777},
    {'Coordinate': [46, 78], 'Height': 888},
    {'Coordinate': [44, 33], 'Height': 999},
    {'Coordinate': [13, 92], 'Height': 222},
    {'Coordinate': [21, 69], 'Height': 2222},
    {'Coordinate': [79, 91], 'Height': 3333}]


问:
Visibility about the UIBarButtonItem in UINavigationItem
In Interface Builder, I did't give the UIBarButtonItem a title, then the UIBarButtonItem was not appear when it was running.
I want to control it in my code, but when I set the title property of UIBarButtonItem to @"", the bar button was not disappear instead.
I don't know if there is a property to control the visibility of UIBarButtonItem in UINavigationItem.
Thanks a lot!</p>

答:
Check out the UIBarButtonItem Class Reference.

You can also try self.navigationItem.leftBarButtonItem = nil;


问:
How does the Apache Spark scheduler split files into tasks?
In spark-summit 2014, Aaron gives the speak A Deeper Understanding of Spark Internals  , in his slide, page 17 show a stage has been splited into 4 tasks as bellow:

Here I wanna know three things about how does a stage be splited into tasks?

in this example above, it seems that tasks' number are created based on the file number, am I right?

if I'm right in point 1, so if there was just 3 files under directory names, will it just create 3 tasks?

If I'm right in point 2, what if there is just one but very large file? Does it just split this stage into 1 task? And what if when the data is coming from a streaming data source?

thanks a lot, I feel confused in how does the stage been splited into tasks.

答:
Stage: New stage will get created when a wide transformation occurs

Task: Will get created based on partitions in a worker

Attaching the link for more explanation: How DAG works under the covers in RDD?


问:
Sort string with integers and words without any change in their positions
Say I have a string a.

```<code>a = "12 I have car 8 200 a"
</code>```

I need to sort this string in such a way that the output should be

```<code>8 a car have 12 200 I
</code>```

ie, Sort the string in such a way that all words are in alphabetical order and all integers are in numerical order. Furthermore, if the nth element in the string is an integer it must remain an integer, and if it is a word it must remain a word.

This is what I tried.

```<code>a = "12 I have car 8 200 a"

def is_digit(element_):
    """
    Function to check the item is a number. We can make using of default isdigit function
    but it will not work with negative numbers.
    :param element_:
    :return: is_digit_
    """
    try:
        int(element_)
        is_digit_ = True
    except ValueError:
        is_digit_ = False

    return is_digit_

space_separated = a.split()

integers = [int(i) for i in space_separated if is_digit(i)]
strings = [i for i in space_separated if i.isalpha()]

# sort list in place
integers.sort()
strings.sort(key=str.lower)

# This conversion to iter is to make use of next method.
int_iter = iter(integers)
st_iter = iter(strings)

final = [next(int_iter) if is_digit(element) else next(st_iter) if element.isalpha() else element for element in
         space_separated]

print " ".join(map(str, final))
# 8 a car have 12 200 I
</code>```

I am getting the right output. But I am using two separate sorting function for sorting integers and the words(which I think is expensive).

Is it possible to do the entire sorting using a single sort function?.

答:
```<code>s = "2 is a A -3 car 11 I 0 a"

def magick(s):
  s = s.split()

  def reverse(tuples):
    return [(a, b) for (b, a) in tuples]

  def do_sort(tuples):
    firsts  = [a for a, _ in tuples]
    seconds = [a for _, a in tuples]
    return list(zip(sorted(firsts), seconds))

  def str_is_int(x):
    try:
      int(x)
      return True
    except:
      return False

  indexed = list(enumerate(s))

  ints = do_sort([(int(x), ix) for (ix, x) in indexed if     str_is_int(x)])
  strs = do_sort([(    x , ix) for (ix, x) in indexed if not str_is_int(x)])

  return ' '.join([str(b) for _, b in sorted(reverse(ints+strs))])

print(magick(s))
</code>```

Body:
Say I have a string a.

a = "12 I have car 8 200 a"

I need to sort this string in such a way that the output should be

8 a car have 12 200 I

ie, Sort the string in such a way that all words are in alphabetical order and all integers are in numerical order. Furthermore, if the nth element in the string is an integer it must remain an integer, and if it is a word it must remain a word.

This is what I tried.

a = "12 I have car 8 200 a"

def is_digit(element_):
    """
    Function to check the item is a number. We can make using of default isdigit function
    but it will not work with negative numbers.
    :param element_:
    :return: is_digit_
    """
    try:
        int(element_)
        is_digit_ = True
    except ValueError:
        is_digit_ = False

    return is_digit_

space_separated = a.split()

integers = [int(i) for i in space_separated if is_digit(i)]
strings = [i for i in space_separated if i.isalpha()]

# sort list in place
integers.sort()
strings.sort(key=str.lower)

# This conversion to iter is to make use of next method.
int_iter = iter(integers)
st_iter = iter(strings)

final = [next(int_iter) if is_digit(element) else next(st_iter) if element.isalpha() else element for element in
         space_separated]

print " ".join(map(str, final))
# 8 a car have 12 200 I

I am getting the right output. But I am using two separate sorting function for sorting integers and the words(which I think is expensive).

Is it possible to do the entire sorting using a single sort function?.


问:
Finding primeNumber and repDigit fails
I have a method for finding, wheter a number is a prime or not. It is working in my test class, but when I am using System.outprintf, it fails.
Same for the repDigit method.

Any help would be appreciated

Method for finding prime number:

```<code>/**
     * Checks whether the number is a prime number.
     *
     * @param number Any number
     * @return true if the number is prime, otherwise false
     */
    public static boolean isPrime(int number) {
        boolean isPrime = true;
        if (number < 2) {
            isPrime = false;
        } else {
            // Start counting from two to begin with even numbers
            for (int i = 2; i < number/2; ++i) {
                if (number % i == 0) {
                    isPrime = false;
                }
            }
        }
        return isPrime;
    }
</code>```

Method for finding repDigit:

```<code> /**
 * This method checks if numbers, after each other, are the same. We take
 * modulus of the number, in order to get the last digit, as long as the
 * number is above 0. The number is divided by 10, to end up with all
 * remaining numbers. Then it checks, if the last digit + the remaining are
 * the same
 *
 * @param number
 * @return
 */
public static boolean isRepDigit(int number) {
    int repDigit = number % 10;
    boolean toReturn = true;
    if (number < 10) {
        toReturn = false;
    } else {
        while (number > 0) {
            int digit = number % 10;
            number = number / 10;
            if (repDigit != digit) {
                toReturn = false;
            }
        }
    }
    return toReturn;
}
</code>```

Main method:

```<code>    public static void main(String[] args) {
    final int START = 5;
    final int END = 100;
    final int SPACE = digitCount(END);
    for (int i = START; i < END; i++) {

        System.out.printf("%" + SPACE + "d is a repdigit &n", isRepDigit(i));
        System.out.printf("%" + SPACE + "d is a prime &n", isPrime(i));
    }
}
</code>```

Error message:

```<code>Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Boolean
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Grp17_ueb01.main(Grp17_ueb01.java:164)
C:\Users\rasmu\Documents\NetBeansProjects\ueb01\nbproject\build-impl.xml:1040: The following error occurred while executing this line:
C:\Users\rasmu\Documents\NetBeansProjects\ueb01\nbproject\build-impl.xml:805: Java returned: 1
BUILD FAILED (total time: 1 second)
</code>```

答:
I think you misunderstood the meaning of the second argument of printf.
Here d in your string is supposed to be replaced by as a decimal, given as second argument. And the boolean isRepDigit(i) cannot be converted as a decimal.

The printf method documentation may be found here.

The Format string syntax is explained here.

What I think you wanted is:

```<code>    if (isRepDigit(i)) {
        System.out.printf("%" + SPACE + "d is a repdigit \n", i);
    }
    if (isPrime(i)) {
        System.out.printf("%" + SPACE + "d is a prime \n", i);
    }
</code>```

Title: Finding primeNumber and repDigit fails

Body:
I have a method for finding, wheter a number is a prime or not. It is working in my test class, but when I am using System.outprintf, it fails.
Same for the repDigit method.

Any help would be appreciated

Method for finding prime number:

/**
     * Checks whether the number is a prime number.
     *
     * @param number Any number
     * @return true if the number is prime, otherwise false
     */
    public static boolean isPrime(int number) {
        boolean isPrime = true;
        if (number < 2) {
            isPrime = false;
        } else {
            // Start counting from two to begin with even numbers
            for (int i = 2; i < number/2; ++i) {
                if (number % i == 0) {
                    isPrime = false;
                }
            }
        }
        return isPrime;
    }

Method for finding repDigit:

 /**
 * This method checks if numbers, after each other, are the same. We take
 * modulus of the number, in order to get the last digit, as long as the
 * number is above 0. The number is divided by 10, to end up with all
 * remaining numbers. Then it checks, if the last digit + the remaining are
 * the same
 *
 * @param number
 * @return
 */
public static boolean isRepDigit(int number) {
    int repDigit = number % 10;
    boolean toReturn = true;
    if (number < 10) {
        toReturn = false;
    } else {
        while (number > 0) {
            int digit = number % 10;
            number = number / 10;
            if (repDigit != digit) {
                toReturn = false;
            }
        }
    }
    return toReturn;
}

Main method:

    public static void main(String[] args) {
    final int START = 5;
    final int END = 100;
    final int SPACE = digitCount(END);
    for (int i = START; i < END; i++) {

        System.out.printf("%" + SPACE + "d is a repdigit &n", isRepDigit(i));
        System.out.printf("%" + SPACE + "d is a prime &n", isPrime(i));
    }
}

Error message:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Boolean
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Grp17_ueb01.main(Grp17_ueb01.java:164)
C:\Users\rasmu\Documents\NetBeansProjects\ueb01\nbproject\build-impl.xml:1040: The following error occurred while executing this line:
C:\Users\rasmu\Documents\NetBeansProjects\ueb01\nbproject\build-impl.xml:805: Java returned: 1
BUILD FAILED (total time: 1 second)

Body:
I think you misunderstood the meaning of the second argument of printf.
Here d in your string is supposed to be replaced by as a decimal, given as second argument. And the boolean isRepDigit(i) cannot be converted as a decimal.

The printf method documentation may be found here.

The Format string syntax is explained here.

What I think you wanted is:

    if (isRepDigit(i)) {
        System.out.printf("%" + SPACE + "d is a repdigit \n", i);
    }
    if (isPrime(i)) {
        System.out.printf("%" + SPACE + "d is a prime \n", i);
    }


问:
SQL Query - Querying from 3 Tables with ID Order
I would like to export records based on the following tables below.

de_orders (date_add is order created)

```<code>id_order  |   id_carrier  |        date_add
    5     |        1      |    2017-10-24 09:14:51
    6     |        2      |    2017-10-25 10:14:51
    7     |        3      |    2017-10-26 08:14:51
</code>```

de_order_history

```<code>id_order  |   id_order_state |        date_add
    5     |        2         |   2017-10-24 10:14:51
    5     |        3         |   2017-10-24 11:14:51
    5     |        4         |   2017-10-24 12:14:51
</code>```

de_carrier

```<code>    id_carrier  |   name
        1       |   XXX
        2       |   YYY
        3       |   ZZZ
</code>```

I am able to get only one date at the moment as such.

```<code>id_order  |  id_carrier |  date_add(from orders) | date_add (from id_order_state (4))
    5     |     XXX     |   2017-10-24 09:14:51  |       2017-10-24 12:14:51
</code>```

With the query below:

```<code>SELECT
o.id_order AS ID,
o.date_add AS Order_date,
h.date_add AS Delivered_date,
c.name AS carrier_name
FROM de_orders o
LEFT JOIN de_order_history h ON (o.id_order=h.id_order)
LEFT JOIN de_carrier c ON (o.id_carrier=c.id_carrier)
WHERE  YEAR(o.date_add) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(o.date_add) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
AND h.id_order_state="4"
GROUP BY o.id_order
ORDER BY o.id_order
</code>```

I would like to export the following:

Desired Results (Return all records WHERE id_order_state = 4)

```<code>id_order  |  id_carrier |  date_add(from orders) | date_add (from id_order_state (3)) | date_add (from id_order_state (4))
    5     |     XXX     |   2017-10-24 09:14:51  |       2017-10-24 11:14:51          |        2017-10-24 12:14:51
</code>```

Am I looking at it the wrong way?

Thank you.

答:
Consider a conditional aggregate by moving id_order_state WHERE condition into an inline CASE statement. Also, your GROUP BY now includes Order_date to be syntatically correct with SQL ANSI where non-aggregated columns must be included in GROUP BY: clause:

```<code>SELECT o.id_order AS ID,
       c.`name` AS ID_Carrier,
       o.date_add AS Order_date,
       MAX(CASE
                WHEN h.id_order_state='3'
                THEN h.date_add
           END) AS ID_Order_State_3_Deliver_date,
       MAX(CASE
                WHEN h.id_order_state='4'
                THEN h.date_add
           END) AS ID_Order_State_4_Deliver_date,
       c.name AS carrier_name
FROM de_orders o
LEFT JOIN de_order_history h ON (o.id_order=h.id_order)
LEFT JOIN de_carrier c ON (o.id_carrier=c.id_carrier)
WHERE YEAR(o.date_add) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
  AND MONTH(o.date_add) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
GROUP BY o.id_order, c.`name`, o.date_add
ORDER BY o.id_order, c.`name`, o.date_add
</code>```

Body:
I would like to export records based on the following tables below.

de_orders (date_add is order created)

id_order  |   id_carrier  |        date_add
    5     |        1      |    2017-10-24 09:14:51
    6     |        2      |    2017-10-25 10:14:51
    7     |        3      |    2017-10-26 08:14:51

de_order_history

id_order  |   id_order_state |        date_add
    5     |        2         |   2017-10-24 10:14:51
    5     |        3         |   2017-10-24 11:14:51
    5     |        4         |   2017-10-24 12:14:51

de_carrier

    id_carrier  |   name
        1       |   XXX
        2       |   YYY
        3       |   ZZZ

I am able to get only one date at the moment as such.

id_order  |  id_carrier |  date_add(from orders) | date_add (from id_order_state (4))
    5     |     XXX     |   2017-10-24 09:14:51  |       2017-10-24 12:14:51

With the query below:

SELECT
o.id_order AS ID,
o.date_add AS Order_date,
h.date_add AS Delivered_date,
c.name AS carrier_name
FROM de_orders o
LEFT JOIN de_order_history h ON (o.id_order=h.id_order)
LEFT JOIN de_carrier c ON (o.id_carrier=c.id_carrier)
WHERE  YEAR(o.date_add) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(o.date_add) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
AND h.id_order_state="4"
GROUP BY o.id_order
ORDER BY o.id_order

I would like to export the following:

Desired Results (Return all records WHERE id_order_state = 4)

id_order  |  id_carrier |  date_add(from orders) | date_add (from id_order_state (3)) | date_add (from id_order_state (4))
    5     |     XXX     |   2017-10-24 09:14:51  |       2017-10-24 11:14:51          |        2017-10-24 12:14:51

Am I looking at it the wrong way?

Thank you.

Body:
Consider a conditional aggregate by moving id_order_state WHERE condition into an inline CASE statement. Also, your GROUP BY now includes Order_date to be syntatically correct with SQL ANSI where non-aggregated columns must be included in GROUP BY: clause:

SELECT o.id_order AS ID,
       c.`name` AS ID_Carrier,
       o.date_add AS Order_date,
       MAX(CASE
                WHEN h.id_order_state='3'
                THEN h.date_add
           END) AS ID_Order_State_3_Deliver_date,
       MAX(CASE
                WHEN h.id_order_state='4'
                THEN h.date_add
           END) AS ID_Order_State_4_Deliver_date,
       c.name AS carrier_name
FROM de_orders o
LEFT JOIN de_order_history h ON (o.id_order=h.id_order)
LEFT JOIN de_carrier c ON (o.id_carrier=c.id_carrier)
WHERE YEAR(o.date_add) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
  AND MONTH(o.date_add) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
GROUP BY o.id_order, c.`name`, o.date_add
ORDER BY o.id_order, c.`name`, o.date_add


问:
How to remove HTML tag if it contains specific string
```<code>    <tr>
        <td width="300" bgcolor="#cccccc" style="text-align: right;">
         <strong>   Sometext<br />
         </strong>
        </td>
        <td width="125" bgcolor="#009900" style="text-align: center;">
         <strong><span style="color: rgb(255, 255, 255);">
          <span style="font-size: larger;">Pricetoreplace</span>
          </span>
         </strong>
        </td>
    </tr>
</code>```

I need to remove whole
....
 row, if it contain the "Pricetoreplace" text in it.
I've tried next:

```<code>$content = preg_replace('~(<tr.*[\'"]Pricetoreplace[\'"].*tr>)~', '', $content);
</code>```

But it didnt work.

答:
One way would be to use an xpath query:

```<code>*//td[contains(., 'Pricetoreplace')]/parent::tr
</code>```

Here, we look for a td which text() property contains Pricetoreplace and then look up the corresponding parent tr. The latter will be removed from the DOM.

In PHP:

```<code><?php

$html = <<<DATA
    <tr><td class="some other class">some text here</td></tr>
   <tr>
        <td width="300" bgcolor="#cccccc" style="text-align: right;">
         <strong>   Sometext<br />
         </strong>
        </td>
        <td width="125" bgcolor="#009900" style="text-align: center;">
         <strong><span style="color: rgb(255, 255, 255);">
          <span style="font-size: larger;">Pricetoreplace</span>
          </span>
         </strong>
        </td>
    </tr>
DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

foreach ($xpath->query("*//td[contains(., 'Pricetoreplace')]/parent::tr") as $row) {
    $row->parentNode->removeChild($row);
}
echo $dom->saveHTML();
?>
</code>```

This yields

```<code><tr><td class="some other class">some text here</td></tr>
</code>```

Body:
            Sometext

          Pricetoreplace

I need to remove whole
....
 row, if it contain the "Pricetoreplace" text in it.
I've tried next:

$content = preg_replace('~(
)~', '', $content);

But it didnt work.

Body:
One way would be to use an xpath query:

*//td[contains(., 'Pricetoreplace')]/parent::tr

Here, we look for a td which text() property contains Pricetoreplace and then look up the corresponding parent tr. The latter will be removed from the DOM.

In PHP:

<?php

$html = <<<DATA
    <tr><td class="some other class">some text here</td></tr>
   <tr>
        <td width="300" bgcolor="#cccccc" style="text-align: right;">
         <strong>&nbsp;&nbsp;&nbsp;Sometext<br />
         </strong>
        </td>
        <td width="125" bgcolor="#009900" style="text-align: center;">
         <strong><span style="color: rgb(255, 255, 255);">
          <span style="font-size: larger;">Pricetoreplace</span>
          </span>
         </strong>
        </td>
    </tr>
DATA;

# set up the DOM
$dom = new DOMDocument();
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

# set up the xpath
$xpath = new DOMXPath($dom);

foreach ($xpath->query("*//td[contains(., 'Pricetoreplace')]/parent::tr") as $row) {
    $row->parentNode->removeChild($row);
}
echo $dom->saveHTML();
?>

This yields

<tr><td class="some other class">some text here</td></tr>


问:
ListView with more than two values
I have an object which contains the necessary data which they are four and I want to set them on a list with four TextView as well. I used HashMap with two values but can't figure it out with more than two.

Medicine class

```<code>public class Medicine {
    private String id;
    private String name;
    private String doctor;
    private String date;
    private String dose;

    public Medicine() {}

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDoctor() {
        return doctor;
    }

    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getDose() {
        return dose;
    }

    public void setDose(String dose) {
        this.dose = dose;
    }
}
</code>```

fragment of medicines

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView
            android:id="@+id/medicinesList"
            android:layout_height="0dip"
            android:layout_width="match_parent"
            android:layout_weight="1" />

        <Button android:id="@+id/btn"
            android:text="@string/addmedButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

</RelativeLayout>
</code>```

list that contains the four text views

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/medicineTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/doseTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/doctorTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/dateTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>
</code>```

On previous implementation when I had two values and two text views I did something like that using HashMap

```<code>List<HashMap<String,String>> listItems = new ArrayList<>();
SimpleAdapter simpleAdapter = new SimpleAdapter(
    getActivity(),listItems,R.layout.list_item,
    new String[]{"name","id"},
    new int[]{R.id.text1,R.id.text2});

Iterator it = patientInfoForList.entrySet().iterator();
while (it.hasNext()) {
  HashMap<String,String> resultsMap = new HashMap<>();
  Map.Entry pair = (Map.Entry) it.next();
  resultsMap.put("name",pair.getKey().toString());
  resultsMap.put("id",pair.getValue().toString());
  listItems.add(resultsMap);
}

patientsList.setAdapter(simpleAdapter);
</code>```

But with four values I can't figure it out. I tried using HashMap<String,Medicine> but I couldn't put the four values to the map. A cheap solution would be to concatenate the four strings into two and reduce the text views from four to two as well. But that will be my last option.

答:
Use the ArrayAdapter instead of the SimpleAdapter.

I.e:

```<code>public class MedicinesAdapter extends ArrayAdapter<Medicine> {
    public MedicinesAdapter(Context context, ArrayList<Medicine> medicines) {
        super(context, 0, medicines);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Medicine medicine = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }
        TextView medicineTextView = (TextView) convertView.findViewById(R.id.medicineTextView);
        TextView doseTextView = (TextView) convertView.findViewById(R.id.doseTextView);
        .... // Lookup  the rest of views for data population

        medicineTextView.setText(medicine.getName());
        doseTextView.setText(medicine.getDose());
        ... // Populate the rest of the views
        return convertView;
    }
}
</code>```

Here's a link to a good guide on the subject.  Make sure the read the part about the ViewHolder pattern.

Title: ListView with more than two values

Body:
I have an object which contains the necessary data which they are four and I want to set them on a list with four TextView as well. I used HashMap with two values but can't figure it out with more than two.

Medicine class

public class Medicine {
    private String id;
    private String name;
    private String doctor;
    private String date;
    private String dose;

    public Medicine() {}

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDoctor() {
        return doctor;
    }

    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getDose() {
        return dose;
    }

    public void setDose(String dose) {
        this.dose = dose;
    }
}

fragment of medicines

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ListView
            android:id="@+id/medicinesList"
            android:layout_height="0dip"
            android:layout_width="match_parent"
            android:layout_weight="1" />

        <Button android:id="@+id/btn"
            android:text="@string/addmedButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

</RelativeLayout>

list that contains the four text views

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/medicineTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/doseTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/doctorTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/dateTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="5dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

On previous implementation when I had two values and two text views I did something like that using HashMap

List<HashMap<String,String>> listItems = new ArrayList<>();
SimpleAdapter simpleAdapter = new SimpleAdapter(
    getActivity(),listItems,R.layout.list_item,
    new String[]{"name","id"},
    new int[]{R.id.text1,R.id.text2});

Iterator it = patientInfoForList.entrySet().iterator();
while (it.hasNext()) {
  HashMap<String,String> resultsMap = new HashMap<>();
  Map.Entry pair = (Map.Entry) it.next();
  resultsMap.put("name",pair.getKey().toString());
  resultsMap.put("id",pair.getValue().toString());
  listItems.add(resultsMap);
}

patientsList.setAdapter(simpleAdapter);

But with four values I can't figure it out. I tried using HashMap<String,Medicine> but I couldn't put the four values to the map. A cheap solution would be to concatenate the four strings into two and reduce the text views from four to two as well. But that will be my last option.

Body:
Use the ArrayAdapter instead of the SimpleAdapter.

I.e:

public class MedicinesAdapter extends ArrayAdapter<Medicine> {
    public MedicinesAdapter(Context context, ArrayList<Medicine> medicines) {
        super(context, 0, medicines);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Medicine medicine = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }
        TextView medicineTextView = (TextView) convertView.findViewById(R.id.medicineTextView);
        TextView doseTextView = (TextView) convertView.findViewById(R.id.doseTextView);
        .... // Lookup  the rest of views for data population

        medicineTextView.setText(medicine.getName());
        doseTextView.setText(medicine.getDose());
        ... // Populate the rest of the views
        return convertView;
    }
}

Here's a link to a good guide on the subject.  Make sure the read the part about the ViewHolder pattern.


问:
Error using Angle in Julia
I am simply trying to get the angle of a complex number. To test the angle function provided in Julia I first tried :

```<code> angle(1+im)
</code>```

But I get the following error message :

MethodError: objects of type Float64 are not callable

Stacktrace:  [1] include_string(::String, ::String) at
  ./loading.jl:515

When I try to ask typeof(1+im) Julia answers

Complex{Int64}

I don't understand what is happening with the angle function. I tried with 1+1*im but I get the same answer.

Could anyone help please?
I could also calculate the angle from coordinates but I'd like to understand Julia language as well.

Thank you

答:
Sometimes it's possible to accidentally define a variable with the same name as a built-in function that you don't know about. For example, there's a function called angle(), but you can do this:

```<code>julia> angle=1.5
1.5

julia> angle(1+1im)
ERROR: MethodError: objects of type Float64 are not callable

julia> typeof(angle)
Float64
</code>```

Now you can't 'see' the function definition, because your variable is hiding it.

To fix this, you can type:

```<code>julia> angle=Base.angle
angle (generic function with 3 methods)

julia> angle(1+1im)
0.7853981633974483
</code>```

A good question is, why doesn't Julia tell me I've just overwritten a basic function?

Addendum

And the answer (thanks to @Matt in a comment) is that if you use it, and then redefine it, you'll get a warning:

```<code>              _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.6.0 (2017-06-19 13:05 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-apple-darwin13.4.0

julia> angle(1+2im)
1.1071487177940904

julia> angle=1.5
WARNING: imported binding for angle overwritten in module Main
1.5
</code>```

Title: Error using Angle in Julia

Body:
I am simply trying to get the angle of a complex number. To test the angle function provided in Julia I first tried :

 angle(1+im)

But I get the following error message :

MethodError: objects of type Float64 are not callable

Stacktrace:  [1] include_string(::String, ::String) at
  ./loading.jl:515

When I try to ask typeof(1+im) Julia answers

Complex{Int64}

I don't understand what is happening with the angle function. I tried with 1+1*im but I get the same answer.

Could anyone help please?
I could also calculate the angle from coordinates but I'd like to understand Julia language as well.

Thank you

Body:
Sometimes it's possible to accidentally define a variable with the same name as a built-in function that you don't know about. For example, there's a function called angle(), but you can do this:

julia> angle=1.5
1.5

julia> angle(1+1im)
ERROR: MethodError: objects of type Float64 are not callable

julia> typeof(angle)
Float64

Now you can't 'see' the function definition, because your variable is hiding it.

To fix this, you can type:

julia> angle=Base.angle
angle (generic function with 3 methods)

julia> angle(1+1im)
0.7853981633974483

A good question is, why doesn't Julia tell me I've just overwritten a basic function?

Addendum

And the answer (thanks to @Matt in a comment) is that if you use it, and then redefine it, you'll get a warning:

              _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.6.0 (2017-06-19 13:05 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-apple-darwin13.4.0

julia> angle(1+2im)
1.1071487177940904

julia> angle=1.5
WARNING: imported binding for angle overwritten in module Main
1.5


问:
Invert a dictionary inplace
I have a dictionary with unique values and I want to invert it (i.e. swap keys with values) inplace.
Is there any way doing it without using another dictionary?

I would prefer to just manipulate the items inside the dict than use a new dictionary, so that id(my_dict) would remain the same.

答:
I guess you want to swap the keys and the values of the dict?

You can do it like this:

```<code>dict_name = dict(zip(dict_name.values(), dict_name.keys()))
</code>```

Title: Invert a dictionary inplace

Body:
I guess you want to swap the keys and the values of the dict?

You can do it like this:

dict_name = dict(zip(dict_name.values(), dict_name.keys()))


问:
Writing from Future of CachedThreadPool. Is my implementation incorrect?
I need help with my multithreading code.
I have a callable class which returns a value. I have a cachedThreadPool to submit ~60,000 tasks. I collect all the Futures in a List. After the ExecutiveService has shutdown, I loop through the list of Futures, and write the returned values using a bufferedWriter. Is this correct way of implementation?

```<code>ExecutorService execService = Executors.newCachedThreadPool();
List<Future<ValidationDataObject<String, Boolean>>> futureList = new ArrayList<>();
for (int i = 0; i < emailArrayList.size(); i++) {
    String emailAddress = emailArrayList.get(i);
    ValidateEmail validateEmail = new ValidateEmail(emailAddress);
    Future<ValidationDataObject<String, Boolean>> future =
         execService.submit(validateEmail);
    futureList.add(future);
}

execService.shutdown();

for (Future<ValidationDataObject<String, Boolean>> future: futureList) {
    ValidationDataObject<String, Boolean> validationObject = future.get();
    bufferedWriter.write(validationObject.getEmailAddress() + "|"
             + validationObject.getIsValid());
    bufferedWriter.newLine();
    bufferedWriter.flush();
}

if (execService.isTerminated()) bufferedWriter.close();
</code>```

Should I using synchronized block for the bufferedWriter? I am thinking, It doesn't need to be synchronized because, I am using the bufferedWriter from the main Thread, right?

答:
I have a cachedThreadPool to submit ~60,000 tasks.

Off the bat, a cached thread-pool and 60k tasks is a red flag.  That is going to start 60k threads which I doubt you really want.  You should use a fixed thread pool and vary the number of threads until you achieve a good balance of throughput versus overwhelming your server.  Maybe start with 2x the number of CPUs and then vary it depending on the server load.

You might also might consider using a fixed size queue which will limit the number of tasks outstanding although 60k tasks is fine unless those objects are heavy.

I collect all the Futures in a List. After the ExecutiveService has shutdown, I loop through the list of Futures, and write the returned values using a bufferedWriter. Is this correct way of implementation?

Yes, that's a good pattern.  You don't show the writer being created but it is certainly fine for the main thread to own that.

Should I using synchronized block for the bufferedWriter? I am thinking, It doesn't need to be synchronized because, I am using the bufferedWriter from the main Thread, right?

Right. No other threads are using it so that's fine.  It is a very typical pattern to have a writer thread managing the output of a multi-thread application.

One final comment is that you might want to look at the ExecutionCompletionService which allows you to process the tasks as they finish instead of having to wait for them in order.  You might require the output to be in order in which case this isn't helpful but it's good technology to know about anyway.

Body:
I need help with my multithreading code.
I have a callable class which returns a value. I have a cachedThreadPool to submit ~60,000 tasks. I collect all the Futures in a List. After the ExecutiveService has shutdown, I loop through the list of Futures, and write the returned values using a bufferedWriter. Is this correct way of implementation?

ExecutorService execService = Executors.newCachedThreadPool();
List<Future<ValidationDataObject<String, Boolean>>> futureList = new ArrayList<>();
for (int i = 0; i < emailArrayList.size(); i++) {
    String emailAddress = emailArrayList.get(i);
    ValidateEmail validateEmail = new ValidateEmail(emailAddress);
    Future<ValidationDataObject<String, Boolean>> future =
         execService.submit(validateEmail);
    futureList.add(future);
}

execService.shutdown();

for (Future<ValidationDataObject<String, Boolean>> future: futureList) {
    ValidationDataObject<String, Boolean> validationObject = future.get();
    bufferedWriter.write(validationObject.getEmailAddress() + "|"
             + validationObject.getIsValid());
    bufferedWriter.newLine();
    bufferedWriter.flush();
}

if (execService.isTerminated()) bufferedWriter.close();

Should I using synchronized block for the bufferedWriter? I am thinking, It doesn't need to be synchronized because, I am using the bufferedWriter from the main Thread, right?


问:
How to speed up importing dataframes into pandas
I understand that one of the reasons why pandas can be relatively slow importing csv files is that it needs to scan the entire content of a column before guessing the type (see the discussions around the mostly deprecated low_memory option for pandas.read_csv). Is my understanding correct?

If it is, what would be a good format in which to store a dataframe, and which explicitly specifies data types, so pandas doesn't have to guess (SQL is not an option for now)?

Any option in particular from those listed here?

My dataframes have floats, integers, dates, strings and Y/N, so formats supporting numeric values only won't do.

答:
I would consider either HDF5 format or Feather Format. Both of them are pretty fast (Feather might be faster, but HDF5 is more feature rich - for example reading from disk by index) and both of them store the type of columns, so they don't have to guess dtypes and they don't have to convert data types (for example strings to numerical or strings to datetimes) when loading data.

Here are some speed comparisons:

which is faster for load: pickle or hdf5 in python

What is the fastest way to upload a big csv file in notebook to work with python pandas?


问:
Error on connecting to Hibernate
I have a problem in hibernate connection. In my hibernate.cfg.xml file is like below

And i get this error

答:
Please use

```<code>hibernate.connection.driver_class
</code>```

in place of

```<code>hibernate.connection.Driver_Class
</code>```

Also try to use

Oracle9iDialect or Oracle10gDialect

Also, you can't get Oracle driver from the usual Maven repository

How to start solve such tasks yourself

Check that copy of updated hibernate.cfg.xml is located near compiled classes.

Check that inside Oracle driver jar you have this path and class oracle.jdbc.driver.OracleDriver

Check that you really has class oracle.jdbc.driver.OracleDriver in the classpath using this approach:
https://stackoverflow.com/a/36278463/3405171

Title: Error on connecting to Hibernate

Body:
Please use

hibernate.connection.driver_class

in place of

hibernate.connection.Driver_Class

Also try to use

Oracle9iDialect or Oracle10gDialect

Also, you can't get Oracle driver from the usual Maven repository

How to start solve such tasks yourself

Check that copy of updated hibernate.cfg.xml is located near compiled classes.

Check that inside Oracle driver jar you have this path and class oracle.jdbc.driver.OracleDriver

Check that you really has class oracle.jdbc.driver.OracleDriver in the classpath using this approach:
https://stackoverflow.com/a/36278463/3405171


问:
React-Native: Application has not been registered error
I am currently going through the React-Native tutorials. I began with the Getting Started tutorial, where I made a new react native project and successfully managed to run the project on my device.

I then started the Props tutorial, I copied the code snippet and tried to run the project again and had the following error message show up on my screen:

答:
This can also be due to Root component name starts with lowercase.

Recorrect it or rather create the project once again with a PascalCase name.

e.g. ignite new HelloWord


问:
String Benchmarks in C# - Refactoring for Speed/Maintainability
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

```<code>private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }
</code>```

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```

However, it changes drastically over the longhaul:

With 10,000 Iterations:

```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```

Here's the code after Refactor #1:

```<code>private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }
</code>```

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

```<code>static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }
</code>```

This results in the following Benchmark:

```
MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder
```

Changing the for loop to a foreach loop resulted in the following benchmark result:

```<code>static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }
</code>```

```
RefactoredForEachMakeNiceString    Took:  45163 Ticks
```

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

```<code>static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }
</code>```

Final Benchmark Results:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```0

Or, if you prefer milliseconds:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```1

So the percentage gains are:

```
MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks
```2

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

```<code>       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }
</code>```

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

答:
Try refactoring so that the regular expression that you're using to split the string in the second method is stored in a static method, and has been built using the RegexOptions.Compiled option.  More info about this here: http://msdn.microsoft.com/en-us/library/8zbs0h2f.aspx.

I didn't test the theory, but I'd imagine that having to recreate the regex every time would be time consuming.

OwnerDisplayName: Gortok

Body:
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book Refactoring: Improving the Design of Existing Code).  I found the following function MakeNiceString() while updating another part of the codebase near it, and it looked like a good candidate to mess with.  As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.

private static string MakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += System.Convert.ToString(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += System.Convert.ToString(ca[i]);
            }
            return result;
        }

static string SplitCamelCase(string str)
    {
        string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
        string result = String.Join(" ", temp);
        return result;
    }

The first function MakeNiceString() is the function I found in some code I was updating at work.  The purpose of the function is to translate ThisIsAString to This Is A String.  It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.

I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.

Well, here are the results:

With 10 Iterations:

MakeNiceString took 2649 ticks
SplitCamelCase took 2502 ticks

However, it changes drastically over the longhaul:

With 10,000 Iterations:

MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks

Refactoring MakeNiceString()

The process of refactoring MakeNiceString() started with simply removing the conversions that were taking place.  Doing that yielded the following results:

MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486

Here's the code after Refactor #1:

private static string ImprovedMakeNiceString(string str)
        { //Removed Convert.ToString()
            char[] ca = str.ToCharArray();
            string result = null;
            int i = 0;
            result += ca[0];
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    result += " ";
                }
                result += ca[i];
            }
            return result;
        }

Refactor#2 - Use StringBuilder

My second task was to use StringBuilder instead of String.  Since String is immutable, unnecessary copies were being created throughout the loop.  The benchmark for using that is below, as is the code:

static string RefactoredMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
            int i = 0;
            sb.Append(ca[0]);
            for (i = 1; i <= ca.Length - 1; i++)
            {
                if (!(char.IsLower(ca[i])))
                {
                    sb.Append(" ");
                }
                sb.Append(ca[i]);
            }
            return sb.ToString();
        }

This results in the following Benchmark:

MakeNiceString Took:           124497 Ticks   //Original
SplitCamelCase Took:           464459 Ticks   //Regex
ImprovedMakeNiceString Took:   117369 Ticks   //Remove Conversion
RefactoredMakeNiceString Took:  38542 Ticks   //Using StringBuilder

Changing the for loop to a foreach loop resulted in the following benchmark result:

static string RefactoredForEachMakeNiceString(string str)
        {
            char[] ca = str.ToCharArray();
            StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
            sb1.Append(ca[0]);
            foreach (char c in ca)
            {
                if (!(char.IsLower(c)))
                {
                    sb1.Append(" ");
                }
                sb1.Append(c);
            }
            return sb1.ToString();
        }

RefactoredForEachMakeNiceString    Took:  45163 Ticks

As you can see, maintenance-wise, the foreach loop will be the easiest to maintain and have the 'cleanest' look.  It is slightly slower than the for loop, but infinitely easier to follow.

Alternate Refactor: Use Compiled Regex

I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster.  What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:

static void runTest5()
        {
            Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
            for (int i = 0; i < 10000; i++)
            {
                CompiledRegex(rg, myString);
            }
        }
 static string CompiledRegex(Regex regex, string str)
    {
        string result = null;
        Regex rg1 = regex;
        string[] temp = rg1.Split(str);
        result = String.Join(" ", temp);
        return result;
    }

Final Benchmark Results:

MakeNiceString Took                   139363 Ticks
SplitCamelCase Took                   489174 Ticks
ImprovedMakeNiceString Took           115478 Ticks
RefactoredMakeNiceString Took          38819 Ticks
RefactoredForEachMakeNiceString Took   44700 Ticks
CompiledRegex Took                    227021 Ticks

Or, if you prefer milliseconds:

MakeNiceString Took                  38 ms
SplitCamelCase Took                 123 ms
ImprovedMakeNiceString Took          33 ms
RefactoredMakeNiceString Took        11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took                   63 ms

So the percentage gains are:

MakeNiceString                   38 ms   Baseline
SplitCamelCase                  123 ms   223% slower
ImprovedMakeNiceString           33 ms   13.15% faster
RefactoredMakeNiceString         11 ms   71.05% faster
RefactoredForEachMakeNiceString  12 ms   68.42% faster
CompiledRegex                    63 ms   65.79% slower

(Please check my math)

In the end, I'm going to replace what's there with the RefactoredForEachMakeNiceString() and while I'm at it, I'm going to rename it to something useful, like SplitStringOnUpperCase.

Benchmark Test:

To benchmark, I simply invoke a new Stopwatch for each method call:

       string myString = "ThisIsAUpperCaseString";
       Stopwatch sw = new Stopwatch();
       sw.Start();
       runTest();
       sw.Stop();

     static void runTest()
        {

            for (int i = 0; i < 10000; i++)
            {
                MakeNiceString(myString);
            }

        }

Questions

What causes these functions to be so different 'over the long haul', and

How can I improve this function
a) to be more maintainable or
b) to run faster?

How would I do memory benchmarks on these to see which used less memory?

Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.

NB: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code as is.  I'm well aware you can remove the System.Convert.ToString() in the first method, and I did just that.  If anyone is aware of any implications of removing the System.Convert.ToString(), that would also be helpful to know.

LastEditorDisplayName: Gortok

OwnerDisplayName: Joel Martinez


问:
Explicitly make GLM model on h2o driverless AI
I have done a few experiments on h2o driverless AI. Was curious to know whether we can explicitly ask the experiment to train using GLM.

Or it will always make model the way it does?

答:
[ Driverless AI is a brand new product, so it's evolving very fast.  This answer is for version 1.0.5 of Driverless AI, but could quickly become out of date. ]

Driverless AI uses (preferably GPU-based) xgboost tree models inside for evaluating variable importance during feature engineering, and for building a final model to make predictions.  But what you can do, after the experiment progress bar shows 100% complete, is download the transformed training and test data as .csv files.  These transformed .csv files include the engineered features as new columns, and can be used as inputs to H2O-3's GLM, for example.

Adding more kinds of models definitely makes sense for the future, though.


Title: Python/Pandas - remove not duplicated rows

Body:
I have DataFrame like this:

        product_id          dt  stock_qty
226870     2948259  2017-11-11     17.000
233645     2948259  2017-11-12     17.000
240572     2948260  2017-11-13      5.000
247452     2948260  2017-11-14      5.000
233644     2948260  2017-11-12      5.000
226869     2948260  2017-11-11      5.000
247451     2948262  2017-11-14     -2.000
226868     2948262  2017-11-11     -1.000  <- not duplicated
240571     2948262  2017-11-13     -2.000
240570     2948264  2017-11-13      5.488
233643     2948264  2017-11-12      5.488
244543     2948269  2017-11-11      2.500
247450     2948276  2017-11-14      3.250
226867     2948276  2017-11-11      3.250

I have to remove rows where stock_qty are different but product_id values are the same. So I should get DataFrame like this:

        product_id          dt  stock_qty
226870     2948259  2017-11-11     17.000
233645     2948259  2017-11-12     17.000
240572     2948260  2017-11-13      5.000
247452     2948260  2017-11-14      5.000
233644     2948260  2017-11-12      5.000
226869     2948260  2017-11-11      5.000
240570     2948264  2017-11-13      5.488
233643     2948264  2017-11-12      5.488
244543     2948269  2017-11-11      2.500
247450     2948276  2017-11-14      3.250
226867     2948276  2017-11-11      3.250

Thanks for help!

Body:
By using drop_duplicates

df.drop(df.drop_duplicates(['stock_qty', 'product_id'], keep=False).index)
Out[797]:
        product_id          dt  stock_qty
226870     2948259  2017-11-11     17.000
233645     2948259  2017-11-12     17.000
240572     2948260  2017-11-13      5.000
247452     2948260  2017-11-14      5.000
233644     2948260  2017-11-12      5.000
226869     2948260  2017-11-11      5.000
247451     2948262  2017-11-14     -2.000
240571     2948262  2017-11-13     -2.000
240570     2948264  2017-11-13      5.488
233643     2948264  2017-11-12      5.488
247450     2948276  2017-11-14      3.250
226867     2948276  2017-11-11      3.250


问:
Python: why appending to a list results in same values
This is my code:

```<code>a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)
</code>```

The result is:

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

But I want the result to be:

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

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?

答:
```<code>a = []                    # (1) list created here
res = []
for i in range(0, 3):
    a.append(i)           # (2) list modified here
    res.append(a)         # (3) res is modified here
print(res)
</code>```

What your code is saying is this:

At (1) a list is created and a refers to this list.

At (2) you modify the list from (1), but the list itself remains at the same memory location and a still refers to this list.

At (3) you just make a copy of a reference and add it to res, and still neither a nor the list at (1) change.

The end results is that res gets 3 copies of the reference to the list at (1).

Here is a side effect:

```<code>a[1] = 42
print(res)
</code>```

Output:

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

You say that you know that this is the code you are after:

```<code>a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a[:])     # (4) new list created
print(res)
</code>```

At (4) a new list is created whose contents is the same as the list that a refers to. This new list is not referred to by a, but instead, one of the elements of res has a reference to this new list.

Firstly this means that res holds references to lists, which is why they hang around long enough to be printed. Secondly a still refers to the original list.

Here is a side effect:

```<code>a[1] = 42
print(res)
</code>```

Output:

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

However, this is not the end of the story if you examine this code:

```<code>a = []
res = []
for i in range(0, 3):
    a.append([i])        # (5) Create a new list with one element
    res.append(a[:])     # (6) Shallow copy as above
print(res)

a[1].append(42)
print(a, res)
</code>```

Output:

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

This occurs because at (6) there was only a shallow copy made.

Body:
This is my code:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)

The result is:

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

But I want the result to be:

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

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?

Body:
a = []                    # (1) list created here
res = []
for i in range(0, 3):
    a.append(i)           # (2) list modified here
    res.append(a)         # (3) res is modified here
print(res)

What your code is saying is this:

At (1) a list is created and a refers to this list.

At (2) you modify the list from (1), but the list itself remains at the same memory location and a still refers to this list.

At (3) you just make a copy of a reference and add it to res, and still neither a nor the list at (1) change.

The end results is that res gets 3 copies of the reference to the list at (1).

Here is a side effect:

a[1] = 42
print(res)

Output:

[[0, 42, 2], [0, 42, 2], [0, 42, 2]]

You say that you know that this is the code you are after:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a[:])     # (4) new list created
print(res)

At (4) a new list is created whose contents is the same as the list that a refers to. This new list is not referred to by a, but instead, one of the elements of res has a reference to this new list.

Firstly this means that res holds references to lists, which is why they hang around long enough to be printed. Secondly a still refers to the original list.

Here is a side effect:

a[1] = 42
print(res)

Output:

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

However, this is not the end of the story if you examine this code:

a = []
res = []
for i in range(0, 3):
    a.append([i])        # (5) Create a new list with one element
    res.append(a[:])     # (6) Shallow copy as above
print(res)

a[1].append(42)
print(a, res)

Output:

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

This occurs because at (6) there was only a shallow copy made.


问:
How to hide the dots in FMX TabControl?
I do not want to show the dots in a TabControl interface, when I change the properties of TabControl, TabPosition: Dots ... I just want to handle it with gestures. </p>

答:
Set the TabPosition property to None.

It can seem misleading because the dots still show up in design mode to simplify moving from page to page when designing, but they will not show when running.

Title: How to hide the dots in FMX TabControl?