问:
Creating an efficient datatype for looking up conversion factors by initial and resulting units C#
I'm trying to create a windows form application that will convert units of measurements from one to the other.  My form features navigation buttons that I figured would make it user friendly.

When the user selects a category from the main menu it fills the category of measurement combobox and sets default unit of measurements into two other combo boxes.

These comboboxes allow the user to select which unit of measurement they want.  When they choose a category such as distance, it fills the initial and resulting unit of measurement comboboxes.

I therefore have already created a few string[] that contains each unit of measurement.

```<code>string[] distanceUnits = { "Inches", "Feet", "Centimeters", "Meters", "Kilometers", "Miles" };
string[] massUnits = { "Grams", "Kilograms", "Pounds", "Ounces" };
</code>```

I also created a couple different decimal[] arrays filled with conversion factors that I have been looking up and editing for precision purposes since I will be doing unit testing. I'd like to easily be able to change the conversion factor or add new ones into the arrays.

For example,

```<code>decimal[] massConversionFactors =
{
    .001m,               // [0] Grams to KiloGrams
    .00220462m,          // [1] Grams to Pounds
    .035274m,            // [2] Grams to Ounces
    1000,                // [3] KiloGrams to Grams
    2.20462m,            // [4] KiloGrams to Pounds
    35.274m,             // [5] KiloGrams to Ounces
    453.592m,            // [6] Pounds to Grams
    .453592m,            // [7] Pounds to Kilograms
    16                   // [8] Pounds to Ounces
};
</code>```

and

```<code>decimal[] distanceConversionFactors =
{
    .083333m,             // [0] Inches to Feet
    2.54m,                // [1] Inches to Centimeters
    .0254m,               // [2] Inches to Meters
    .0000254m,            // [3] Inches to Kilometers
    .0000157828282828m,   // [4] Inches to Miles
    12,                   // [5] Feet to Inches
    30.48m,               // [6] Feet to Centimetes
    .3048m,               // [7] Feet to Meters
    .0003048m,            // [8] Feet to Kilometers
    .000189394m,          // [9] Feet to Miles
    .3937009133858m,      // [10] Centimeters to Inches
    .03280840944882m,     // [11] Centimeters to Feet
    .01m,                 // [12] Centimeters to Meters
    .00001m,              // [13] Centimeters to Kilometers
    .0000062137m,         // [14] Centimeters to Miles
    39.3701m,             // [15] Meters to Inches
    3.28084m,             // [16] Meters to Feet
    100,                  // [17] Meters to Centimeters
    .001m,                // [18] Meters to Kilometers
    .000621371m,          // [19] Meters to Miles
    39370.1m,             // [20] Kilometers to Inches
    3280.84m,             // [21] Kilometers to Feet
    100000,               // [22] Kilometers to Centimeters
    1000,                 // [23] Kilometers to Meters
    .621371m,             // [24] Kilometers to Miles
    63360,                // [25] Miles to Inches
    5280,                 // [26] Miles to Feet
    160934,               // [27] Miles to Centimeters
    1609.34m,             // [28] Miles to Meters
    1.60934m              // [29] Miles to Kilometers
};
</code>```

That way when the submission button is pressed I can do a calculation such as:

```<code>private void ConvertSubmissionButton_Click(object sender, EventArgs e)
{
    //User's input value
    decimal input = decimal.Parse(UserInputTextBox.Text);
    string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
    string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

    //conversion of user input to result accepting initial and resulting
    decimal result =  input * ObjectWithTooManyMethods(initalUnits, resultingUnits);

    ResultingValueLabel.Text = (initialUnits);
    ResultingValueLabel.Show();
}
</code>```

This works fine for now, but as I add more methods to the object I wonder if there is a way to consolidate the already created arrays.

The problem I'm having is that I am forced to hardcode every permutation of conversion in the

```<code>ObjectWithTooManyMethods(string, string);
</code>```

What I'd really like to do is create a recursive loop that will go through the distanceUnits[] massUnits[] and other unit of measurement category arrays, and creates every possible permutation based on the category's appropriate conversionFactor arrays.
This way I can add on units of measurements and their conversion factors without coding an entire new method in the future.

Is this possible?

This ideal loop would create a single datatype that contains this information and be able to retrieve the decimal value for the conversion factor for initial, and resulting units when the user clicks a submission button.

Such as:

```<code>DesiredDatatype<string,string,decimal> conversionFactors = new DesiredDatatype<string,string,decimal>()
{
    {initialUnits, resultingUnits, conversionFactor}
};

    private void ConvertSubmissionButton_Click(object sender, EventArgs e)
    {
        //User's input value
        decimal input = decimal.Parse(UserInputTextBox.Text);
        string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
        string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

        decimal result =  input * conversionFactors.get(initialUnits, resultingUnits);

        ResultingValueLabel.Text = (result);
        ResultingValueLabel.Show();
    }
</code>```

Maybe I'm approaching this the wrong way, and/or have been coding too long today.. I have looked up information about tuples and dictionarys and they seem like they would ideal for this scenario but I have failed in creating a working datatype from looping through the information in these existing arrays.

Any advice is greatly appreciated. Thanks a lot!

答:
I think you would be better served by creating hard-coded functions inside a helper class for this. There is really no reason to place all these constant inside a dynamic array. That's going to be abstract, confusing and hard to keep track of. For example, your mass conversion class could look like this:

```<code>public static class MassConversion
{
    public static decimal GramsToKilograms(decimal grams) {
        return grams * .001;
    }
    public static decimal GramsToPounds(decimal grams) {
        return grams * .00220462;
    }
    public static decimal GramsToOunces(decimal grams) {
        return grams * .035274;
    }
    public static decimal KilogramsToGrams(decimal kilograms) {
        return kilograms* 1000;
    }
    //...
};
</code>```

Then, to use it:

```<code>var grams = 4267;
var kilos = MassConversion.GramsToKilograms(grams);
</code>```

This also has the benefit of being self-documenting.

Body:
I'm trying to create a windows form application that will convert units of measurements from one to the other.  My form features navigation buttons that I figured would make it user friendly.

When the user selects a category from the main menu it fills the category of measurement combobox and sets default unit of measurements into two other combo boxes.

These comboboxes allow the user to select which unit of measurement they want.  When they choose a category such as distance, it fills the initial and resulting unit of measurement comboboxes.

I therefore have already created a few string[] that contains each unit of measurement.

string[] distanceUnits = { "Inches", "Feet", "Centimeters", "Meters", "Kilometers", "Miles" };
string[] massUnits = { "Grams", "Kilograms", "Pounds", "Ounces" };

I also created a couple different decimal[] arrays filled with conversion factors that I have been looking up and editing for precision purposes since I will be doing unit testing. I'd like to easily be able to change the conversion factor or add new ones into the arrays.

For example,

decimal[] massConversionFactors =
{
    .001m,               // [0] Grams to KiloGrams
    .00220462m,          // [1] Grams to Pounds
    .035274m,            // [2] Grams to Ounces
    1000,                // [3] KiloGrams to Grams
    2.20462m,            // [4] KiloGrams to Pounds
    35.274m,             // [5] KiloGrams to Ounces
    453.592m,            // [6] Pounds to Grams
    .453592m,            // [7] Pounds to Kilograms
    16                   // [8] Pounds to Ounces
};

and

decimal[] distanceConversionFactors =
{
    .083333m,             // [0] Inches to Feet
    2.54m,                // [1] Inches to Centimeters
    .0254m,               // [2] Inches to Meters
    .0000254m,            // [3] Inches to Kilometers
    .0000157828282828m,   // [4] Inches to Miles
    12,                   // [5] Feet to Inches
    30.48m,               // [6] Feet to Centimetes
    .3048m,               // [7] Feet to Meters
    .0003048m,            // [8] Feet to Kilometers
    .000189394m,          // [9] Feet to Miles
    .3937009133858m,      // [10] Centimeters to Inches
    .03280840944882m,     // [11] Centimeters to Feet
    .01m,                 // [12] Centimeters to Meters
    .00001m,              // [13] Centimeters to Kilometers
    .0000062137m,         // [14] Centimeters to Miles
    39.3701m,             // [15] Meters to Inches
    3.28084m,             // [16] Meters to Feet
    100,                  // [17] Meters to Centimeters
    .001m,                // [18] Meters to Kilometers
    .000621371m,          // [19] Meters to Miles
    39370.1m,             // [20] Kilometers to Inches
    3280.84m,             // [21] Kilometers to Feet
    100000,               // [22] Kilometers to Centimeters
    1000,                 // [23] Kilometers to Meters
    .621371m,             // [24] Kilometers to Miles
    63360,                // [25] Miles to Inches
    5280,                 // [26] Miles to Feet
    160934,               // [27] Miles to Centimeters
    1609.34m,             // [28] Miles to Meters
    1.60934m              // [29] Miles to Kilometers
};

That way when the submission button is pressed I can do a calculation such as:

private void ConvertSubmissionButton_Click(object sender, EventArgs e)
{
    //User's input value
    decimal input = decimal.Parse(UserInputTextBox.Text);
    string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
    string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

    //conversion of user input to result accepting initial and resulting
    decimal result =  input * ObjectWithTooManyMethods(initalUnits, resultingUnits);

    ResultingValueLabel.Text = (initialUnits);
    ResultingValueLabel.Show();
}

This works fine for now, but as I add more methods to the object I wonder if there is a way to consolidate the already created arrays.

The problem I'm having is that I am forced to hardcode every permutation of conversion in the

ObjectWithTooManyMethods(string, string);

What I'd really like to do is create a recursive loop that will go through the distanceUnits[] massUnits[] and other unit of measurement category arrays, and creates every possible permutation based on the category's appropriate conversionFactor arrays.
This way I can add on units of measurements and their conversion factors without coding an entire new method in the future.

Is this possible?

This ideal loop would create a single datatype that contains this information and be able to retrieve the decimal value for the conversion factor for initial, and resulting units when the user clicks a submission button.

Such as:

DesiredDatatype<string,string,decimal> conversionFactors = new DesiredDatatype<string,string,decimal>()
{
    {initialUnits, resultingUnits, conversionFactor}
};

    private void ConvertSubmissionButton_Click(object sender, EventArgs e)
    {
        //User's input value
        decimal input = decimal.Parse(UserInputTextBox.Text);
        string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
        string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

        decimal result =  input * conversionFactors.get(initialUnits, resultingUnits);

        ResultingValueLabel.Text = (result);
        ResultingValueLabel.Show();
    }

Maybe I'm approaching this the wrong way, and/or have been coding too long today.. I have looked up information about tuples and dictionarys and they seem like they would ideal for this scenario but I have failed in creating a working datatype from looping through the information in these existing arrays.

Any advice is greatly appreciated. Thanks a lot!

Body:
I think you would be better served by creating hard-coded functions inside a helper class for this. There is really no reason to place all these constant inside a dynamic array. That's going to be abstract, confusing and hard to keep track of. For example, your mass conversion class could look like this:

public static class MassConversion
{
    public static decimal GramsToKilograms(decimal grams) {
        return grams * .001;
    }
    public static decimal GramsToPounds(decimal grams) {
        return grams * .00220462;
    }
    public static decimal GramsToOunces(decimal grams) {
        return grams * .035274;
    }
    public static decimal KilogramsToGrams(decimal kilograms) {
        return kilograms* 1000;
    }
    //...
};

Then, to use it:

var grams = 4267;
var kilos = MassConversion.GramsToKilograms(grams);

This also has the benefit of being self-documenting.


来源: stackexchange

问:
Can I use different metadata for each library in Dspace
To clarify, when I go to search, i want to be able to chose different metadata based on the library I am searching in.

Also when I submit file, i want to be able to see different metadata fields based on the library where I am submitting the file.

Can I do this with Dspace? I know I can change some cfg files to edit metadata, but can i do it library depended. I have searched for an answer but couldn't find anything useful, so any link would be highly appreciated. Tnx

edit: Sorry for the mistake, what I meant to ask is can I use different metadata for each Community in Dspace.

答:
For submit forms

You can declare different forms and map them with collections in the submit form configuration. See documentation for the details. This refers to this file in the source.

For search filters

Similarly to the XML configuration for submit forms above, the search module, Discovery, can attach a different setup to each individual collection. See documentation for all config possibilities. The mapping of a given config with a collection can be made in this section of the config file, and configuring the list of filters or sidebar facets in a given config is similar to this section. Note that each filter / facet refers to a dedicated bean configuration that defines its behaviour, e.g. here for authors.

You'll probably need to experiment a bit before getting to exactly what you need, but unless I missed something, everything you're trying to do is doable via those files and — relatively — simple config.

Good luck !

ContentLicense: CC BY-SA 3.0


问:
Implementing NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy
Do anyone have a sample code for implementing image caching using NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy?

I am using the following code but seems like no caching is happening. All the time I am getting the image from the URL. Please tell me what's wrong here:

```<code>NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://i54.tinypic.com/10pd2jk.png"]];
    NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [req setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [[NSURLCache sharedURLCache] setMemoryCapacity:1024*1024*10];

    UIImage *myImage = [UIImage imageWithData:data];
    UIImageView *sd = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    sd.image = myImage;
    [self.view addSubview:sd];
</code>```

答:
You may want to take a look at using SDURLCache: https://github.com/rs/SDURLCache

SDURLCache actually saves cache to disk, whereas NSURLCache doesn't. NSURLCache only caches in memory, so within your app session. See ReadMe at link which explains it in more detail.

Update: Looks like NSURLCache does cache to disk since iOS 5.x: http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/

ContentLicense: CC BY-SA 2.5

Body:
Do anyone have a sample code for implementing image caching using NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy?

I am using the following code but seems like no caching is happening. All the time I am getting the image from the URL. Please tell me what's wrong here:

NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://i54.tinypic.com/10pd2jk.png"]];
    NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [req setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [[NSURLCache sharedURLCache] setMemoryCapacity:1024*1024*10];

    UIImage *myImage = [UIImage imageWithData:data];
    UIImageView *sd = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    sd.image = myImage;
    [self.view addSubview:sd];


问:
Relationships GraphQL
The second week I try to link two collections in the apollo-server-express / MongoDB / Mongoose / GraphQL stack, but I do not understand how. I found a similar lesson with the REST API, what I need is called Relationships. I need this, but in GraphQL

watch video

How to add cars to the User?
I collected the test server, the code is here: https://github.com/gHashTag/test-graphql-server
Help

答:
You need to add a resolver for the cars field on the User type.

```<code>const resolvers = {
  Query: {
    getUsers: ...
    getCars: ...
    ...
  },
  Mutation: {
    ...
  },
  User: {
    cars: ...
  }
}
</code>```

Title: Relationships GraphQL

Body:
You need to add a resolver for the cars field on the User type.

const resolvers = {
  Query: {
    getUsers: ...
    getCars: ...
    ...
  },
  Mutation: {
    ...
  },
  User: {
    cars: ...
  }
}


问:
Matching an array of Objects using Mockito
I'm trying to set up a mock for a method that takes an array of Request objects:

```<code>client.batchCall(Request[])
</code>```

I've tried these two variations:

```<code>when(clientMock.batchCall(any(Request[].class))).thenReturn(result);
...
verify(clientMock).batchCall(any(Request[].class));
</code>```

and

```<code>when(clientMock.batchCall((Request[])anyObject())).thenReturn(result);
...
verify(clientMock).batchCall((Request[])anyObject());
</code>```

But I can tell the mocks aren't being invoked.

They both result in the following error:

```<code>Argument(s) are different! Wanted:
clientMock.batchCall(
    <any>
);
-> at com.my.pkg.MyUnitTest.call_test(MyUnitTest.java:95)
Actual invocation has different arguments:
clientMock.batchCall(
    {Request id:123},
    {Request id:456}
);
</code>```

Why does the  matcher not match the array? Is there a special matcher I need to use to match an array of objects? The closest thing I can find is AdditionalMatches.aryEq(), but that requires that I specify the exact contents of the array, which I'd rather not do.

答:
Necroposting, but check whether the method you're calling is declared as batchCall(Request[] requests) or batchCall(Request... requests).

If it's the latter, try when(clientMock.batchCall(Mockito.anyVararg())).

Body:
I'm trying to set up a mock for a method that takes an array of Request objects:

client.batchCall(Request[])

I've tried these two variations:

when(clientMock.batchCall(any(Request[].class))).thenReturn(result);
...
verify(clientMock).batchCall(any(Request[].class));

and

when(clientMock.batchCall((Request[])anyObject())).thenReturn(result);
...
verify(clientMock).batchCall((Request[])anyObject());

But I can tell the mocks aren't being invoked.

They both result in the following error:

Argument(s) are different! Wanted:
clientMock.batchCall(
    <any>
);
-> at com.my.pkg.MyUnitTest.call_test(MyUnitTest.java:95)
Actual invocation has different arguments:
clientMock.batchCall(
    {Request id:123},
    {Request id:456}
);

Why does the  matcher not match the array? Is there a special matcher I need to use to match an array of objects? The closest thing I can find is AdditionalMatches.aryEq(), but that requires that I specify the exact contents of the array, which I'd rather not do.


问:
Star Button in Android
I'd like to put one star-shaped button in my app, just like a rating star.  I've already tried to use a one star rating bar, but unfortunately it doesn't work as a button.

I'd like it to work as a button, even better if the background of the selected state is yellow...any suggestions? Thanks.

答:
You can try to insert it as a text view. It was the easiest way I found to do this.

In the layout xml I added it as a text view

```<code><TextView
    android:id="@+id/tv_star_fav"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#00ffffff"
    android:onClick="onToggleStar"
    android:text="★"
    android:textSize="40sp" />
</code>```

Then in the code wrote a function like the following.

```<code>boolean isfavourite;

public void onToggleStar(View view){
    TextView favouriteStar = (TextView) view;
    if(!isfavourite){
        // if the star is not already selected and you select it
        isfavourite = true;
        favouriteStar.setTextColor(Color.parseColor("#FFD600"));
    }else{
        // if the star is already selected and you unselect it
        isfavourite = false;
        favouriteStar.setTextColor(Color.parseColor("#9E9E9E"));
    }

}
</code>```

Title: Star Button in Android

Body:
You can try to insert it as a text view. It was the easiest way I found to do this.

In the layout xml I added it as a text view

<TextView
    android:id="@+id/tv_star_fav"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#00ffffff"
    android:onClick="onToggleStar"
    android:text="★"
    android:textSize="40sp" />

Then in the code wrote a function like the following.

boolean isfavourite;

public void onToggleStar(View view){
    TextView favouriteStar = (TextView) view;
    if(!isfavourite){
        // if the star is not already selected and you select it
        isfavourite = true;
        favouriteStar.setTextColor(Color.parseColor("#FFD600"));
    }else{
        // if the star is already selected and you unselect it
        isfavourite = false;
        favouriteStar.setTextColor(Color.parseColor("#9E9E9E"));
    }

}


问:
No test assemblies found matching the pattern - Visual Studio Test - VSTS
This question is similar to - VSTS Test Assemblies - No test assemblies found - which appeared to resolve itself at the time. Unfortunately I'm getting a similar recurrence that I'm not sure how to resolve.

During my Visual Studio Test step, I'm getting the following message....

```<code>2017-12-05T18:43:31.9808980Z ##[warning]No test assemblies found matching the pattern: *SA.SEPA.Web.UI.Selenium.dll.
</code>```

In my VSTS tasks, after I build my solution, I copy an entire project directory to a directory on the virtual machine. This virtual machine is also hosting the build agent.

The path to the test assembly file is here, after the files have been copied....

My test task looks like the following....

The search folder should be correct, as this is the machine with the build agent.

Looking at the minimatch patterns described here - https://learn.microsoft.com/en-us/vsts/build-release/tasks/file-matching-patterns, *SA.SEPA.Web.UI.Selenium.dll should also match to the SA.SEPA.Web.UI.Selenium.dll file, possibly without requiring the asterix (?)

The build log is located here - https://gist.github.com/Konnor5092/1feb4536f7dd92218de27df8f3fefc52

Any help would be much appreciated.

答:
Your dll is in a sub directory of c:\build so the search will need to be recursive:

```<code>**\SA.SEPA.Web.UI.Selenium.dll
</code>```

or change the search folder to c:\build\bin\debug

Body:
This question is similar to - VSTS Test Assemblies - No test assemblies found - which appeared to resolve itself at the time. Unfortunately I'm getting a similar recurrence that I'm not sure how to resolve.

During my Visual Studio Test step, I'm getting the following message....

2017-12-05T18:43:31.9808980Z ##[warning]No test assemblies found matching the pattern: *SA.SEPA.Web.UI.Selenium.dll.

In my VSTS tasks, after I build my solution, I copy an entire project directory to a directory on the virtual machine. This virtual machine is also hosting the build agent.

The path to the test assembly file is here, after the files have been copied....

My test task looks like the following....

The search folder should be correct, as this is the machine with the build agent.

Looking at the minimatch patterns described here - https://learn.microsoft.com/en-us/vsts/build-release/tasks/file-matching-patterns, *SA.SEPA.Web.UI.Selenium.dll should also match to the SA.SEPA.Web.UI.Selenium.dll file, possibly without requiring the asterix (?)

The build log is located here - https://gist.github.com/Konnor5092/1feb4536f7dd92218de27df8f3fefc52

Any help would be much appreciated.

Body:
Your dll is in a sub directory of c:\build so the search will need to be recursive:

**\SA.SEPA.Web.UI.Selenium.dll

or change the search folder to c:\build\bin\debug


问:
Hitting EBS volume limit
I am trying to launch 210 instances of type p2.xlarge. Earlier I am hitting instance limit which I have increased now to 300 but now I am getting  'Client.VolumeLimitExceeded: Volume limit exceeded' error. Can you please help to resolve this issue? Any one knows the

What is Volume limit?

What should I request to increase inorder to run 210 instance (p2.xlarge) and aviod this error.

答:
The default EBS limits are: Amazon Elastic Block Store (Amazon EBS) Limits

It is the number of EBS volumes an account can use. You have a bigger problem if you are launching 210 p2.xlarge instances. You will hit various resource limits. You may need to request increase in limits for those resources.

Delete unattached/unused EBS volumes in your account

Check your EBS limits in: Amazon EC2 Service Limits

Calculate the number of volumes you will be using for each instance (Check your AMI)

Request for more EBS volume limit.

Title: Hitting EBS volume limit


问:
In iOS, how do I reference an object in a view that is created with a xib file?
I have a view controller that is instantiated in appDelegate and pushed onto a navigation controller. The view controller's view is created with a xib file. The xib file puts a UILabel on the view (among other things). Now I need to set the label's text property programatically but I don't see how to get a reference to it. How do I reference the label object?

I'm using xcode 3.2.5 and building an iPad app.

答:
Aside from IBOutlets, you can also set a tag property on the label in the IB. Then, when you need it you can do:

```<code>UILabel *label = (UILabel *)[self.view viewWithTag:111];
</code>```

111 of course being the tag you assigned to the label in IB.

Body:
Aside from IBOutlets, you can also set a tag property on the label in the IB. Then, when you need it you can do:

UILabel *label = (UILabel *)[self.view viewWithTag:111];

111 of course being the tag you assigned to the label in IB.


问:
SQL combine two select across multiple tables
So I've these tables:

Table 1:

```<code>facilities   emails
Fac 1        fac1@email.com
Fac 2        fac2@email.com
Fac 1 RE     fac1@email.com
</code>```

Table 2:

```<code>facilities  emails
fac1        fac1@email.com
fac2        fac3@email.com
</code>```

Now, on those two tables, I am trying to figure out how many facilities are using each address email. I have two sql queries that do just that:

```<code>SELECT ce.email, count(*)
AS TOTAL_FACILITIES
FROM table1
AS ce
GROUP BY ce.email
ORDER BY TOTAL_FACILITIES DESC

SELECT ca.emails, count(*)
AS TOTAL_FACILITIES
FROM table2
AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC
</code>```

This gives me the different emails from each table and how many facilities use them. I'm now  trying to combine it into a single call using a join but I can't seem to figure out how to make the count work.

Any suggestions?

答:
I think you are looking for something like this:  </p>

```<code>SELECT A.emails, COUNT(*) as total_facilities
FROM
(SELECT * FROM table1 UNION ALL SELECT * FROM table2) A
GROUP BY A.emails
ORDER BY COUNT(*) DESC;
</code>```

Body:
So I've these tables:

Table 1:

facilities   emails
Fac 1        fac1@email.com
Fac 2        fac2@email.com
Fac 1 RE     fac1@email.com

Table 2:

facilities  emails
fac1        fac1@email.com
fac2        fac3@email.com

Now, on those two tables, I am trying to figure out how many facilities are using each address email. I have two sql queries that do just that:

SELECT ce.email, count(*)
AS TOTAL_FACILITIES
FROM table1
AS ce
GROUP BY ce.email
ORDER BY TOTAL_FACILITIES DESC

SELECT ca.emails, count(*)
AS TOTAL_FACILITIES
FROM table2
AS ca
GROUP BY ca.emails
ORDER BY TOTAL_FACILITIES DESC

This gives me the different emails from each table and how many facilities use them. I'm now  trying to combine it into a single call using a join but I can't seem to figure out how to make the count work.

Any suggestions?

Body:
I think you are looking for something like this:

SELECT A.emails, COUNT(*) as total_facilities
FROM
(SELECT * FROM table1 UNION ALL SELECT * FROM table2) A
GROUP BY A.emails
ORDER BY COUNT(*) DESC;


问:
Change select box option background color
I have a select box and I'm trying to change the background color of the options when the select box has been clicked and shows all the options.

body {
  background: url(http://subtlepatterns.com/patterns/black_linen_v2.png) repeat;
}

select {
  margin: 40px;
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select>
  <option val="">Please choose</option>
  <option val="1">Option 1</option>
  <option val="2">Option 2</option>
  <option val="3">Option 3</option>
  <option val="4">Option 4</option>
</select></code>```

答:
Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

ContentLicense: CC BY-SA 4.0

Body:
I have a select box and I'm trying to change the background color of the options when the select box has been clicked and shows all the options.

body {
  background: url(http://subtlepatterns.com/patterns/black_linen_v2.png) repeat;
}

select {
  margin: 40px;
  background: rgba(0, 0, 0, 0.3);
  color: #fff;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}

<select>
  <option val="">Please choose</option>
  <option val="1">Option 1</option>
  <option val="2">Option 2</option>
  <option val="3">Option 3</option>
  <option val="4">Option 4</option>
</select>


问:
Liquid: resolve a link function from a variable
Well, I got a menu.yaml like so:

```<code>  entries:
  - title: Welcome to my site
    url: /

  - title: Über mich
    link: about_DE.md

  - title: About me
    link: about_EN.md

  - title: Parcour
    url: /parcours/
</code>```

As you can see, I sometimes use an explicit url, sometimes the page name, that can directly be resolved with {% link _pages/about_DE.md %}

Now my problem: How to do that in a loop, when I can't write the link explictly but rather must use a variable like item.link?

```<code>{% for item in site.data.header.entries %}

    {% if item.link %}
    {% link item.link %}
    {% else %}
    {{ item.url }}
    {% endif %}
</code>```

Liquid Exception: Could not find document '{{item.link}}' in tag 'link'.

How can I tell Liquid, that item.link is a link, note already the page name. And then resolve it to an actual URL? Or is there a corresponding filter?

答:
While traversing the for loop, if the item has a link then we look through all our pages which one has that path, that will be our page.

```<code>{% for item in site.data.menu.entries %}
{% if item.link %}
 {% assign apost = site.pages | where:"path",item.link  | first %}
   <a href="{{apost.url}}">{{apost.title}}</a>
{% endif %}
{%endfor %}
</code>```

Body:
Well, I got a menu.yaml like so:

  entries:
  - title: Welcome to my site
    url: /

  - title: Über mich
    link: about_DE.md

  - title: About me
    link: about_EN.md

  - title: Parcour
    url: /parcours/

As you can see, I sometimes use an explicit url, sometimes the page name, that can directly be resolved with {% link _pages/about_DE.md %}

Now my problem: How to do that in a loop, when I can't write the link explictly but rather must use a variable like item.link?

{% for item in site.data.header.entries %}

    {% if item.link %}
    {% link item.link %}
    {% else %}
    {{ item.url }}
    {% endif %}

Liquid Exception: Could not find document '{{item.link}}' in tag 'link'.

How can I tell Liquid, that item.link is a link, note already the page name. And then resolve it to an actual URL? Or is there a corresponding filter?

Body:
While traversing the for loop, if the item has a link then we look through all our pages which one has that path, that will be our page.

{% for item in site.data.menu.entries %}
{% if item.link %}
 {% assign apost = site.pages | where:"path",item.link  | first %}
   <a href="{{apost.url}}">{{apost.title}}</a>
{% endif %}
{%endfor %}


问:
help need to start developing simple jigsaw puzzle game
i am doing a simple  game like puzzle.

for that there is 9-patch image in android.

similarly is there is any facility in iphone.

i am doing manually  for this as fallows.

```<code> UIImage* whole = [UIImage imageNamed:@"bull.jpg"]; //I know this image is 300x300

     int partId = 0;
     for (int x=0; x<=200; x+=100) {
         for(int y=0; y<=200; y+=100) {
             CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, 100, 100));
             UIImage* part = [UIImage imageWithCGImage:cgImg];
            if (partId == 0 ) {
                photo.image = part;

            }
             if (partId == 1 ) {
                 photo1.image = part;

             }
             if (partId == 2 ) {
                 photo2.image = part;

             }
             if (partId == 3 ) {
                 photo3.image = part;

             }
             if (partId == 4 ) {
                 photo4.image = part;

             }
             if (partId == 5 ) {
                 photo5.image = part;

             }
             if (partId == 6 ) {
                 photo6.image = part;

             }
             if (partId == 7 ) {
                 photo7.image = part;

             }
             if (partId == 8 ) {
                 photo8.image = part;

             }

             partId++;
         }
     }
</code>```

here photo,photo1,...,photo8 are image views
 but this is not good.

while dragging images one images comes under the another images.

can any one please suggest better way to start my puzzle game.

Thank u in advance.

答:
I think you should probably check out the UIImage documentation:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html

In particular, this method:

```<code>- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight
</code>```

iOS doesn't have a '9-patch' image, in the sense that a 9-patch defines the stretchable sections within the image itself. Instead, you define the stretchable parts of the image in code (leftCapWidth and topCapHeight respectively).

I'm not quite sure how that helps you with your game, but since your question was 'is there something similar to 9-patch' on iOS, I hope this answer suffices!

Body:
i am doing a simple  game like puzzle.

for that there is 9-patch image in android.

similarly is there is any facility in iphone.

i am doing manually  for this as fallows.

 UIImage* whole = [UIImage imageNamed:@"bull.jpg"]; //I know this image is 300x300

     int partId = 0;
     for (int x=0; x<=200; x+=100) {
         for(int y=0; y<=200; y+=100) {
             CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, 100, 100));
             UIImage* part = [UIImage imageWithCGImage:cgImg];
            if (partId == 0 ) {
                photo.image = part;

            }
             if (partId == 1 ) {
                 photo1.image = part;

             }
             if (partId == 2 ) {
                 photo2.image = part;

             }
             if (partId == 3 ) {
                 photo3.image = part;

             }
             if (partId == 4 ) {
                 photo4.image = part;

             }
             if (partId == 5 ) {
                 photo5.image = part;

             }
             if (partId == 6 ) {
                 photo6.image = part;

             }
             if (partId == 7 ) {
                 photo7.image = part;

             }
             if (partId == 8 ) {
                 photo8.image = part;

             }

             partId++;
         }
     }

here photo,photo1,...,photo8 are image views
 but this is not good.

while dragging images one images comes under the another images.

can any one please suggest better way to start my puzzle game.

Thank u in advance.

Body:
I think you should probably check out the UIImage documentation:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html

In particular, this method:

- (UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

iOS doesn't have a '9-patch' image, in the sense that a 9-patch defines the stretchable sections within the image itself. Instead, you define the stretchable parts of the image in code (leftCapWidth and topCapHeight respectively).

I'm not quite sure how that helps you with your game, but since your question was 'is there something similar to 9-patch' on iOS, I hope this answer suffices!


问:
Getting result as Array
We are learning how to use Stream Reader, and i got some problems with methods, actually when im trying to get return value it doesn't work.

```<code>static void FindeMinMaxVerkauf(Verkauf[] arr, out Verkauf min, out Verkauf max)
{

    double min2 = 10000;
    double max2 = 0;
    int min3 = 0;
    int max3 = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        if((arr[i].StückPreis * arr[i].Stückzahl) < min2)
        {
            min2 = arr[i].StückPreis * arr[i].Stückzahl;
            min3 = i;
        }
        if ((arr[i].StückPreis * arr[i].Stückzahl) > max2)
        {
            max2 = arr[i].StückPreis * arr[i].Stückzahl;
            max3 = i;
        }
    }
    min = arr[min3];
    max = arr[max3];
}
</code>```

This is how im trying to get return value

```<code>double min,max;
FindeMinMaxVerkauf(alle, out min, out max);
Console.WriteLine("Verkäufe mit kleinsten Preis " + min + "Verkäufe mit größten Preis" + max );
</code>```

But it says

CS1503    Argument "3": Konvertierung von "out double" in "out
  _61_T_Shirts.Verkauf" nicht möglich.

It means converting from double in Tshirts... not possible. I dont know how to fix it really.

This is my second methode:

```<code>static Verkauf FindeHöchsteStückzahl(Verkauf[] arr)
{
    int anz = 0;
    int pos = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Stückzahl > anz)
        {
            anz = arr[i].Stückzahl;
            pos = i;
        }
    }
    return arr[pos];
}
</code>```

And this is how I'm trying to get return value:

```<code>FindeHöchsteStückzahl(alle);
Console.WriteLine("Höchste Stückzahl: " + alle );
</code>```

But I'm getting Array as result:

```<code>Höchste Stückzahl: _61_T_Shirts.Verkauf[]
</code>```

I mean this:

```<code>static Verkauf[] FindeVerkäufe(Verkauf[] arr, string farbe)
{
    int j = 0;
    Verkauf[] finderverk = new Verkauf[10000];
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Farbe == farbe)
        {
            finderverk[j] = arr[i];
            j++;
        }
    }
    Array.Resize(ref finderverk, j);
    return finderverk;
}
</code>```

}
}

I need help ;D

答:
First problem. Why not just follow suit and declare min as well as max being Verkauf?

```<code>Verkauf min, max; // Verkauf, not double
FindeMinMaxVerkauf(alle, out min, out max);

// String interpolation - $"... {value} ..." is more readable
// We have min and max of type Verkauf; we want to print out StückPreis:
Console.WriteLine(
  $"Verkäufe mit kleinsten Preis {min.StückPreis} Verkäufe mit größten Preis {max.StückPreis}");
</code>```

Second problem. You have to save the result of FindeHöchsteStückzahl call and then display it, not the initial array:

```<code>// Save the result of the method call (sorry for the umlaut)
var hoch = FindeHöchsteStückzahl(alle);

// ... and print out the result (hoch), not the initial array
// If you haven't implement `ToString()` in the Verkauf class
// You, probably, don't want {hoch} but {hoch.StückPreis}:
// Console.WriteLine($"Höchste Stückzahl: {hoch.StückPreis}");
Console.WriteLine($"Höchste Stückzahl: {hoch}");
</code>```

Edit: If you want to return an array, i.e. Verkauf[] (First and Second problem combined):

```<code>// Array: 1st item is min, 2nd one is max
static Verkauf[] MinMaxVerkauf(Verkauf[] value) {
  Verkauf min, max;
  FindeMinMaxVerkauf(alle, out min, out max);

  return new Verkauf[] {min, max};
}

...

var minmax = MinMaxVerkauf(alle);

Console.WriteLine(
  $"Verkäufe mit kleinsten Preis {minmax[0].StückPreis} Verkäufe mit größten Preis {minmax[1].StückPreis}");
</code>```

Edit 2: When you want to query your data (find out the max StückPreis of some Farbe) try using Linq which has been specially designed for such purpose:

```<code>using System.Linq;

...

// See how it's easy (the third problem in the question):
static Verkauf[] FindeVerkäufe(Verkauf[] arr, string farbe) {
  return arr
    .Where(stuck => stuck.Farbe == farbe)
    .ToArray();
}

...

string farbe = "Rot";

double max = alle
  .Where(stuck => stuck.Farbe == farbe)
  .Max(stuck => stuck.StückPreis);

double min = alle
  .Where(stuck => stuck.Farbe == farbe)
  .Min(stuck => stuck.StückPreis);

Console.WriteLine(
  $"Farbe {farbe}: Verkäufe mit kleinsten Preis {min.StückPreis} Verkäufe mit größten Preis {max.StückPreis}");
</code>```

Title: Getting result as Array

Body:
We are learning how to use Stream Reader, and i got some problems with methods, actually when im trying to get return value it doesn't work.

static void FindeMinMaxVerkauf(Verkauf[] arr, out Verkauf min, out Verkauf max)
{

    double min2 = 10000;
    double max2 = 0;
    int min3 = 0;
    int max3 = 0;

    for (int i = 0; i < arr.Length; i++)
    {
        if((arr[i].StückPreis * arr[i].Stückzahl) < min2)
        {
            min2 = arr[i].StückPreis * arr[i].Stückzahl;
            min3 = i;
        }
        if ((arr[i].StückPreis * arr[i].Stückzahl) > max2)
        {
            max2 = arr[i].StückPreis * arr[i].Stückzahl;
            max3 = i;
        }
    }
    min = arr[min3];
    max = arr[max3];
}

This is how im trying to get return value

double min,max;
FindeMinMaxVerkauf(alle, out min, out max);
Console.WriteLine("Verkäufe mit kleinsten Preis " + min + "Verkäufe mit größten Preis" + max );

But it says

CS1503    Argument "3": Konvertierung von "out double" in "out
  _61_T_Shirts.Verkauf" nicht möglich.

It means converting from double in Tshirts... not possible. I dont know how to fix it really.

This is my second methode:

static Verkauf FindeHöchsteStückzahl(Verkauf[] arr)
{
    int anz = 0;
    int pos = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Stückzahl > anz)
        {
            anz = arr[i].Stückzahl;
            pos = i;
        }
    }
    return arr[pos];
}

And this is how I'm trying to get return value:

FindeHöchsteStückzahl(alle);
Console.WriteLine("Höchste Stückzahl: " + alle );

But I'm getting Array as result:

Höchste Stückzahl: _61_T_Shirts.Verkauf[]

I mean this:

static Verkauf[] FindeVerkäufe(Verkauf[] arr, string farbe)
{
    int j = 0;
    Verkauf[] finderverk = new Verkauf[10000];
    for (int i = 0; i < arr.Length; i++)
    {
        if(arr[i].Farbe == farbe)
        {
            finderverk[j] = arr[i];
            j++;
        }
    }
    Array.Resize(ref finderverk, j);
    return finderverk;
}

}
}

I need help ;D

Body:
First problem. Why not just follow suit and declare min as well as max being Verkauf?

Verkauf min, max; // Verkauf, not double
FindeMinMaxVerkauf(alle, out min, out max);

// String interpolation - $"... {value} ..." is more readable
// We have min and max of type Verkauf; we want to print out StückPreis:
Console.WriteLine(
  $"Verkäufe mit kleinsten Preis {min.StückPreis} Verkäufe mit größten Preis {max.StückPreis}");

Second problem. You have to save the result of FindeHöchsteStückzahl call and then display it, not the initial array:

// Save the result of the method call (sorry for the umlaut)
var hoch = FindeHöchsteStückzahl(alle);

// ... and print out the result (hoch), not the initial array
// If you haven't implement `ToString()` in the Verkauf class
// You, probably, don't want {hoch} but {hoch.StückPreis}:
// Console.WriteLine($"Höchste Stückzahl: {hoch.StückPreis}");
Console.WriteLine($"Höchste Stückzahl: {hoch}");

Edit: If you want to return an array, i.e. Verkauf[] (First and Second problem combined):

// Array: 1st item is min, 2nd one is max
static Verkauf[] MinMaxVerkauf(Verkauf[] value) {
  Verkauf min, max;
  FindeMinMaxVerkauf(alle, out min, out max);

  return new Verkauf[] {min, max};
}

...

var minmax = MinMaxVerkauf(alle);

Console.WriteLine(
  $"Verkäufe mit kleinsten Preis {minmax[0].StückPreis} Verkäufe mit größten Preis {minmax[1].StückPreis}");

Edit 2: When you want to query your data (find out the max StückPreis of some Farbe) try using Linq which has been specially designed for such purpose:

using System.Linq;

...

// See how it's easy (the third problem in the question):
static Verkauf[] FindeVerkäufe(Verkauf[] arr, string farbe) {
  return arr
    .Where(stuck => stuck.Farbe == farbe)
    .ToArray();
}

...

string farbe = "Rot";

double max = alle
  .Where(stuck => stuck.Farbe == farbe)
  .Max(stuck => stuck.StückPreis);

double min = alle
  .Where(stuck => stuck.Farbe == farbe)
  .Min(stuck => stuck.StückPreis);

Console.WriteLine(
  $"Farbe {farbe}: Verkäufe mit kleinsten Preis {min.StückPreis} Verkäufe mit größten Preis {max.StückPreis}");


问:
Why would an inner static class extend the outer abstract class?

I am trying to extend some existing code that implements a tree using composite pattern. As expected from this pattern, there is an interface
 (Node) and an abstract class (AbstractNode) representing a generic node. The latter is extended by multiple concrete types of nodes (ConcreteNodeA, ConcreteNodeB, ConcreteNodeC).

I encountered this other pattern in the code that I am working with, in which the concrete classes are implemented as static inner classes, extending the outer abstract class. And at the same time they implement static inner interfaces (NodeA, NodeB, NodeC) from the outer(?) interface Node.

```<code>public interface Node {
  public static interface NodeA {}
  public static interface NodeB {}
  public static interface NodeC {}
}

public abstract class AbstractNode implements Node {

  public void foo() {
    ...
  }

  public void bar() {
    ...
  }

  ...

  public static class ConcreteNodeA extends AbstractNode implements Node.NodeA {
    ...
  }

  public static class ConcreteNodeB extends AbstractNode implements Node.NodeB {
    ...
  }

  public static class ConcreteNodeC extends AbstractNode implements Node.NodeC {
    ...
  }
}
</code>```

What is the use of this pattern? Through many years of experience with Java, I have never seen something like this before. My intuition says it is a massive code smell, as the concrete classes are constantly instantiated and used many times throughout the code. Anyway, I am not worried about efficiency, it is just that this is so difficult to mantain and extend!. It would make more sense to have them in separate classes, right?

I have searched for more formal references to prove it is bad idea to do it this way, but have not found anything yet.

There is no compiltation error, and the code works perfectly.

答:
This pattern is actually quite common when describing related families of types, such as the nodes of a tree.

One reason is simply that it is a convenient grouping; these classes tend to be individually small, and having them all in one place can make it easier to read and maintain, as well as sending the signal that they are a tightly coupled family and intended to be used together.

A more compelling reason is that it can provide a form of sealed classes.  By having a private constructor in the abstract class, only the inner classes can access it, meaning that the inner classes are the only allowed subclasses.

Body:
I am trying to extend some existing code that implements a tree using composite pattern. As expected from this pattern, there is an interface
 (Node) and an abstract class (AbstractNode) representing a generic node. The latter is extended by multiple concrete types of nodes (ConcreteNodeA, ConcreteNodeB, ConcreteNodeC).

I encountered this other pattern in the code that I am working with, in which the concrete classes are implemented as static inner classes, extending the outer abstract class. And at the same time they implement static inner interfaces (NodeA, NodeB, NodeC) from the outer(?) interface Node.

public interface Node {
  public static interface NodeA {}
  public static interface NodeB {}
  public static interface NodeC {}
}

public abstract class AbstractNode implements Node {

  public void foo() {
    ...
  }

  public void bar() {
    ...
  }

  ...

  public static class ConcreteNodeA extends AbstractNode implements Node.NodeA {
    ...
  }

  public static class ConcreteNodeB extends AbstractNode implements Node.NodeB {
    ...
  }

  public static class ConcreteNodeC extends AbstractNode implements Node.NodeC {
    ...
  }
}

What is the use of this pattern? Through many years of experience with Java, I have never seen something like this before. My intuition says it is a massive code smell, as the concrete classes are constantly instantiated and used many times throughout the code. Anyway, I am not worried about efficiency, it is just that this is so difficult to mantain and extend!. It would make more sense to have them in separate classes, right?

I have searched for more formal references to prove it is bad idea to do it this way, but have not found anything yet.

There is no compiltation error, and the code works perfectly.


问:
How to index a 1D numpy array as if it is a matrix with 1 row?
I have a 1D numpy array like:

```<code>a = np.array([1,2,3,4,5])
</code>```

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

```<code>a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array
</code>```

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

答:
You could use np.atleast_2d to promote 1D arrays to 2D:

```<code>a = np.atleast_2d(a)
</code>```

If you put this inside of your loop then you can henceforth treat all as as 2D (or higher-dimensional) arrays.

For example,

```<code>In [103]: a1 = np.array([1,2,3,4,5])
In [105]: np.atleast_2d(a1)
Out[107]: array([[1, 2, 3, 4, 5]])
</code>```

while higher-dimensional arrays are unchanged:

```<code>In [104]: a2 = np.array([[1,2],[3,4]])
In [108]: np.atleast_2d(a2)
Out[108]:
array([[1, 2],
       [3, 4]])
</code>```

Body:
I have a 1D numpy array like:

a = np.array([1,2,3,4,5])

And I would like to index this a like (as if it's a 1 by 5 matrix, and a[0,2] would be equal to 3):

a[0,2]

Traceback (most recent call last):

  File "<ipython-input-34-2fc0526218b3>", line 1, in <module>
    a[0,1]

IndexError: too many indices for array

I know in MATLAB it's possible, but how to do that in Python? The reason that I need this is coz that a is dynamically generated, sometimes it's a 1D array, sometimes it's a nD array. And I need a unified way of indexing in my loop.

Body:
You could use np.atleast_2d to promote 1D arrays to 2D:

a = np.atleast_2d(a)

If you put this inside of your loop then you can henceforth treat all as as 2D (or higher-dimensional) arrays.

For example,

In [103]: a1 = np.array([1,2,3,4,5])
In [105]: np.atleast_2d(a1)
Out[107]: array([[1, 2, 3, 4, 5]])

while higher-dimensional arrays are unchanged:

In [104]: a2 = np.array([[1,2],[3,4]])
In [108]: np.atleast_2d(a2)
Out[108]:
array([[1, 2],
       [3, 4]])


问:
Error make distcheck

I am trying to create Makefile.am and configure.ac

but i have errors when i type make dist or make distcheck

Makefile.am:

```<code>bin_PROGRAMS = neuromz
neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h
neuromz_CFLAGS = -lm
</code>```

counfigure.ac:

```<code>AC_INIT([neuromz] , [1.0] , [mz32programmer@gmail.com])

AC_PREREQ([2.68])
AC_CONFIG_SRCDIR([neuromz.c])
AC_CONFIG_HEADERS([config.h])
#AC_CONFIG_AUX_DIR([build-aux])
AM_INIT_AUTOMAKE([1.11 -Wall -Werror])
AC_CONFIG_FILES([Makefile])

AC_SEARCH_LIBS([exp],[m])
AC_PROG_CC
AM_PROG_CC_C_O

AC_OUTPUT
</code>```

i type the following command:

```<code> autoreconf -i
 ./configure
 make distcheck
</code>```

the result is :

```<code>mz@mz-32:~/programming/ctest/ANN$ make distcheck
make  dist-gzip am__post_remove_distdir='@:'
make[1]: Entering directory '/home/mz/programming/ctest/ANN'
if test -d "neuromz--1.0 "; then find "neuromz--1.0 " -type d ! -perm -200 -exec chmod u+w {} ';' && rm -rf "neuromz--1.0 " || { sleep 5 && rm -rf  "neuromz--1.0 "; }; else :; fi
test -d "neuromz--1.0 " || mkdir "neuromz--1.0 "
test -n "" \
|| find "neuromz--1.0 " -type d ! -perm -755 \
-exec chmod u+rwx,go+rx {} \; -o \
  ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
  ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
  ! -type d ! -perm -444 -exec /bin/bash /home/mz/programming/ctest/ANN/install-sh -c -m a+r {} {} \; \
|| chmod -R a+r "neuromz--1.0 "
tardir=neuromz--1.0  && ${TAR-tar} chof - "$tardir" | GZIP=--best gzip -c >neuromz--1.0 .tar.gz
gzip: .tar.gz: No such file or directory
Makefile:528: recipe for target 'dist-gzip' failed
make[1]: *** [dist-gzip] Error 1
make[1]: Leaving directory '/home/mz/programming/ctest/ANN'
Makefile:563: recipe for target 'dist' failed
make: *** [dist] Error 2
</code>```

what is the error ???

答:
The problem is here:

```<code>AC_INIT([neuromz] , [1.0] , [mz32programmer@gmail.com])
</code>```

Remember always that Autoconf is fundamentally a text processor and that space characters are part of the text it processes. Quoting with [] is just that -- quoting -- not demarcation of argument values.  The arguments are delimited by the commas in the argument list.

Autoconf ignores leading whitespace in macro arguments, but not trailing whitespace (though the manual does not call out the latter explicitly).  The trailing spaces in these particular arguments happen to screw up the build rule for the distribution tarball.  You might argue that Automake should apply more careful quotation in generated Makefiles, and I wouldn't argue with that.  Do note, however, that the result of it doing so in this case would likely not be what you expected or wanted.  In any event, you can resolve the problem simply by removing the trailing spaces from the macro arguments:

```<code>AC_INIT([neuromz], [1.0], [mz32programmer@gmail.com])
</code>```

Title: Error make distcheck

Body:
I am trying to create Makefile.am and configure.ac

but i have errors when i type make dist or make distcheck

Makefile.am:

bin_PROGRAMS = neuromz
neuromz_SOURCES = neuromz.c neuromz.h ann.c ann.h
neuromz_CFLAGS = -lm

counfigure.ac:

AC_INIT([neuromz] , [1.0] , [mz32programmer@gmail.com])

AC_PREREQ([2.68])
AC_CONFIG_SRCDIR([neuromz.c])
AC_CONFIG_HEADERS([config.h])
#AC_CONFIG_AUX_DIR([build-aux])
AM_INIT_AUTOMAKE([1.11 -Wall -Werror])
AC_CONFIG_FILES([Makefile])

AC_SEARCH_LIBS([exp],[m])
AC_PROG_CC
AM_PROG_CC_C_O

AC_OUTPUT

i type the following command:

 autoreconf -i
 ./configure
 make distcheck

the result is :

mz@mz-32:~/programming/ctest/ANN$ make distcheck
make  dist-gzip am__post_remove_distdir='@:'
make[1]: Entering directory '/home/mz/programming/ctest/ANN'
if test -d "neuromz--1.0 "; then find "neuromz--1.0 " -type d ! -perm -200 -exec chmod u+w {} ';' && rm -rf "neuromz--1.0 " || { sleep 5 && rm -rf  "neuromz--1.0 "; }; else :; fi
test -d "neuromz--1.0 " || mkdir "neuromz--1.0 "
test -n "" \
|| find "neuromz--1.0 " -type d ! -perm -755 \
-exec chmod u+rwx,go+rx {} \; -o \
  ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
  ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
  ! -type d ! -perm -444 -exec /bin/bash /home/mz/programming/ctest/ANN/install-sh -c -m a+r {} {} \; \
|| chmod -R a+r "neuromz--1.0 "
tardir=neuromz--1.0  && ${TAR-tar} chof - "$tardir" | GZIP=--best gzip -c >neuromz--1.0 .tar.gz
gzip: .tar.gz: No such file or directory
Makefile:528: recipe for target 'dist-gzip' failed
make[1]: *** [dist-gzip] Error 1
make[1]: Leaving directory '/home/mz/programming/ctest/ANN'
Makefile:563: recipe for target 'dist' failed
make: *** [dist] Error 2

what is the error ???

Body:
The problem is here:

AC_INIT([neuromz] , [1.0] , [mz32programmer@gmail.com])

Remember always that Autoconf is fundamentally a text processor and that space characters are part of the text it processes. Quoting with [] is just that -- quoting -- not demarcation of argument values.  The arguments are delimited by the commas in the argument list.

Autoconf ignores leading whitespace in macro arguments, but not trailing whitespace (though the manual does not call out the latter explicitly).  The trailing spaces in these particular arguments happen to screw up the build rule for the distribution tarball.  You might argue that Automake should apply more careful quotation in generated Makefiles, and I wouldn't argue with that.  Do note, however, that the result of it doing so in this case would likely not be what you expected or wanted.  In any event, you can resolve the problem simply by removing the trailing spaces from the macro arguments:

AC_INIT([neuromz], [1.0], [mz32programmer@gmail.com])


问:
VBA - Excel Forces Restart
I am having a major issue with my code that is supposed to reset the worksheets, not shut down the entire workbook and force a restart.  This has not been an issue, and has only occured since I added the last bit of code starting at On Error Resume Next.

```<code>Sub Reset()

    Application.ScreenUpdating = False

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "Set Up" Or ws.Name = "Report" Then
            Else:
                Application.DisplayAlerts = False
                ws.Delete
        End If
    Next

    Worksheets("Report").Cells.ClearContents

    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Charts.Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End Sub
</code>```

Thanks in advance

答:
this deletes the charts in a workhseet, say activesheet for example:

```<code>Sub DeleteallCharts()
    Dim chtObj As ChartObject
    For Each chtObj In ActiveSheet.ChartObjects
        chtObj.Delete
    Next
End Sub
</code>```

if you want to delete all of the charts in the workbook, then you have to loop through the worksheet too like this:

```<code>Sub DeleteallChartsInWorkbook()
    Dim chtObj As ChartObject
    Dim WS As Worksheet
    For Each WS in Thisworkbook.Worksheets
        For Each chtObj In WS.ChartObjects
            chtObj.Delete
        Next chtObj
    Next WS
End Sub
</code>```

Title: VBA - Excel Forces Restart

Body:
I am having a major issue with my code that is supposed to reset the worksheets, not shut down the entire workbook and force a restart.  This has not been an issue, and has only occured since I added the last bit of code starting at On Error Resume Next.

Sub Reset()

    Application.ScreenUpdating = False

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "Set Up" Or ws.Name = "Report" Then
            Else:
                Application.DisplayAlerts = False
                ws.Delete
        End If
    Next

    Worksheets("Report").Cells.ClearContents

    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Charts.Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End Sub

Thanks in advance

Body:
this deletes the charts in a workhseet, say activesheet for example:

Sub DeleteallCharts()
    Dim chtObj As ChartObject
    For Each chtObj In ActiveSheet.ChartObjects
        chtObj.Delete
    Next
End Sub

if you want to delete all of the charts in the workbook, then you have to loop through the worksheet too like this:

Sub DeleteallChartsInWorkbook()
    Dim chtObj As ChartObject
    Dim WS As Worksheet
    For Each WS in Thisworkbook.Worksheets
        For Each chtObj In WS.ChartObjects
            chtObj.Delete
        Next chtObj
    Next WS
End Sub


问:
Counting rows with a condition
i work with a table "ships" like this:

```<code>shipid
container1
container2
</code>```

shipid and container1 are always filled, container2 is optional.

This is my query for now:

```<code>SELECT COUNT(container1) FROM table
</code>```

How can i achieve that this query counts the amount of the container2's too?!

It must be a joined query made of those both queries:

```<code>SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''
</code>```

Thanks for any hints!

答:
```<code>SELECT COUNT(container1) FROM table
UNION
SELECT COUNT(container2) FROM table
</code>```

Title: Counting rows with a condition

Body:
i work with a table "ships" like this:

shipid
container1
container2

shipid and container1 are always filled, container2 is optional.

This is my query for now:

SELECT COUNT(container1) FROM table

How can i achieve that this query counts the amount of the container2's too?!

It must be a joined query made of those both queries:

SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''

Thanks for any hints!


问:
React big calendar hide start time end time from time slot
I have a react big calendar as in teh picture below, and I want to remove the circled strat-time/end time:

The react big calendare is rendered with this parameters:

```<code><BigCalendar
                selectable
                events={this.props.events?this.props.events:[]}
                views={{ week:MyWeek}}
                defaultView='week'
                defaultDate={this.state.date?this.state.date:new Date()}
                date={this.state.date?this.state.date:new Date()}
                now={new Date(0)}
                min={new Date(this.state.today.getFullYear(), this.state.today.getMonth(), this.state.today.getDate(), 8)}
                max={new Date(this.state.today.getFullYear(), this.state.today.getMonth(), this.state.today.getDate(), 20)}
                onSelectSlot={(slotInfo) => {this.props.onSelectSlot('interview', slotInfo, 'add'); store.dispatch(addBreadcrumb({name: B_PREPARATION_INTERVIEW}));}}
                onSelectEvent={event => {this.props.onSelectEvent('interview', event); store.dispatch(addBreadcrumb({name: B_PREPARATION_INTERVIEW}));} }
                onNavigate={(date) => this.changeDate(date)}
                components={{event: Event }}
                eventPropGetter={(this.eventStyleGetter)}
                titleAccessor={function(e) {console.log("aaaaaaaaaaa"); console.log(e); return e.title;}}
            />
</code>```

I tried to add titleAccessor to remove the start time/end time but with no result.

答:
You can override the CSS class rbc-event-label like so:

```<code>.rbc-event-label {
  display: none;
}
</code>```

to hide the start and end times.

Body:
I have a react big calendar as in teh picture below, and I want to remove the circled strat-time/end time:

The react big calendare is rendered with this parameters:

<BigCalendar
                selectable
                events={this.props.events?this.props.events:[]}
                views={{ week:MyWeek}}
                defaultView='week'
                defaultDate={this.state.date?this.state.date:new Date()}
                date={this.state.date?this.state.date:new Date()}
                now={new Date(0)}
                min={new Date(this.state.today.getFullYear(), this.state.today.getMonth(), this.state.today.getDate(), 8)}
                max={new Date(this.state.today.getFullYear(), this.state.today.getMonth(), this.state.today.getDate(), 20)}
                onSelectSlot={(slotInfo) => {this.props.onSelectSlot('interview', slotInfo, 'add'); store.dispatch(addBreadcrumb({name: B_PREPARATION_INTERVIEW}));}}
                onSelectEvent={event => {this.props.onSelectEvent('interview', event); store.dispatch(addBreadcrumb({name: B_PREPARATION_INTERVIEW}));} }
                onNavigate={(date) => this.changeDate(date)}
                components={{event: Event }}
                eventPropGetter={(this.eventStyleGetter)}
                titleAccessor={function(e) {console.log("aaaaaaaaaaa"); console.log(e); return e.title;}}
            />

I tried to add titleAccessor to remove the start time/end time but with no result.

Body:
You can override the CSS class rbc-event-label like so:

.rbc-event-label {
  display: none;
}

to hide the start and end times.


问:
Create edit form for Primefaces table
I want to create edit form for Primefaces table. I tested this code:

```<code><h:form id="form">
    <p:dataTable id="tbl" var="systemuser" value="#{systemusers.systemUsers}"
                 selectionMode="single" selection="#{systemusers.selectedSystemUser}" rowKey="#{systemuser.username}" lazy="true"
                 resizableColumns="true"
                 >

        <p:ajax event="rowSelect" listener="#{systemusers.onRowSelect}" update=":form:carDetail" oncomplete="PF('carDialog').show()" />
        ....................
    </p:dataTable>

    <p:dialog id="wd" header="System User Details" widgetVar="carDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="true">
        <p:outputPanel id="carDetail" style="text-align:center;">
            <p:panelGrid  columns="2"  columnClasses="label,value">

                <h:outputLabel for="id" value="ID" />
                <p:outputLabel id="id" value="#{systemusers.selectedSystemUser.id}" rendered="#{not systemusers.editable}"/>
                <h:inputText value="#{systemusers.selectedSystemUser.id}" rendered="#{systemusers.editable}" />
                ........
            </p:panelGrid>
        </p:outputPanel>

        <f:facet name="footer">
            <p:commandButton value="Edit System User" rendered="#{not systemusers.editable}"
                             actionListener="#{systemusers.editRecord(false)}">
                <f:ajax render=":form:wd" execute=":form:wd"></f:ajax>
            </p:commandButton>

            <p:commandButton value="Cancel" rendered="#{systemusers.editable}" actionListener="#{systemusers.editRecord(true)}">
                <f:ajax render=":form" execute=":form"></f:ajax>
            </p:commandButton>
        </f:facet>
    </p:dialog>

    <p:contextMenu for="tbl">
        <p:menuitem value="View" update="carDetail" icon="fa fa-search" oncomplete="PF('carDialog').show()"/>
        <p:menuitem value="Delete" update="tbl" icon="fa fa-remove" actionListener="#{systemusers.deleteSystemUser}">
            <p:confirm header="Confirmation" message="Are you sure?" icon="fa fa-warning" />
        </p:menuitem>
    </p:contextMenu>

    <p:confirmDialog global="true" showEffect="fade" hideEffect="fade">
        <p:commandButton value="Yes" type="button" styleClass="ui-confirmdialog-yes" icon="fa fa-check" />
        <p:commandButton value="No" type="button" styleClass="ui-confirmdialog-no" icon="fa fa-remove" />
    </p:confirmDialog>
</h:form>
</code>```

Managed bean:

```<code>@Named
@RequestScoped
public class Systemusers implements Serializable
{
.......
public void editRecord(boolean editable)
    {
        SessionFactory factory = HibernateUtils.getSessionFactory();
        Session session = factory.getCurrentSession();

        try
        {
            session.getTransaction().begin();

            SystemUsersModel obj = new SystemUsersModel();
            obj.setId(selectedSystemUser.getId());
            ..........
            session.update(obj);

            session.getTransaction().commit();

            this.editable = editable;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
    }
......
private boolean editable = false;

    public boolean isEditable()
    {
        return editable;
    }

    public void setEditable(boolean editable)
    {
        this.editable = editable;
    }
}
</code>```

When I open the Edit form and I click button Edit System User the form disappears. Probably because I render and execute it. How I can execute the form and under it without closing it?

答:
The example code is bad in multiple ways. Two things stand out:

It is not an [mcve]

<f:ajax render=":form" execute=":form"> is superfluous or might even cause the weird behaviour

OP most likely does not know that (quote from the PrimeFaces showcase , emphasis mine)

CommandButton

CommandButton extends the standard h:commandButton with ajax, partial processing and skinning features.

So the commandBotton is already ajax anabled and does not need to hava a

```<code><f:ajax render=":form" execute=":form">
</code>```

inside it. This (most likely) makes an the update run twice. One @none (Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes) and one updating the form. The second one most likely does not have any content. But trying (and debugging) will make things clear. If this is not the answer, the reason cannot be seen in the code and hence it should have been a [mcve]

Title: Create edit form for Primefaces table

Body:
I want to create edit form for Primefaces table. I tested this code:

<h:form id="form">

        ....................

                <h:outputLabel for="id" value="ID" />

                <h:inputText value="#{systemusers.selectedSystemUser.id}" rendered="#{systemusers.editable}" />
                ........

        <f:facet name="footer">

                <f:ajax render=":form:wd" execute=":form:wd"></f:ajax>

                <f:ajax render=":form" execute=":form"></f:ajax>

        </f:facet>

</h:form>

Managed bean:

@Named
@RequestScoped
public class Systemusers implements Serializable
{
.......
public void editRecord(boolean editable)
    {
        SessionFactory factory = HibernateUtils.getSessionFactory();
        Session session = factory.getCurrentSession();

        try
        {
            session.getTransaction().begin();

            SystemUsersModel obj = new SystemUsersModel();
            obj.setId(selectedSystemUser.getId());
            ..........
            session.update(obj);

            session.getTransaction().commit();

            this.editable = editable;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
    }
......
private boolean editable = false;

    public boolean isEditable()
    {
        return editable;
    }

    public void setEditable(boolean editable)
    {
        this.editable = editable;
    }
}

When I open the Edit form and I click button Edit System User the form disappears. Probably because I render and execute it. How I can execute the form and under it without closing it?

Body:
The example code is bad in multiple ways. Two things stand out:

It is not an [mcve]

<f:ajax render=":form" execute=":form"> is superfluous or might even cause the weird behaviour

OP most likely does not know that (quote from the PrimeFaces showcase , emphasis mine)

CommandButton

CommandButton extends the standard h:commandButton with ajax, partial processing and skinning features.

So the commandBotton is already ajax anabled and does not need to hava a

<f:ajax render=":form" execute=":form">

inside it. This (most likely) makes an the update run twice. One @none (Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes) and one updating the form. The second one most likely does not have any content. But trying (and debugging) will make things clear. If this is not the answer, the reason cannot be seen in the code and hence it should have been a [mcve]


问:
How to detect DOM modification event
I have been trying to get listen to DOM change event for a several hours, however still cannot get it working.

I need to detect events that are showed in Chrome Debug Tools as changes displayed as pink color.

Here is what I've tried

```<code>  function listenForDomModified(node, listener) {
            node.addEventListener("DOMSubtreeModified", listener, false);
            var iframes = node.getElementsByTagName("iframe");
            for (var i = 0, len = iframes.length, doc; i < len; ++i) {
                // Catch and ignore errors caused by iframes from other domains
                try {
                    doc = iframes[i].contentDocument || iframes[i].contentWindow.document;
                    doc.addEventListener("DOMSubtreeModified", listener, false);
                } catch (ex) {}
            }
        }
        var findElements = function () {
            elements.iframeBlock = $(SELECTOR.IFRAME_BLOCK);
        };
        var onIframeChange = function (e) {

            console.log("CHANGE !!!");
            alert("DOM CHANGES");
        };
        var setListeners = function () {
            listenForDomModified(elements.iframeBlock[0],onIframeChange);
            elements.iframeBlock.bind('DOMSubtreeModified', function(e) {
                  if (e.target.innerHTML.length > 0) {
                    alert("ON CHANGE");
                  }
                  alert("ON CHANGE");
            });
            //elements.iframeBlock.change(onIframeChange);
        };
</code>```

Please note, I tried these methods separately.

But still cannot get my function called. However Chrome displays these changes.

I would be grateful for any help.

Thanks

答:
Have you tried</p>

```<code>$(document).on('change', function () { /*code*/ });
</code>```

Title: How to detect DOM modification event

Body:
I have been trying to get listen to DOM change event for a several hours, however still cannot get it working.

I need to detect events that are showed in Chrome Debug Tools as changes displayed as pink color.

Here is what I've tried

  function listenForDomModified(node, listener) {
            node.addEventListener("DOMSubtreeModified", listener, false);
            var iframes = node.getElementsByTagName("iframe");
            for (var i = 0, len = iframes.length, doc; i < len; ++i) {
                // Catch and ignore errors caused by iframes from other domains
                try {
                    doc = iframes[i].contentDocument || iframes[i].contentWindow.document;
                    doc.addEventListener("DOMSubtreeModified", listener, false);
                } catch (ex) {}
            }
        }
        var findElements = function () {
            elements.iframeBlock = $(SELECTOR.IFRAME_BLOCK);
        };
        var onIframeChange = function (e) {

            console.log("CHANGE !!!");
            alert("DOM CHANGES");
        };
        var setListeners = function () {
            listenForDomModified(elements.iframeBlock[0],onIframeChange);
            elements.iframeBlock.bind('DOMSubtreeModified', function(e) {
                  if (e.target.innerHTML.length > 0) {
                    alert("ON CHANGE");
                  }
                  alert("ON CHANGE");
            });
            //elements.iframeBlock.change(onIframeChange);
        };

Please note, I tried these methods separately.

But still cannot get my function called. However Chrome displays these changes.

I would be grateful for any help.

Thanks

Body:
Have you tried

$(document).on('change', function () { /*code*/ });


问:
Used groupby to select most recent data, want to append a column that returns the date of the data
I originally had a dataframe that looked like this:

```<code>                                  industry    population %of rural land
        country       date
        Australia     2017-01-01  NaN         NaN        NaN
                      2016-01-01  24.327571   18.898304  12
                      2015-01-01  25.396251   18.835267  12
                      2014-01-01  27.277007   18.834835  13
        United States 2017-01-01  NaN         NaN        NaN
                      2016-01-01  NaN         19.028231  NaN
                      2015-01-01  20.027274   19.212860  NaN
                      2014-01-01  20.867359   19.379071  NaN
</code>```

I applied the following code which pulled the most recent data for each of the columns for each of the countries and resulted in the following dataset:

```<code>df = df.groupby(level=0).first()

               industry  population  %of rural land
country
Australia      24.327571   18.898304 12
United States  20.027274   19.028231 NaN
</code>```

Is there any way to add a column that shows the year of the data as well? and in the case where the year is different for the same country to return the oldest year of the data in the new data frame? So for Australia, that would be 2016 and US that would be 2015. Ideally, the dataframe would look like this:

```<code>               year      industry  population  %of rural land
country
Australia      2016      24.327571   18.898304 12
United States  2015      20.027274   19.028231 NaN
</code>```

答:
I think you need for first year of non NaNs rows create helper Series by dropna and then :

```<code>s = df.dropna().reset_index(level=1)['date'].dt.year.groupby(level=0).first()
df1 = df.groupby(level=0).first()
df1.insert(0, 'year', df1.rename(s).index)
#alternative
#df1.insert(0, 'year', df1.index.to_series().map(s))
print (df1)
               year   industry  population
country
Australia      2016  24.327571   18.898304
United States  2015  20.027274   19.028231
</code>```

Another solution with add NaNs to date column and last get years by dt.year:

```<code>df1 = (df.reset_index(level=1)
        .assign(date=lambda x: x['date'].where(df.notnull().all(1).values))
        .groupby(level=0).first()
        .assign(date=lambda x: x['date'].dt.year)
        .rename(columns={'date':'year'}))
print (df1)
               year   industry  population
country
Australia      2016  24.327571   18.898304
United States  2015  20.027274   19.028231
</code>```

EDIT:

```<code>def f(x):
    #check NaNs
    m = x.isnull()
    #remove all NaNs columns
    m = m.loc[:, ~m.all()]
    #first index value of non NaNs rows
    m = m[~m.any(1)].index[0][1].year
    return (m)

s = df.groupby(level=0).apply(f)
print (s)
country
Australia        2016
United States    2015
dtype: int64

df1 = df.groupby(level=0).first()
df1.insert(0, 'year', df1.rename(s).index)
#alternative
#df1.insert(0, 'year', df1.index.to_series().map(s))
print (df1)
               year   industry  population  %of rural land
country
Australia      2016  24.327571   18.898304            12.0
United States  2015  20.027274   19.028231             NaN
</code>```

Body:
I originally had a dataframe that looked like this:

                                  industry    population %of rural land
        country       date
        Australia     2017-01-01  NaN         NaN        NaN
                      2016-01-01  24.327571   18.898304  12
                      2015-01-01  25.396251   18.835267  12
                      2014-01-01  27.277007   18.834835  13
        United States 2017-01-01  NaN         NaN        NaN
                      2016-01-01  NaN         19.028231  NaN
                      2015-01-01  20.027274   19.212860  NaN
                      2014-01-01  20.867359   19.379071  NaN

I applied the following code which pulled the most recent data for each of the columns for each of the countries and resulted in the following dataset:

df = df.groupby(level=0).first()

               industry  population  %of rural land
country
Australia      24.327571   18.898304 12
United States  20.027274   19.028231 NaN

Is there any way to add a column that shows the year of the data as well? and in the case where the year is different for the same country to return the oldest year of the data in the new data frame? So for Australia, that would be 2016 and US that would be 2015. Ideally, the dataframe would look like this:

               year      industry  population  %of rural land
country
Australia      2016      24.327571   18.898304 12
United States  2015      20.027274   19.028231 NaN

Body:
I think you need for first year of non NaNs rows create helper Series by dropna and then :

s = df.dropna().reset_index(level=1)['date'].dt.year.groupby(level=0).first()
df1 = df.groupby(level=0).first()
df1.insert(0, 'year', df1.rename(s).index)
#alternative
#df1.insert(0, 'year', df1.index.to_series().map(s))
print (df1)
               year   industry  population
country
Australia      2016  24.327571   18.898304
United States  2015  20.027274   19.028231

Another solution with add NaNs to date column and last get years by dt.year:

df1 = (df.reset_index(level=1)
        .assign(date=lambda x: x['date'].where(df.notnull().all(1).values))
        .groupby(level=0).first()
        .assign(date=lambda x: x['date'].dt.year)
        .rename(columns={'date':'year'}))
print (df1)
               year   industry  population
country
Australia      2016  24.327571   18.898304
United States  2015  20.027274   19.028231

EDIT:

def f(x):
    #check NaNs
    m = x.isnull()
    #remove all NaNs columns
    m = m.loc[:, ~m.all()]
    #first index value of non NaNs rows
    m = m[~m.any(1)].index[0][1].year
    return (m)

s = df.groupby(level=0).apply(f)
print (s)
country
Australia        2016
United States    2015
dtype: int64

df1 = df.groupby(level=0).first()
df1.insert(0, 'year', df1.rename(s).index)
#alternative
#df1.insert(0, 'year', df1.index.to_series().map(s))
print (df1)
               year   industry  population  %of rural land
country
Australia      2016  24.327571   18.898304            12.0
United States  2015  20.027274   19.028231             NaN


问:
Way to represent unknown file size in FTP LIST?
I have an FTP server running on a device which generates a synthetic file. i.e. The file is not actually present on the file system. It is generated on the fly whenever it is requested for download. Its size is not known until it is generated.

Certain FTP clients (e.g. Windows Explorer) are apparently using the info from the FTP LIST command to determine the expected file size after they download it. When I request the download, Windows Explorer is first trying the FTP SIZE extension (RFC 3659), which the server doesn't support. Then it downloads the entire file (I see the whole contents in Wireshark), but it truncates the file to the size that was reported in the LIST.

What is the expected behavior here? Is Windows Explorer acting outside of spec with this optimization / safety measure?

Our current work-around is to show the file size as bigger than it will ever be in the file listing.

Is there a way to represent an unknown file size in an ls -l / FTP LIST? As I read RFC 959, the LIST format is not standardized, but I'm guessing the POSIX ls '-l' format is pretty common, and that Windows Explorer is parsing that.

How should I be handling this situation?

答:
The workaround here for client could be to use wget or 'ftp' command. 'ftp' command example:

open console

ftp user@yourserver

cd to_your_path

get your_filename.

Because neither wget nor 'ftp get command' don't need size to download file.

One more solution could be usage of own ftp server. You can find a lot of whose servers with basic features, gui client support and simple code on scripting language, like php. It's simple to change the code for this feature. I have done the same for one of the projects.


问:
SAS Macro Query
I am having trouble with the following %macro for a regression.

Basically, I want it to run whenever i=j, and i=1 to 12 and j=1 to 12.

```<code>  %macro reg(num=);
    %do i=1 %to #
    %do j=1 %to #
    proc reg data=ccy.eur; *Specify Currency Data Set Here;
    model Ft_leadSt&i = Ft_St&j;
    where &i=&j;
    ods output parameterestimates (persist) =dpara1;
    run;
    %end;
%end;
%mend;
%reg(num=12)
</code>```

The problem is my output seems to stop when i=9 and j=9. I haven't been able to figure out why?

Screen Shot of data

答:
I would rewrite this without the double loop and only 1 PROC REG statement:

```<code>  %macro reg(num=);
    proc reg data=ccy.eur; *Specify Currency Data Set Here;
    ods output parameterestimates (persist) =dpara1;
    var FT_leads1 - FT_leads&n FT_St1 - FT_St&n;
    %do i=1 %to #
       _&i: model Ft_leadSt&i = Ft_St&i;
       run;
    %end;
    quit;
  %mend;
%reg(num=12)
</code>```

Make sure you have those variables in the data set.

Title: SAS Macro Query

Body:
I am having trouble with the following %macro for a regression.

Basically, I want it to run whenever i=j, and i=1 to 12 and j=1 to 12.

  %macro reg(num=);
    %do i=1 %to #
    %do j=1 %to #
    proc reg data=ccy.eur; *Specify Currency Data Set Here;
    model Ft_leadSt&i = Ft_St&j;
    where &i=&j;
    ods output parameterestimates (persist) =dpara1;
    run;
    %end;
%end;
%mend;
%reg(num=12)

The problem is my output seems to stop when i=9 and j=9. I haven't been able to figure out why?

Screen Shot of data

Body:
I would rewrite this without the double loop and only 1 PROC REG statement:

  %macro reg(num=);
    proc reg data=ccy.eur; *Specify Currency Data Set Here;
    ods output parameterestimates (persist) =dpara1;
    var FT_leads1 - FT_leads&n FT_St1 - FT_St&n;
    %do i=1 %to &num;
       _&i: model Ft_leadSt&i = Ft_St&i;
       run;
    %end;
    quit;
  %mend;
%reg(num=12)

Make sure you have those variables in the data set.


问:
Hitting EBS volume limit
I am trying to launch 210 instances of type p2.xlarge. Earlier I am hitting instance limit which I have increased now to 300 but now I am getting  'Client.VolumeLimitExceeded: Volume limit exceeded' error. Can you please help to resolve this issue? Any one knows the

What is Volume limit?

What should I request to increase inorder to run 210 instance (p2.xlarge) and aviod this error.

答:
Your error means: Client.VolumeLimitExceeded: The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your limits.

The AWS Limits page for EBS lists the default limit being 5,000 EBS volumes and 10,000 EBS snapshots. Total storage limit is 20 TB per type (gp2, io12, st1, sc1). Make sure that this is not your issue.

Amazon Elastic Block Store (Amazon EBS) Limits

To request an increase for EBS go to Volume List Increase Request. On the same page your can change the Limit Type for other limit increases.

I would open a support case with Amazon support and ask them to review your requirements to make sure that all your limits are managed for this usage case instead of hitting one limit after the other. Amazon will definitely help you.

Title: Hitting EBS volume limit


问:
Read a file in a fragment and put it in a listview
I have a "Todo.txt" file where i want to read all lines and insert them to my listview. It seems like the listview is not getting any items and the problem is how i read the file in. Any suggestions?

```<code>public class MainFragment extends Fragment {
    ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        // Set title of fragment page
        TextView textView = (TextView) v.findViewById(R.id.titleTextView);
        textView.setText(getArguments().getString("fragmentTitle"));

        ListView listView = (ListView)v.findViewById(R.id.listview);

        arrayListSetup();

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                arrayList
        );

        listView.setAdapter(arrayAdapter);

        return v;
    }

    private void arrayListSetup(){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new MainActivity().FILENAME));
            String line;

            // add line to arraylist
            while((line = br.readLine()) != null){
                arrayList.add(line);
            }
            // close bufferedreader
            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

The MainActivity when clicking the button, it writes the todo-activity to the file:

```<code>addTodoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Get category of to-do
                String category = spinner.getSelectedItem().toString();

                // Get the to-do text what has to be done
                String todo_text = editText.getText().toString();

                // Try to create inputfile
                try {
                    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(todo_text.getBytes());
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });
</code>```

答: The problem was that i didnt call getActivity() before calling openFileInput(),  because a Fragment is not a context!

Body:
I have a "Todo.txt" file where i want to read all lines and insert them to my listview. It seems like the listview is not getting any items and the problem is how i read the file in. Any suggestions?

public class MainFragment extends Fragment {
    ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        // Set title of fragment page
        TextView textView = (TextView) v.findViewById(R.id.titleTextView);
        textView.setText(getArguments().getString("fragmentTitle"));

        ListView listView = (ListView)v.findViewById(R.id.listview);

        arrayListSetup();

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                arrayList
        );

        listView.setAdapter(arrayAdapter);

        return v;
    }

    private void arrayListSetup(){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new MainActivity().FILENAME));
            String line;

            // add line to arraylist
            while((line = br.readLine()) != null){
                arrayList.add(line);
            }
            // close bufferedreader
            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

The MainActivity when clicking the button, it writes the todo-activity to the file:

addTodoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Get category of to-do
                String category = spinner.getSelectedItem().toString();

                // Get the to-do text what has to be done
                String todo_text = editText.getText().toString();

                // Try to create inputfile
                try {
                    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(todo_text.getBytes());
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });


问:
Rails 3 - CanCan error? NameError (uninitialized constant Ability::Invitation):
Error:

```<code>NameError (uninitialized constant Ability::Invitation):
  app/models/ability.rb:72:in `initialize'
  app/controllers/invitations_controller.rb:12:in `new'
  app/controllers/invitations_controller.rb:12:in `current_ability'
  app/middleware/flash_session_cookie_middleware.rb:14:in `call'
</code>```

In CanCan i have:

```<code>can :manage, Invitation
</code>```

in the Invitations Controller:

before_filter :current_ability  # CanCan
  load_and_authorize_resource #CanCan

def current_ability
    @current_ability ||= Ability.new(current_user, nil)
  end

Application's controller:

```<code>#CanCan
def current_ability
    @current_ability ||= Ability.new(current_user, nil) # since no group
end
</code>```

Routes:

```<code>resources :invitations
</code>```

Any thoughts why CanCan isn't happy? thanks

答: Looks like you are trying to reference a class that is not defined. Is there a file at app/models/invitation.rb that defines this Invitation class?

Body:
Error:

NameError (uninitialized constant Ability::Invitation):
  app/models/ability.rb:72:in `initialize'
  app/controllers/invitations_controller.rb:12:in `new'
  app/controllers/invitations_controller.rb:12:in `current_ability'
  app/middleware/flash_session_cookie_middleware.rb:14:in `call'

In CanCan i have:

can :manage, Invitation

in the Invitations Controller:

before_filter :current_ability  # CanCan
  load_and_authorize_resource #CanCan

def current_ability
    @current_ability ||= Ability.new(current_user, nil)
  end

Application's controller:

#CanCan
def current_ability
    @current_ability ||= Ability.new(current_user, nil) # since no group
end

Routes:

resources :invitations

Any thoughts why CanCan isn't happy? thanks


问:
having trouble converting from resource to bitmap in an android test
Iam attempting to convert a resource image to a bitmap to test it in an Instrumentation test in android. originally i had this as a regular test extending testcase. my issue is with this

```<code> protected void setUp()
{
 testbmap=BitmapFactory.decodeResource(getInstrumentation().
 getContext().getResources(), R.drawable.ic_launcher);
}
</code>```

then i test that the bitmap is not null but the test fails.

```<code>public void testnotnull()
{
 assertNotNull(testbmap);
}
</code>```

so iam doing something wrong here i think it could b something to do with the first param in the decoderecource(), maybe iam not pointing to the correct resources? I also tried getApplicationContext.getResources() method but iam not too sure on this one.
can anyone help me?

答:
I solved this problem changing #getContext() which will return Context of instrumentation's package to #getTargetContext() which will return context of target application.

Return a Context for the target application being instrumented.  Note
  that this is often different than the Context of the instrumentation
  code, since the instrumentation code often lives is a different
  package    than that of the application it is running against. See
  getContext to retrieve a Context for the instrumentation code.

Kotlin method:

```<code>@Test
fun bitmapIsNotNull() {
    val context = InstrumentationRegistry.getInstrumentation().targetContext
    val bitmap = BitmapFactory.decodeResource(context.resources, R.raw.any_image)

    Assert.assertNotNull(bitmap)
}
</code>```

Body:
Iam attempting to convert a resource image to a bitmap to test it in an Instrumentation test in android. originally i had this as a regular test extending testcase. my issue is with this

 protected void setUp()
{
 testbmap=BitmapFactory.decodeResource(getInstrumentation().
 getContext().getResources(), R.drawable.ic_launcher);
}

then i test that the bitmap is not null but the test fails.

public void testnotnull()
{
 assertNotNull(testbmap);
}

so iam doing something wrong here i think it could b something to do with the first param in the decoderecource(), maybe iam not pointing to the correct resources? I also tried getApplicationContext.getResources() method but iam not too sure on this one.
can anyone help me?

Body:
I solved this problem changing #getContext() which will return Context of instrumentation's package to #getTargetContext() which will return context of target application.

Return a Context for the target application being instrumented.  Note
  that this is often different than the Context of the instrumentation
  code, since the instrumentation code often lives is a different
  package    than that of the application it is running against. See
  getContext to retrieve a Context for the instrumentation code.

Kotlin method:

@Test
fun bitmapIsNotNull() {
    val context = InstrumentationRegistry.getInstrumentation().targetContext
    val bitmap = BitmapFactory.decodeResource(context.resources, R.raw.any_image)

    Assert.assertNotNull(bitmap)
}