问:
Showing current location in offline mode with gps
Hi I am a bit new to android and I have been wanted to develop an android app which is supposed to show the current location of the user on a map like google map in offline mode. Can I show the location with just GPS and without Internet connection ?  Needless to say that this offline thing is vitally important for me. Any help would be appreciated. Tnx in advance</p>

答:
You can get raw NMEA data from GPS via NmeaListener or better OnNmeaMessageListener (IMHO it more complex), and parse RMC sentence like this:

```<code>public class CustomNmeaListener implements GpsStatus.NmeaListener{

    private GoogleMap mGoogleMap;
    private Marker mMarkerPosition = null;
    private BitmapDescriptor mMarkerMoveDescriptor;
    private BitmapDescriptor mMarkerStopDescriptor;

    public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
        this.mGoogleMap = googleMap;

        mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
        mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        double latitude;
        double longitude;
        float speed;
        float angle;

        // parse NMEA RMC sentence
        // Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
        //   nmea    [0]   [1]  [2]  [3]   [4]   [5]   [6] [7]   [8]   [9]   [10]  [11]
        if (nmea.startsWith("$GPRMC")) {

            String[] nmeaParts = nmea.split(",");

            // if RMC data valid ("active")
            if (nmeaParts[2].equals("A")) {
                latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
                longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
                speed = parseSpeed(nmeaParts[7]);
                angle = parseAngle(nmeaParts[8]);

                // remove marker on "old" position
                if (mMarkerPosition != null) {
                    mMarkerPosition.remove();
                }

                MarkerOptions positionMarkerOptions;

                if (speed > 0) {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerMoveDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(angle);
                } else {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerStopDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(0);
                }
                mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
            }
        }

    }

    static float parseLatitude(String lat, String sign) {
        float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
        latitude +=  Float.parseFloat(lat.substring(0, 2));
        if(sign.startsWith("S")) {
            latitude = -latitude;
        }
        return latitude;
    }

    static float parseLongitude(String lon, String sign) {
        float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
        longitude +=  Float.parseFloat(lon.substring(0, 3));
        if(sign.startsWith("W")) {
            longitude = -longitude;
        }
        return longitude;
    }

    static float parseSpeed(String knots) {
        float speed;
        try {
            speed = Float.parseFloat(knots);
        } catch (Exception e) {
            speed = 0;
        }
        return speed;
    }

    static float parseAngle(String ang) {
        float angle;
        try {
            angle = Float.parseFloat(ang);
        } catch (Exception e) {
            angle = 0;
        }
        return angle;
    }
}
</code>```

and set RMC sentence interval on requestLocationUpdates() call

```<code>try {
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            <your_update_interval>,
            LOCATION_DISTANCE,
            this
    );
 } catch (java.lang.SecurityException ex) {
    Log.d(TAG, "fail to request location update, ignore", ex);
 }
</code>```

And for map service you should use custom solution, because, even for offline maps Google Maps need Internet connection at least for MAPS API KEY check. As first approach you can use simple ImageView with map screenshot.

Body:
You can get raw NMEA data from GPS via NmeaListener or better OnNmeaMessageListener (IMHO it more complex), and parse RMC sentence like this:

public class CustomNmeaListener implements GpsStatus.NmeaListener{

    private GoogleMap mGoogleMap;
    private Marker mMarkerPosition = null;
    private BitmapDescriptor mMarkerMoveDescriptor;
    private BitmapDescriptor mMarkerStopDescriptor;

    public CustomNmeaListener(GoogleMap googleMap, int markerMoveResource, int markerStopResource){
        this.mGoogleMap = googleMap;

        mMarkerMoveDescriptor = BitmapDescriptorFactory.fromResource(markerMoveResource);
        mMarkerStopDescriptor = BitmapDescriptorFactory.fromResource(markerStopResource);
    }

    @Override
    public void onNmeaReceived(long timestamp, String nmea) {
        double latitude;
        double longitude;
        float speed;
        float angle;

        // parse NMEA RMC sentence
        // Example $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A
        //   nmea    [0]   [1]  [2]  [3]   [4]   [5]   [6] [7]   [8]   [9]   [10]  [11]
        if (nmea.startsWith("$GPRMC")) {

            String[] nmeaParts = nmea.split(",");

            // if RMC data valid ("active")
            if (nmeaParts[2].equals("A")) {
                latitude = parseLatitude(nmeaParts[3], nmeaParts[4]);
                longitude = parseLongitude(nmeaParts[5], nmeaParts[6]);
                speed = parseSpeed(nmeaParts[7]);
                angle = parseAngle(nmeaParts[8]);

                // remove marker on "old" position
                if (mMarkerPosition != null) {
                    mMarkerPosition.remove();
                }

                MarkerOptions positionMarkerOptions;

                if (speed > 0) {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerMoveDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(angle);
                } else {
                    positionMarkerOptions = new MarkerOptions()
                            .position(new LatLng(latitude, longitude))
                            .icon(mMarkerStopDescriptor)
                            .anchor(0.5f, 0.5f)
                            .rotation(0);
                }
                mMarkerPosition = mGoogleMap.addMarker(positionMarkerOptions);
            }
        }

    }

    static float parseLatitude(String lat, String sign) {
        float latitude = Float.parseFloat(lat.substring(2)) / 60.0f;
        latitude +=  Float.parseFloat(lat.substring(0, 2));
        if(sign.startsWith("S")) {
            latitude = -latitude;
        }
        return latitude;
    }

    static float parseLongitude(String lon, String sign) {
        float longitude = Float.parseFloat(lon.substring(3)) / 60.0f;
        longitude +=  Float.parseFloat(lon.substring(0, 3));
        if(sign.startsWith("W")) {
            longitude = -longitude;
        }
        return longitude;
    }

    static float parseSpeed(String knots) {
        float speed;
        try {
            speed = Float.parseFloat(knots);
        } catch (Exception e) {
            speed = 0;
        }
        return speed;
    }

    static float parseAngle(String ang) {
        float angle;
        try {
            angle = Float.parseFloat(ang);
        } catch (Exception e) {
            angle = 0;
        }
        return angle;
    }
}

and set RMC sentence interval on requestLocationUpdates() call

try {
    mLocationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            <your_update_interval>,
            LOCATION_DISTANCE,
            this
    );
 } catch (java.lang.SecurityException ex) {
    Log.d(TAG, "fail to request location update, ignore", ex);
 }

And for map service you should use custom solution, because, even for offline maps Google Maps need Internet connection at least for MAPS API KEY check. As first approach you can use simple ImageView with map screenshot.


来源: stackexchange

问:
How to query huge MySQL databases?
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75
</code>```

Users table looks like this:

```<code>user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password
</code>```

To get the purchase history of a user I use a query like this:

```<code>mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");
</code>```

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

```<code>user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)
</code>```

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

```<code>purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75
</code>```

答:
By doing this with your schema, you will break the entity-relationship of your database.

You might want to look into Memcached, NoSQL, and Redis.
These are all tools that will help you improve your query performances, mostly by storing data in the RAM.

For example - run the query once, store it in the Memcache, if the user refresh the page, you get the data from Memcache, not from MySQL, which avoids querying your database a second time.

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: How to query huge MySQL databases?

Body:
I have 2 tables, a purchases table and a users table. Records in the purchases table looks like this:

purchase_id | product_ids | customer_id
---------------------------------------
1           | (99)(34)(2) | 3
2           | (45)(3)(74) | 75

Users table looks like this:

user_id  | email              | password
----------------------------------------
3        | joeShmoe@gmail.com | password
75       | nolaHue@aol.com    | password

To get the purchase history of a user I use a query like this:

mysql_query(" SELECT * FROM purchases WHERE customer_id = '$users_id' ");

The problem is, what will happen when tens of thousands of records are inserted into the purchases table. I feel like this will take a performance toll.

So I was thinking about storing the purchases in an additional field directly in the user's row:

user_id | email              | password  | purchases
------------------------------------------------------
1       | joeShmoe@gmail.com | password  | (99)(34)(2)
2       | nolaHue@aol.com    | password  | (45)(3)(74)

And when I query the user's table for things like username, etc. I can just as easily grab their purchase history using that one query.

Is this a good idea, will it help better performance or will the benefit be insignificant and not worth making the database look messier?

I really want to know what the pros do in these situations, for example how does amazon query it's database for user's purchase history since they have millions of customers. How come there queries don't take hours?

EDIT

Ok, so I guess keeping them separate is the way to go. Now the question is a design one:

Should I keep using the "purchases" table I illustrated earlier. In that design I am separating the product ids of each purchase using parenthesis and using this as the delimiter to tell the ids apart when extracting them via PHP.

Instead should I be storing each product id separately in the "purchases" table so it looks like this?:

purchase_id | product_ids | customer_id
---------------------------------------
1           | 99          | 3
1           | 34          | 3
1           | 2           | 3
2           | 45          | 75
2           | 3           | 75
2           | 74          | 75


问:
Take the mean of values in a list if a duplicate is found
I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on:

```<code>l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]
</code>```

My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be:

```<code>l1 = ['John', 'Bob', 'Stew']
l2 = [2, 4, 7]
</code>```

I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this.

Thank you

答:
Here is a shorter version using dict,</p>

```<code>final_dict = {}
l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

for i in range(len(l1)):
    if final_dict.get(l1[i]) == None:
        final_dict[l1[i]] = l2[i]
    else:
        final_dict[l1[i]] = int((final_dict[l1[i]] + l2[i])/2)

print(final_dict)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 lists which are associated with each other. E.g., here, 'John' is associated with '1', 'Bob' is associated with 4, and so on:

l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

My problem is with the duplicate John. Instead of adding the duplicate John, I want to take the mean of the values associated with the Johns, i.e., 1 and 3, which is (3 + 1)/2 = 2. Therefore, I would like the lists to actually be:

l1 = ['John', 'Bob', 'Stew']
l2 = [2, 4, 7]

I have experimented with some solutions including for-loops and the "contains" function, but can't seem to piece it together. I'm not very experienced with Python, but linked lists sound like they could be used for this.

Thank you

Body:
Here is a shorter version using dict,

final_dict = {}
l1 = ['John', 'Bob', 'Stew', 'John']
l2 = [1, 4, 7, 3]

for i in range(len(l1)):
    if final_dict.get(l1[i]) == None:
        final_dict[l1[i]] = l2[i]
    else:
        final_dict[l1[i]] = int((final_dict[l1[i]] + l2[i])/2)

print(final_dict)


问:
Very simple code, not working
I am trying to elicit two responses depending on user input, and can't get it to work. It just keeps printing "Correct, seems you're smarter than I thought...". Any help would be much appreciated, thank you

```<code>print ("Welcome to UTOPIA")

river= ""
while not river:
    river = input ("\n\n\n\nYou come across a raging river, what do you do? ")

if river == "swim" or "swim through it":
    print ("Correct, seems you're smarter than I thought...")

elif river == "walk through it" or "walk through":
    print ("You cant walk through such a big river... silly!")

else:
    print ("Well, sensible suggestions now...")
</code>```

答:
All non-empty strings are (unfortunately) True in Python.

That means that this will always be True:

```<code>if something or "string":
</code>```

Because or "string" will always be True.

Title: Very simple code, not working

Body:
I am trying to elicit two responses depending on user input, and can't get it to work. It just keeps printing "Correct, seems you're smarter than I thought...". Any help would be much appreciated, thank you

print ("Welcome to UTOPIA")

river= ""
while not river:
    river = input ("\n\n\n\nYou come across a raging river, what do you do? ")

if river == "swim" or "swim through it":
    print ("Correct, seems you're smarter than I thought...")

elif river == "walk through it" or "walk through":
    print ("You cant walk through such a big river... silly!")

else:
    print ("Well, sensible suggestions now...")

Body:
All non-empty strings are (unfortunately) True in Python.

That means that this will always be True:

if something or "string":

Because or "string" will always be True.


问:
c# show/hide controls depending on user properties
In my application each user has one clientid but multiple roles.

For example user John has clientid=1 and roles=userx, userz

What I want to achieve is to hide or show controls of my application regarding the user's clientid and role

I have this array in my DB:

```<code>[dbo].[MyMenus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [controlid] [nvarchar](500) NULL,
    [clientid_available] [nvarchar](50) NULL,
    [clientid_hidden] [nvarchar](50) NULL,
    [role_available] [nvarchar](500) NULL,
    [role_hidden] [nvarchar](500) NULL
</code>```

Where clientid_available, clientid_hidden, role_available, role_hidden contain values separated by comma. If a control has clientid_available then clientid_hidden is null and vice versa. Same thing for role_available and role_hidden

Example: 0 | Control1 | 0,1 | null | userx | null Which means that Control will be visible to users with clientid 0,1 and users in userx role

Here is my code until now:

```<code>var hiddenControls = from c in dc.MyMenus
                                 where c.clientid_hidden != null || c.role_hidden != null
                                 select c;

            var visibleControls = from c in dc.MyMenus
                                  where c.clientid_available != null || c.clientid_available != null
                                  select c;

foreach (var c in hiddenControls)
                {
                    if (c.clientid_hidden != null)
                    {
                        if (c.clientid_hidden.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

foreach (var c in visibleControls)
                {
                    if (c.clientid_available != null)
                    {
                        if (c.clientid_available.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }
</code>```

But I dont know the logic for the role handling. Because role_available, role_hidden can have multiple values separated by ',' and current user can have multiple roles Roles.GetRolesForUser(HttpContext.Current.User.ToString())

答:
Well I used this code using Intersect:

```<code>string[] roles = Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name);

if (c.role_hidden.Split(',').Intersect(roles).Any())
                    {
                        (this.Page.FindControl(c.controlid)).Visible = false;
</code>```

Body:
In my application each user has one clientid but multiple roles.

For example user John has clientid=1 and roles=userx, userz

What I want to achieve is to hide or show controls of my application regarding the user's clientid and role

I have this array in my DB:

[dbo].[MyMenus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [controlid] [nvarchar](500) NULL,
    [clientid_available] [nvarchar](50) NULL,
    [clientid_hidden] [nvarchar](50) NULL,
    [role_available] [nvarchar](500) NULL,
    [role_hidden] [nvarchar](500) NULL

Where clientid_available, clientid_hidden, role_available, role_hidden contain values separated by comma. If a control has clientid_available then clientid_hidden is null and vice versa. Same thing for role_available and role_hidden

Example: 0 | Control1 | 0,1 | null | userx | null Which means that Control will be visible to users with clientid 0,1 and users in userx role

Here is my code until now:

var hiddenControls = from c in dc.MyMenus
                                 where c.clientid_hidden != null || c.role_hidden != null
                                 select c;

            var visibleControls = from c in dc.MyMenus
                                  where c.clientid_available != null || c.clientid_available != null
                                  select c;

foreach (var c in hiddenControls)
                {
                    if (c.clientid_hidden != null)
                    {
                        if (c.clientid_hidden.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

foreach (var c in visibleControls)
                {
                    if (c.clientid_available != null)
                    {
                        if (c.clientid_available.Contains(clientId.ToString()))
                            (this.Page.FindControl(c.controlid)).Visible = true;
                        else
                            (this.Page.FindControl(c.controlid)).Visible = false;
                    }
                    //Code for role handling
                }

But I dont know the logic for the role handling. Because role_available, role_hidden can have multiple values separated by ',' and current user can have multiple roles Roles.GetRolesForUser(HttpContext.Current.User.ToString())

Body:
Well I used this code using Intersect:

string[] roles = Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name);

if (c.role_hidden.Split(',').Intersect(roles).Any())
                    {
                        (this.Page.FindControl(c.controlid)).Visible = false;


问:
Excel formula to get number of days between two dates in months with precision
what's the formula to get number of days between two dates in months with days precision.

For example: the number of days between 01-01-2017 & 14-02-2017 these two dates is 45 days. (31 days + 14 days - including both) So I'm expecting 1 month 14 days as output. So the format should be 1.14 (1 month 14 days)

Edit:
There is no assumption of 30 days in a month. I'm expecting exact calendar difference.

Body:
Try this:

=DATEDIF(A1,B1,"m") & "." & B1-DATE(YEAR(B1),MONTH(B1)-IF(DAY(A1)>DAY(B1),1,0),DAY(A1))+1


问:
Split collection into multiple collections
I want to create new list of list on basis of a single list.
I have a list like

```<code>public class OfficeLocator
{
    public String id{ get; set; }
    public string Geography{ get; set; }
    public string Country{ get; set; }
    public string State{ get; set; }
    public string OfficeName{ get; set; }
}
</code>```

I am trying to prepare an tree structured list

```<code>GeographyName="Asia",
{
   Country = "China",
   {
      State = "Hunan",
        {
            {
                OfficeId = "1",
                OfficeName = "Office 1"
            },
            {
                OfficeId = "2",
                OfficeName = "Office 2"
            }
        },
      State = "Hubei"
        {
            {
                OfficeId = "3",
                OfficeName = "Office 3"
            }
        }
    },
    Country = "India",
    {
      State = "Maharashtra",
        {
            {
                OfficeId = "4",
                OfficeName = "Office 4"
            },
            {
                OfficeId = "5",
                OfficeName = "Office 5"
            }
        },
      State = "Punjab"
        {
            {
                OfficeId = "6",
                OfficeName = "Office 6"
            }
        }
    },
},
GeographyName="Europe",
{
   Country = "UK",
   {
      State = "York",
        {
            {
                OfficeId = "7",
                OfficeName = "Office 7"
            },
            {
                OfficeId = "8",
                OfficeName = "Office 8"
            }
        }
    }
}
</code>```

I tried using some group by on Geography and Country.
But I am not getting the required output.

I can use looping logic to get the result, but I want to avoid it and try something with linq.

答:
you could achieve the same result as Tim mentioned
but instead of using the method syntax,
rely on the query syntax for debatable better readability

```<code>var projection = from location in locations
                 group location by location.Geography into geographies
                 select new
                 {
                    Geography = geographies.Key,
                    Countries = from geography in geographies
                                group geography by geography.Country into countries
                                select new
                                {
                                    Country = countries.Key,
                                    States = from country in countries
                                            group country by country.State into states
                                            select new
                                            {
                                                State = states.Key,
                                                Offices = from state in states
                                                        select new
                                                        {
                                                            Id = state.Id,
                                                            Office = state.Office,
                                                        }
                                             }
                                }
                };
</code>```

and the end result would look like this

Body:
I want to create new list of list on basis of a single list.
I have a list like

public class OfficeLocator
{
    public String id{ get; set; }
    public string Geography{ get; set; }
    public string Country{ get; set; }
    public string State{ get; set; }
    public string OfficeName{ get; set; }
}

I am trying to prepare an tree structured list

GeographyName="Asia",
{
   Country = "China",
   {
      State = "Hunan",
        {
            {
                OfficeId = "1",
                OfficeName = "Office 1"
            },
            {
                OfficeId = "2",
                OfficeName = "Office 2"
            }
        },
      State = "Hubei"
        {
            {
                OfficeId = "3",
                OfficeName = "Office 3"
            }
        }
    },
    Country = "India",
    {
      State = "Maharashtra",
        {
            {
                OfficeId = "4",
                OfficeName = "Office 4"
            },
            {
                OfficeId = "5",
                OfficeName = "Office 5"
            }
        },
      State = "Punjab"
        {
            {
                OfficeId = "6",
                OfficeName = "Office 6"
            }
        }
    },
},
GeographyName="Europe",
{
   Country = "UK",
   {
      State = "York",
        {
            {
                OfficeId = "7",
                OfficeName = "Office 7"
            },
            {
                OfficeId = "8",
                OfficeName = "Office 8"
            }
        }
    }
}

I tried using some group by on Geography and Country.
But I am not getting the required output.

I can use looping logic to get the result, but I want to avoid it and try something with linq.

Body:
you could achieve the same result as Tim mentioned
but instead of using the method syntax,
rely on the query syntax for debatable better readability

var projection = from location in locations
                 group location by location.Geography into geographies
                 select new
                 {
                    Geography = geographies.Key,
                    Countries = from geography in geographies
                                group geography by geography.Country into countries
                                select new
                                {
                                    Country = countries.Key,
                                    States = from country in countries
                                            group country by country.State into states
                                            select new
                                            {
                                                State = states.Key,
                                                Offices = from state in states
                                                        select new
                                                        {
                                                            Id = state.Id,
                                                            Office = state.Office,
                                                        }
                                             }
                                }
                };

and the end result would look like this


问:
How to use vue.js with Nginx?

I want to build a single page application with Vue.js using Nginx as my webserver and a my own Dropwiward REST API. Moreover I use Axios to call my REST request.

My nginx config looks like

```<code>server {
    listen       80;
    server_name  localhost;

    location / {
        root     path/to/vue.js/Project;
        index    index.html index.htm;
        include  /etc/nginx/mime.types;
    }
    location /api/ {
        rewrite ^/api^/ /$1 break;
        proxy_pass http://localhost:8080/;
    }
}
</code>```

Currently I can just call my localhost/api/path/to/rescource to get the the information from the backend.

I  build the Front end with HTML and javascript(vue.js) which has worked so far. However when I want to build a single page application most tutorials mention node.js. How can I use Nginx instead?

答:
Add the following code to your Nginx Config, as detailed in the VueRouter docs, here:

```<code>location / {
  try_files $uri $uri/ /index.html;
}
</code>```

Also, you need to enable history mode on VueRouter:

```<code>const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use vue.js with Nginx?

Body:
I want to build a single page application with Vue.js using Nginx as my webserver and a my own Dropwiward REST API. Moreover I use Axios to call my REST request.

My nginx config looks like

server {
    listen       80;
    server_name  localhost;

    location / {
        root     path/to/vue.js/Project;
        index    index.html index.htm;
        include  /etc/nginx/mime.types;
    }
    location /api/ {
        rewrite ^/api^/ /$1 break;
        proxy_pass http://localhost:8080/;
    }
}

Currently I can just call my localhost/api/path/to/rescource to get the the information from the backend.

I  build the Front end with HTML and javascript(vue.js) which has worked so far. However when I want to build a single page application most tutorials mention node.js. How can I use Nginx instead?

Body:
Add the following code to your Nginx Config, as detailed in the VueRouter docs, here:

location / {
  try_files $uri $uri/ /index.html;
}

Also, you need to enable history mode on VueRouter:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})


问:
How to change font to Calibri in PDF using iTextsharp for VB.NET
I am trying to change the font in a PDF file while using VB.net and itextsharp.
I think I am allmost there but I am failing at declaring  the right things.
The code I got looks ok but I get an error.

```<code>Dim FontColour As VariantType = New BaseColor(35, 31, 32)
Dim Calibri8 As VariantType = FontFactory.GetFont("Calibri", 8, FontColour)
</code>```

The errors I get are the following.

Severity    Code    Description Project File    Line    Suppression State
Error   BC30311 Value of type 'BaseColor' cannot be converted to 'VariantType'. J   C:\Users\Jeffrey\Documents\Visual Studio 2013\Projects\J\J\UniFormulieren\Offerte\OfferteUniverseel.vb  61  Active

Severity    Code    Description Project File    Line    Suppression State
Error   BC30311 Value of type 'Font' cannot be converted to 'VariantType'.  J   C:\Users\Jeffrey\Documents\Visual Studio 2013\Projects\J\J\UniFormulieren\Offerte\OfferteUniverseel.vb  62  Active

I also tried using another method as below.

```<code>Dim bftimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim times As New Font(bftimes, 10)
</code>```

This way I could introduce "Times new roman" but not Calibri.
The code above would only let met add Times new roman, Courier and Helvetica.

I am using Microsoft Visual studio 2017 with VB.NET and iTextSharp.
My C# is not that great, but it helped me get this far in VB.net :)

Edit:

The first solution is something I tried using this answer from Nalan M.
https://stackoverflow.com/a/29641544/9056174

Edit2:

SOLUTION

Thank you for your help ! I was so hammering on that varianttype that I was blind for another option.

Made the follow adjustments and indeed it worked like a charm!

```<code>    Dim FontColour As BaseColor = New BaseColor(35, 31, 32)
    Dim Calibri8 As Font = FontFactory.GetFont("Calibri", 8, FontColour)
</code>```

Thank you guys for your help. ( Still don't get why I didn't thought of it myself, using the C# to VB.net converter sometimes makes you crazy)

答:
The error messages

Value of type 'BaseColor' cannot be converted to 'VariantType'

and

Value of type 'Font' cannot be converted to 'VariantType'

indicate what the issue is: The BaseColor and Font instances cannot be converted to a VariantType.

Thus, one has to assign them to variables of a different type. Fortunately there are natural alternatives: Let's take the known actual types BaseColor and Font!

```<code>Dim FontColour As BaseColor = New BaseColor(35, 31, 32)
Dim Calibri8 As Font = FontFactory.GetFont("Calibri", 8, FontColour)
</code>```

Body:
I am trying to change the font in a PDF file while using VB.net and itextsharp.
I think I am allmost there but I am failing at declaring  the right things.
The code I got looks ok but I get an error.

Dim FontColour As VariantType = New BaseColor(35, 31, 32)
Dim Calibri8 As VariantType = FontFactory.GetFont("Calibri", 8, FontColour)

The errors I get are the following.

Severity    Code    Description Project File    Line    Suppression State
Error   BC30311 Value of type 'BaseColor' cannot be converted to 'VariantType'. J   C:\Users\Jeffrey\Documents\Visual Studio 2013\Projects\J\J\UniFormulieren\Offerte\OfferteUniverseel.vb  61  Active

Severity    Code    Description Project File    Line    Suppression State
Error   BC30311 Value of type 'Font' cannot be converted to 'VariantType'.  J   C:\Users\Jeffrey\Documents\Visual Studio 2013\Projects\J\J\UniFormulieren\Offerte\OfferteUniverseel.vb  62  Active

I also tried using another method as below.

Dim bftimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim times As New Font(bftimes, 10)

This way I could introduce "Times new roman" but not Calibri.
The code above would only let met add Times new roman, Courier and Helvetica.

I am using Microsoft Visual studio 2017 with VB.NET and iTextSharp.
My C# is not that great, but it helped me get this far in VB.net :)

Edit:

The first solution is something I tried using this answer from Nalan M.
https://stackoverflow.com/a/29641544/9056174

Edit2:

SOLUTION

Thank you for your help ! I was so hammering on that varianttype that I was blind for another option.

Made the follow adjustments and indeed it worked like a charm!

    Dim FontColour As BaseColor = New BaseColor(35, 31, 32)
    Dim Calibri8 As Font = FontFactory.GetFont("Calibri", 8, FontColour)

Thank you guys for your help. ( Still don't get why I didn't thought of it myself, using the C# to VB.net converter sometimes makes you crazy)

Body:
The error messages

Value of type 'BaseColor' cannot be converted to 'VariantType'

and

Value of type 'Font' cannot be converted to 'VariantType'

indicate what the issue is: The BaseColor and Font instances cannot be converted to a VariantType.

Thus, one has to assign them to variables of a different type. Fortunately there are natural alternatives: Let's take the known actual types BaseColor and Font!

Dim FontColour As BaseColor = New BaseColor(35, 31, 32)
Dim Calibri8 As Font = FontFactory.GetFont("Calibri", 8, FontColour)


问:
Why does C++ not have a const constructor?
(Edit: Heavy change because previous example was flawed, which may make some answers/comments seem odd)

This might be an overly contrived, but the following is legal because of lack of const constructor:

```<code>class Cheater
{
public:
    Cheater(int avalue)
       : cheaterPtr(this) //conceptually odd legality in const Cheater ctor
       , value(avalue)
    {}

    Cheater& getCheaterPtr() const {return *cheaterPtr;}
    int value;

private:
    Cheater * cheaterPtr;
};

int main()
{
    const Cheater cheater(7); //Initialize the value to 7

    cheater.value                 = 4;    //good, illegal
    cheater.getCheaterPtr().value = 4;    //oops, legal

    return 0;
}
</code>```

It seems like providing a const constructor a thing would be as easy technically as const methods, and be analogous to a const overload.

Note: I'm not looking for 'Image( const Data & data ) const' but rather 'const Image( const Data & data) const'

So:

Why is the const constructor absent in C++?

Here's some related material for context:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0798.htm

How to deal with initialization of non-const reference member in const object?

C++, Classes, Const, and strange syntax

答:
In my opinion, the fact of that the ctors haven't return-type specification is what fails here. Any other imaginable syntax like for example

```<code>class A
{
    const A& ctor(...);
}
</code>```

would be, imho, very valuable. For example, imagine such a situation of calling a method with prototype

```<code>void my_method(const my_own_string_class& z);
</code>```

If my_own_string_class holds a ctor from char*, the compiler could choose
this ctor, but as this ctor is not allowed to return a const object, it need to allocate and copy... If const return type were allowed, one could do

```<code>class my_own_string_class
{
    char *_ptr;
    public:
    const my_own_string_class& ctor(char *txt)
    : _ptr(txt)
    { return *this;}
 }
</code>```

provided that this special construct be restricted to the creation of temporal instances. (And dtor's must be mutable ;) ).

Body:
(Edit: Heavy change because previous example was flawed, which may make some answers/comments seem odd)

This might be an overly contrived, but the following is legal because of lack of const constructor:

class Cheater
{
public:
    Cheater(int avalue)
       : cheaterPtr(this) //conceptually odd legality in const Cheater ctor
       , value(avalue)
    {}

    Cheater& getCheaterPtr() const {return *cheaterPtr;}
    int value;

private:
    Cheater * cheaterPtr;
};

int main()
{
    const Cheater cheater(7); //Initialize the value to 7

    cheater.value                 = 4;    //good, illegal
    cheater.getCheaterPtr().value = 4;    //oops, legal

    return 0;
}

It seems like providing a const constructor a thing would be as easy technically as const methods, and be analogous to a const overload.

Note: I'm not looking for 'Image( const Data & data ) const' but rather 'const Image( const Data & data) const'

So:

Why is the const constructor absent in C++?

Here's some related material for context:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1995/N0798.htm

How to deal with initialization of non-const reference member in const object?

C++, Classes, Const, and strange syntax

Body:
In my opinion, the fact of that the ctors haven't return-type specification is what fails here. Any other imaginable syntax like for example

class A
{
    const A& ctor(...);
}

would be, imho, very valuable. For example, imagine such a situation of calling a method with prototype

void my_method(const my_own_string_class& z);

If my_own_string_class holds a ctor from char*, the compiler could choose
this ctor, but as this ctor is not allowed to return a const object, it need to allocate and copy... If const return type were allowed, one could do

class my_own_string_class
{
    char *_ptr;
    public:
    const my_own_string_class& ctor(char *txt)
    : _ptr(txt)
    { return *this;}
 }

provided that this special construct be restricted to the creation of temporal instances. (And dtor's must be mutable ;) ).


问:
How to get dom element value in the page using jquery
Let say I have two fields with id "name" and "address". I want to show the actual value in the div message when I show it to user. And I did

```<code><input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div style="visibility:hidden">
    <div>Your name is $(name)</div>
    <div>Your address is $(address)</div>
</div>
</code>```

I tried

```<code><div style="visibility:hidden">
    <div>Your name is <script>$("input[id=name]").val()</script></div>
    <div>Your address is <script>$("input[id=address]").val())</script></div>
</div>
</code>```

I am getting empty name and address.

Questtion is how can I fix it, is there any better approach? like

```<code><div style="visibility:hidden">
    <div>Your name is <script>GetValue(name)</script></div>
    <div>Your address is <script>GetValue(address)</</script></div>
</div>
</code>```

and use jquery to replace values?

答:
Give the two result divs ids, and so the enclosing (hidden) div:</p>

```<code><input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div id="result" style="visibility:hidden">
    <div id="result_name"></div>
    <div id="result_address"></div>
</div>

<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('#name').change(function() {
        jQuery('#result_name').text('Your name is ' + jQuery(this).val());
    });

    jQuery('#address').change(function() {
        jQuery('#result_address').text('Your address is ' + jQuery(this).val());
    });

    jQuery('#result').css('display', 'block');
});
</script>
</code>```

Body:
Let say I have two fields with id "name" and "address". I want to show the actual value in the div message when I show it to user. And I did

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

Your name is $(name)

Your address is $(address)

I tried

Your name is

Your address is

I am getting empty name and address.

Questtion is how can I fix it, is there any better approach? like

Your name is

Your address is

and use jquery to replace values?

Body:
Give the two result divs ids, and so the enclosing (hidden) div:

<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />

<div id="result" style="visibility:hidden">
    <div id="result_name"></div>
    <div id="result_address"></div>
</div>

<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('#name').change(function() {
        jQuery('#result_name').text('Your name is ' + jQuery(this).val());
    });

    jQuery('#address').change(function() {
        jQuery('#result_address').text('Your address is ' + jQuery(this).val());
    });

    jQuery('#result').css('display', 'block');
});
</script>


问:
rollback transaction error rails from google geocoding api
I am trying to create a review form in my rails app but when i click on the submit button,  the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:

```<code>Google API error: over query limit.
   (0.1ms)  rollback transaction
</code>```

Update

I am not only getting the Google API error. sometimes i get this error and other time i only get  rollback transaction only.

This is the Reviews Controller:

```<code>class ReviewsController < ApplicationController

  # check if logged in
  before_action :check_login, except: [:index, :show]

  def index
    # this is our list page for our reviews
    @price = params[:price]
    @cuisine = params[:cuisine]
    @location = params[:location]

    # start with all the reviews
    @reviews = Review.all

    # filtering by price
    if @price.present?
      @reviews = @reviews.where(price: @price)
    end

    # filter by cuisine
    if @cuisine.present?
      @reviews = @reviews.where(cuisine: @cuisine)
    end

    # search near the location
    if @location.present?
      @reviews = @reviews.near(@location)
    end

  end

  def new
    # the form for adding a new review
    @review = Review.new
  end

  def create
    # take info from the form and add it to the model
    @review = Review.new(form_params)

    # and then associate it with a user
    @review.user = @current_user

    # we want to check if the model can be saved
    # if it is, we're go the home page again
    # if it isn't, show the new form
    if @review.save
      flash[:succces] = "Your review was posted!"

      redirect_to root_path
    else
      # show the view for new.html.erb
      render "new"
    end

  end

  def show
    # individual review page
    @review = Review.find(params[:id])
  end

  def destroy
    # find the individual review
    @review = Review.find(params[:id])

    # destroy if they have access
    if @review.user == @current_user
      @review.destroy
    end

    # redirect to the home page
    redirect_to root_path
  end

  def edit
    # find the individual review (to edit)
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    elsif @review.created_at < 4.hours.ago
      redirect_to review_path(@review)
    end
  end

  def update
    # find the individual review
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    else
      # update with the new info from the form
      if @review.update(form_params)

        # redirect somewhere new
        redirect_to review_path(@review)
      else
        render "edit"
      end
    end
  end

  def form_params
    params.require(:review).permit(:title, :restaurant, :body, :score,
      :ambiance, :cuisine, :price, :address)
  end

end
</code>```

This is the  Review form page:

```<code><%= simple_form_for @review do |f| %>
  <%= f.input :title %>
  <%= f.input :restaurant %>
  <%= f.input :address %>
  <%= f.input :body %>
  <%= f.input :cuisine %>
  <%= f.input :price %>
  <%= f.input :score %>
  <%= f.input :ambiance %>

  <%= f.button :submit %>
<% end %>
</code>```

The Review Model

```<code>class Review < ApplicationRecord

  # add an association that has a 1-to-many relationship
  has_many :comments
  has_many :bookmarks

  # add an association to the user
  belongs_to :user

  geocoded_by :address
  after_validation :geocode

  validates :title, presence: true
  validates :body, length: { minimum: 10 }
  validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
  validates :restaurant, presence: true
  validates :address, presence: true

  def to_param
    id.to_s + "-" + title.parameterize
  end

end
</code>```

This is My Schema file

```<code>  create_table "reviews", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.integer "score"
    t.string "restaurant"
    t.integer "price"
    t.string "cuisine"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "phone_number"
    t.string "ambiance"
    t.text "address"
    t.float "latitude"
    t.float "longitude"
    t.integer "user_id"
  end
</code>```

答:
You have two problems:

you are going over Google's Geocoding API quota as evidenced by the error message "over query limit"

Most likely because of that, your model cannot be saved is rolled back. The geocoding API call fails, it doesn't save.

I would check the Google API Console and see if you have actually hit their quota (possible if you're running multiple tests and you're on their free tier of service). If you have not hit the limit, file a support request with Google API.

Body:
I am trying to create a review form in my rails app but when i click on the submit button,  the form cannot be submitted.When i lookup the error in the terminal and i get this error. i searched the error but couldn't find any solution. did anyone had this issue before?:

Google API error: over query limit.
   (0.1ms)  rollback transaction

Update

I am not only getting the Google API error. sometimes i get this error and other time i only get  rollback transaction only.

This is the Reviews Controller:

class ReviewsController < ApplicationController

  # check if logged in
  before_action :check_login, except: [:index, :show]

  def index
    # this is our list page for our reviews
    @price = params[:price]
    @cuisine = params[:cuisine]
    @location = params[:location]

    # start with all the reviews
    @reviews = Review.all

    # filtering by price
    if @price.present?
      @reviews = @reviews.where(price: @price)
    end

    # filter by cuisine
    if @cuisine.present?
      @reviews = @reviews.where(cuisine: @cuisine)
    end

    # search near the location
    if @location.present?
      @reviews = @reviews.near(@location)
    end

  end

  def new
    # the form for adding a new review
    @review = Review.new
  end

  def create
    # take info from the form and add it to the model
    @review = Review.new(form_params)

    # and then associate it with a user
    @review.user = @current_user

    # we want to check if the model can be saved
    # if it is, we're go the home page again
    # if it isn't, show the new form
    if @review.save
      flash[:succces] = "Your review was posted!"

      redirect_to root_path
    else
      # show the view for new.html.erb
      render "new"
    end

  end

  def show
    # individual review page
    @review = Review.find(params[:id])
  end

  def destroy
    # find the individual review
    @review = Review.find(params[:id])

    # destroy if they have access
    if @review.user == @current_user
      @review.destroy
    end

    # redirect to the home page
    redirect_to root_path
  end

  def edit
    # find the individual review (to edit)
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    elsif @review.created_at < 4.hours.ago
      redirect_to review_path(@review)
    end
  end

  def update
    # find the individual review
    @review = Review.find(params[:id])

    if @review.user != @current_user
      redirect_to root_path
    else
      # update with the new info from the form
      if @review.update(form_params)

        # redirect somewhere new
        redirect_to review_path(@review)
      else
        render "edit"
      end
    end
  end

  def form_params
    params.require(:review).permit(:title, :restaurant, :body, :score,
      :ambiance, :cuisine, :price, :address)
  end

end

This is the  Review form page:

<%= simple_form_for @review do |f| %>
  <%= f.input :title %>
  <%= f.input :restaurant %>
  <%= f.input :address %>
  <%= f.input :body %>
  <%= f.input :cuisine %>
  <%= f.input :price %>
  <%= f.input :score %>
  <%= f.input :ambiance %>

  <%= f.button :submit %>
<% end %>

The Review Model

class Review < ApplicationRecord

  # add an association that has a 1-to-many relationship
  has_many :comments
  has_many :bookmarks

  # add an association to the user
  belongs_to :user

  geocoded_by :address
  after_validation :geocode

  validates :title, presence: true
  validates :body, length: { minimum: 10 }
  validates :score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 10 }
  validates :restaurant, presence: true
  validates :address, presence: true

  def to_param
    id.to_s + "-" + title.parameterize
  end

end

This is My Schema file

  create_table "reviews", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.integer "score"
    t.string "restaurant"
    t.integer "price"
    t.string "cuisine"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "phone_number"
    t.string "ambiance"
    t.text "address"
    t.float "latitude"
    t.float "longitude"
    t.integer "user_id"
  end


问:
Pandas - Find increasing trend in a row of different columns
I have a dataset of milk production in India. I am trying to get the list of 5 states(if present) in which the total Milk Production increased in last 3 years through Pandas.

```<code>State        Total10-11 Total11-12  Total13-14  Total14-15  Total15-16
Andhra Pradesh    11204      12088       13007         9656      10817
Arunachal Pradesh    28         22          43           46         50
Assam               790        797         814          829        844
Bihar              6517       6643        7197         7775       8289
Chhattisgarh       1030       1118        1208         1232       1278
Goa                  60         60          68           66         54
Gujarat            9322       4089       11112        11690      12262
Haryana            6268       6661        7442         7902       8381
Himachal Pradesh   1102       1120        1151         1173       1283
</code>```

Expected output:

```<code>State
Assam
Bihar
Chhattisgarh
Haryana
Himachal Pradesh
</code>```

I want to find the states which have an increasing trend in their milk production each year. The Milk production should not have decreased in the consequent years compared to the previous years. the expected output states have the production in increasing order and there is no dip even once in their production. I am kind of stuck with this one, I tried a few methods but they are not close to the right answer. What's the solution ? Thanks in advance.

答:
If you are looking for the difference is always increasing you can use diff > 0 and cumsum i.e

```<code>df = df.set_index("State/UT Name")

temp = (df.T.diff() > 0).cumsum()
# Values will increment if the difference between past and present is positive
State/UT Name  Andhra Pradesh  Arunachal Pradesh  Assam  Bihar  Chhattisgarh  \
Total10-11                  0                  0      0      0             0
Total11-12                  1                  0      1      1             1
Total13-14                  2                  1      2      2             2
Total14-15                  2                  2      3      3             3
Total15-16                  3                  3      4      4             4

State/UT Name  Goa  Gujarat  Haryana  Himachal Pradesh
Total10-11       0        0        0                 0
Total11-12       0        0        1                 1
Total13-14       1        1        2                 2
Total14-15       1        2        3                 3
Total15-16       1        3        4                 4

# The one with max sum is the one that kept increasing over time
temp.sum().nlargest(10)

State/UT Name
Assam                10
Bihar                10
Chhattisgarh         10
Haryana              10
Himachal Pradesh     10
Andhra Pradesh        8
Arunachal Pradesh     6
Gujarat               6
Goa                   3
</code>```

If you want the state names then

```<code>states = temp.sum().nlargest(5).index.tolist()

['Assam', 'Bihar', 'Chhattisgarh', 'Haryana', 'Himachal_Pradesh']
</code>```

Body:
I have a dataset of milk production in India. I am trying to get the list of 5 states(if present) in which the total Milk Production increased in last 3 years through Pandas.

State        Total10-11 Total11-12  Total13-14  Total14-15  Total15-16
Andhra Pradesh    11204      12088       13007         9656      10817
Arunachal Pradesh    28         22          43           46         50
Assam               790        797         814          829        844
Bihar              6517       6643        7197         7775       8289
Chhattisgarh       1030       1118        1208         1232       1278
Goa                  60         60          68           66         54
Gujarat            9322       4089       11112        11690      12262
Haryana            6268       6661        7442         7902       8381
Himachal Pradesh   1102       1120        1151         1173       1283

Expected output:

State
Assam
Bihar
Chhattisgarh
Haryana
Himachal Pradesh

I want to find the states which have an increasing trend in their milk production each year. The Milk production should not have decreased in the consequent years compared to the previous years. the expected output states have the production in increasing order and there is no dip even once in their production. I am kind of stuck with this one, I tried a few methods but they are not close to the right answer. What's the solution ? Thanks in advance.

Body:
If you are looking for the difference is always increasing you can use diff > 0 and cumsum i.e

df = df.set_index("State/UT Name")

temp = (df.T.diff() > 0).cumsum()
# Values will increment if the difference between past and present is positive
State/UT Name  Andhra Pradesh  Arunachal Pradesh  Assam  Bihar  Chhattisgarh  \
Total10-11                  0                  0      0      0             0
Total11-12                  1                  0      1      1             1
Total13-14                  2                  1      2      2             2
Total14-15                  2                  2      3      3             3
Total15-16                  3                  3      4      4             4

State/UT Name  Goa  Gujarat  Haryana  Himachal Pradesh
Total10-11       0        0        0                 0
Total11-12       0        0        1                 1
Total13-14       1        1        2                 2
Total14-15       1        2        3                 3
Total15-16       1        3        4                 4

# The one with max sum is the one that kept increasing over time
temp.sum().nlargest(10)

State/UT Name
Assam                10
Bihar                10
Chhattisgarh         10
Haryana              10
Himachal Pradesh     10
Andhra Pradesh        8
Arunachal Pradesh     6
Gujarat               6
Goa                   3

If you want the state names then

states = temp.sum().nlargest(5).index.tolist()

['Assam', 'Bihar', 'Chhattisgarh', 'Haryana', 'Himachal_Pradesh']


问:
TypeORM: auto generated UUID in PostgreSQL
I am writing an REST API and for data access I am using typeorm, I have used this successfully but I would like to have a UUID auto-generated primary key on one of my tables.

Does anyone know how to setup a column in typeorm that is a UUID type and auto-generated, I have tried the following:

Using @PrimaryGeneratedColumn()

```<code>@PrimaryGeneratedColumn() id: string;
</code>```

This gives me an exception when synchronising with the database

```<code>TypeORM connection error: Error: column "id" cannot be cast automatically to type integer
app.ts:65
at new QueryFailedError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/error/QueryFailedError.js:27:28)
at Query.callback (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:216:38)
at Query.handleError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/query.js:143:17)
at Connection.connectedErrorHandler (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/client.js:132:26)
at emitOne (events.js:115:13)
at Connection.emit (events.js:210:7)
at Socket.<anonymous> (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/connection.js:118:12)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
</code>```

Using @PrimaryColumn and @Generated

```<code>@PrimaryColumn({type:"uuid"})
@Generated("uuid") id: string;
</code>```

I get the following error when attempting this

```<code>TypeORM connection error: Error: sequence "SystemUser_id_seq" does not exist
app.ts:65
at new QueryFailedError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/error/QueryFailedError.js:27:28)
at Query.callback (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:216:38)
at Query.handleError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/query.js:143:17)
at Connection.connectedErrorHandler (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/client.js:132:26)
at emitOne (events.js:115:13)
at Connection.emit (events.js:210:7)
at Socket.<anonymous> (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/connection.js:118:12)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
</code>```

So it looks like this way I can get a primary column but typeorm is not creating the sequence required for this to be an auto-generated column.

If I use @PrimaryColumn({type: "uuid"}) then I do get a UUID column in the table but NOT and auto-generated column

I cannot see any other way to achieve this so could someone please advise if this is a) even possible and b) how one would go about creating a auto-generated UUID column...please?

答:
Try:

```<code>@PrimaryGeneratedColumn("uuid")
id: string;
</code>```

Also, if you don't need a primary column, but need to generate uuid sequence, you can try this:

```<code>@Column()
@Generated("uuid")
uuid: string;
</code>```

Body:
I am writing an REST API and for data access I am using typeorm, I have used this successfully but I would like to have a UUID auto-generated primary key on one of my tables.

Does anyone know how to setup a column in typeorm that is a UUID type and auto-generated, I have tried the following:

Using @PrimaryGeneratedColumn()

@PrimaryGeneratedColumn() id: string;

This gives me an exception when synchronising with the database

TypeORM connection error: Error: column "id" cannot be cast automatically to type integer
app.ts:65
at new QueryFailedError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/error/QueryFailedError.js:27:28)
at Query.callback (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:216:38)
at Query.handleError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/query.js:143:17)
at Connection.connectedErrorHandler (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/client.js:132:26)
at emitOne (events.js:115:13)
at Connection.emit (events.js:210:7)
at Socket.<anonymous> (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/connection.js:118:12)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)

Using @PrimaryColumn and @Generated

@PrimaryColumn({type:"uuid"})
@Generated("uuid") id: string;

I get the following error when attempting this

TypeORM connection error: Error: sequence "SystemUser_id_seq" does not exist
app.ts:65
at new QueryFailedError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/error/QueryFailedError.js:27:28)
at Query.callback (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:216:38)
at Query.handleError (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/query.js:143:17)
at Connection.connectedErrorHandler (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/client.js:132:26)
at emitOne (events.js:115:13)
at Connection.emit (events.js:210:7)
at Socket.<anonymous> (/Users/neilstevens/repositories/Capp.co/capp/ms/ms-token-server/node_modules/pg/lib/connection.js:118:12)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)

So it looks like this way I can get a primary column but typeorm is not creating the sequence required for this to be an auto-generated column.

If I use @PrimaryColumn({type: "uuid"}) then I do get a UUID column in the table but NOT and auto-generated column

I cannot see any other way to achieve this so could someone please advise if this is a) even possible and b) how one would go about creating a auto-generated UUID column...please?

Body:
Try:

@PrimaryGeneratedColumn("uuid")
id: string;

Also, if you don't need a primary column, but need to generate uuid sequence, you can try this:

@Column()
@Generated("uuid")
uuid: string;


问:
Routing to API gateway using AWS Route 53
I have a lambda function in all AWS regions. I have clients throughout the globe who will make a POST call to my base domain example.com. It is the responsibility of my (kind-of) load-balancer to make sure that the requests are routed to the API gateway of the region which is closest to the client, in order to minimize the latency.

So, far I have the following configuration:

Lambda functions deployed on each region

Custom domain names for each of the API gateways, which exposes a CloudFront domain name. For instance, N.California region has custom domain name us-west-1.example.com configured and a mapping of the path which calls my lambda. The CloudFront URL for this API gateway is d12345123.cloudfront.net

A RecordSet of type A in the Route53 hosted zone for us-west-1.example.com which is an alias of d12345123.cloufront.net. If I make a POST call to us-west-1.example.com/1.0/localdb, it returns me the correct output.

A traffic policy in Route53 and a policy record, for default.example.com of A type, which has a geo-proximity rule assigned to it, which redirects the traffic to the CloudFront instance (the same instance which is exposed after adding the custom domain name in that region) of the region. This creates an entry for default.example.com in the hosted zone of type A

A RecordSet of type A in the Route53 hosted zone for example.com which is an alias to default.example.com, so that the traffic which comes to example.com can be routed to default.example.com

After these configurations, when I make a call to example.com, I receive a 403 response from Cloudfront, calling it a Bad Request

Thanks

答:
As of Nov 2017 "Amazon API Gateway Supports Regional API Endpoints"

https://aws.amazon.com/about-aws/whats-new/2017/11/amazon-api-gateway-supports-regional-api-endpoints/

You can now choose from two types of API endpoints when creating REST APIs and custom domains with Amazon API Gateway. A regional API endpoint is a new type of endpoint that is accessed from the same AWS region in which your REST API is deployed. This helps you reduce request latency when API requests originate from the same region as your REST API. Additionally, you can now choose to associate your own Amazon CloudFront distribution with the regional API endpoint. The second type of API endpoint is the edge-optimized API. Edge-optimized APIs are endpoints that are accessed through a CloudFront distribution that is created and managed by API Gateway. Previously, edge-optimized APIs were the default option for creating APIs with API Gateway.

To get started, create a new REST API using the Amazon API Gateway console, AWS CLI, or AWS SDKs and APIs. You can also migrate existing REST APIs and custom domains to a regional API endpoint. Visit our documentation to learn more about this feature.

This feature is now available in US East (N. Virginia), US East (Ohio), US West (Oregon), US West (N. California), Canada (Central), South America (São Paulo), EU (Ireland), EU (Frankfurt), EU (London), Asia Pacific (Singapore), Asia Pacific (Tokyo), Asia Pacific (Sydney), Asia Pacific (Seoul), and Asia Pacific (Mumbai) AWS regions. Visit our product page for more information about Amazon API Gateway.


问:
Electron Login / Register etc
I am pretty new to making Electron apps. After asking a question on Stack Overflow (Properly Using Electron) I followed the advice I was given and created a desktop application in Electron.

I have another app created in NodeJS that handles my database
methods.

I am not sure where to start with this problem, as there are hundreds of options online, and I am not sure which ones suit my needs.

Should I:

Have a client application made in Electron and a server made in NodeJS that handles the database

OR

Have a client application and connect to my database from Electron?

If I were to do it all in a client app, I think that would cause major security issues, so I am unsure what to do. The problem is as simple as creating a login/system application, but I have no idea how to incorporate it into Electron.

Where do I start? How do I approach this?

答:
If all you need is a login and your server already manages the database I would keep this logic on the server. This is also something the answer to your previous question states.

Your client sends a POST request containing the username, password over HTTPS (SSL encryption), this can happen in the renderer process.

Your Server checks if the password and user are valid.

Server returns your client if the authentification was valid, via token.

Either the main process (Electron-NodeJs) persists the token (File)

Or the Render process (Electron-Chromium) persists the token (Web Storage)

This is the most simple example which is neglecting advanced security concerns, if you want to make it more secure you definitely should look for general advise about web security like crypto-pbkdf2 and how to handle the tokens. But this is not electron specific.

Title: Electron Login / Register etc


问:
JUnit test zipping of folder
I have implemented a method to zip files. This method is capable of zipping subfolder, overwriting existing zip files and some more. Now I want to create unit tests for this method. I started with a default zip-file with some content so I could test the overwriting etc.

My method to set up the source files:

```<code>@Before
public void setUp() throws IOException, URISyntaxException {

    util = new ZipFileUtil();

    parent = folder.newFolder("Parent");
    File subfolder = folder.newFolder("Parent", "Subfolder");
    File sub2 = folder.newFolder("Parent", "Subfolder", "Sub2");

    File f1 = File.createTempFile("file1", ".txt", parent);
    File f2 = File.createTempFile("file2", ".txt", parent);
    File f3 = File.createTempFile("file3", ".txt", parent);

    File f4 = File.createTempFile("file4", ".txt", subfolder);
    File f5 = File.createTempFile("file5", ".txt", subfolder);

    File f6 = File.createTempFile("file6", ".txt", sub2);
    File f7 = File.createTempFile("file7", ".txt", sub2);

    File f8 = File.createTempFile("test", ".txt", sub2);

    File f9 = File.createTempFile("test1", ".txt", parent);

    files[0] = f1;
    files[1] = f2;
    files[2] = f3;
    files[3] = f4;
    files[4] = f5;
    files[5] = f6;
    files[6] = f7;
    files[7] = f8;
    files[8] = f9;

    File file = new File(getClass().getClassLoader().getResource("test.zip").toURI());

    Files.copy(file.toPath(), Paths.get(folder.getRoot().toString(), "test.zip"),
            StandardCopyOption.REPLACE_EXISTING);
}
</code>```

And my test:

```<code>@Test
public void testOverwriteFilesInExistingZip() throws IOException {
    util.setZipNameGenerator(new ZipNamingStrategy() {

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "test";
        }

    });
    util.setOverwriteFilesInExistingZip(true);
    util.setSourceFolder(parent);
    util.setDestinationFolder(folder.getRoot());
    util.generateZip(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return true;

        }
    });
    FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

    assertEquals("/" + files[0].getName(),
            fs.getPath("/", parent.toPath().relativize(files[0].toPath()).toString()).toString());
    assertEquals("/" + files[1].getName(),
            fs.getPath("/", parent.toPath().relativize(files[1].toPath()).toString()).toString());
    assertEquals("/" + files[2].getName(),
            fs.getPath("/", parent.toPath().relativize(files[2].toPath()).toString()).toString());
    assertEquals(true,
            new File(fs.getPath("/", parent.toPath().relativize(files[8].toPath()).toString()).toString()).exists());

    assertEquals("/file.txt", fs.getPath("/", "file.txt").toString());
    assertEquals("/New Text Document.txt", fs.getPath("/", "New Text Document.txt").toString());
    assertEquals("/test.txt", fs.getPath("/", "test.txt").toString());
    assertEquals("/test1.txt", fs.getPath("/", "test1.txt").toString());

    assertEquals("/Subfolder/file.txt", fs.getPath("/", "test1.txt").toString());
    assertEquals("/Subfolder/desktop.ini", fs.getPath("/", "test1.txt").toString());
    assertEquals("/Subfolder/test.txt", fs.getPath("/", "test1.txt").toString());
    assertEquals("/Subfolder/New Text Document.txt", fs.getPath("/", "test1.txt").toString());

    assertEquals(15, util.getProcessedFiles());

}
</code>```

I am kinda lost on how to properly check if the zip file has the right structure (files have to exist in the file). Currently I am just checking the paths, but this is so wrong and I know it. Can anyone enlighten me on how to properly test this kind of method?

答:
If you want to check whether these files exist within the zip file, you can use Files.exist(path).

If you want to go further and check the actual content, you can either unzip into a different temporary directory, or ask Java to read directly from the zip file.

Title: JUnit test zipping of folder

Body:
I have implemented a method to zip files. This method is capable of zipping subfolder, overwriting existing zip files and some more. Now I want to create unit tests for this method. I started with a default zip-file with some content so I could test the overwriting etc.

My method to set up the source files:

@Before
public void setUp() throws IOException, URISyntaxException {

    util = new ZipFileUtil();

    parent = folder.newFolder("Parent");
    File subfolder = folder.newFolder("Parent", "Subfolder");
    File sub2 = folder.newFolder("Parent", "Subfolder", "Sub2");

    File f1 = File.createTempFile("file1", ".txt", parent);
    File f2 = File.createTempFile("file2", ".txt", parent);
    File f3 = File.createTempFile("file3", ".txt", parent);

    File f4 = File.createTempFile("file4", ".txt", subfolder);
    File f5 = File.createTempFile("file5", ".txt", subfolder);

    File f6 = File.createTempFile("file6", ".txt", sub2);
    File f7 = File.createTempFile("file7", ".txt", sub2);

    File f8 = File.createTempFile("test", ".txt", sub2);

    File f9 = File.createTempFile("test1", ".txt", parent);

    files[0] = f1;
    files[1] = f2;
    files[2] = f3;
    files[3] = f4;
    files[4] = f5;
    files[5] = f6;
    files[6] = f7;
    files[7] = f8;
    files[8] = f9;

    File file = new File(getClass().getClassLoader().getResource("test.zip").toURI());

    Files.copy(file.toPath(), Paths.get(folder.getRoot().toString(), "test.zip"),
            StandardCopyOption.REPLACE_EXISTING);
}

And my test:

@Test
public void testOverwriteFilesInExistingZip() throws IOException {
    util.setZipNameGenerator(new ZipNamingStrategy() {

        @Override
        public String getName() {
            // TODO Auto-generated method stub
            return "test";
        }

    });
    util.setOverwriteFilesInExistingZip(true);
    util.setSourceFolder(parent);
    util.setDestinationFolder(folder.getRoot());
    util.generateZip(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            return true;

        }
    });
    FileSystem fs = FileSystems.newFileSystem(Paths.get(folder.getRoot().getAbsolutePath(), "test.zip"), null);

    assertEquals("/" + files[0].getName(),
            fs.getPath("/", parent.toPath().relativize(files[0].toPath()).toString()).toString());
    assertEquals("/" + files[1].getName(),
            fs.getPath("/", parent.toPath().relativize(files[1].toPath()).toString()).toString());
    assertEquals("/" + files[2].getName(),
            fs.getPath("/", parent.toPath().relativize(files[2].toPath()).toString()).toString());
    assertEquals(true,
            new File(fs.getPath("/", parent.toPath().relativize(files[8].toPath()).toString()).toString()).exists());

    assertEquals("/file.txt", fs.getPath("/", "file.txt").toString());
    assertEquals("/New Text Document.txt", fs.getPath("/", "New Text Document.txt").toString());
    assertEquals("/test.txt", fs.getPath("/", "test.txt").toString());
    assertEquals("/test1.txt", fs.getPath("/", "test1.txt").toString());

    assertEquals("/Subfolder/file.txt", fs.getPath("/", "test1.txt").toString());
    assertEquals("/Subfolder/desktop.ini", fs.getPath("/", "test1.txt").toString());
    assertEquals("/Subfolder/test.txt", fs.getPath("/", "test1.txt").toString());
    assertEquals("/Subfolder/New Text Document.txt", fs.getPath("/", "test1.txt").toString());

    assertEquals(15, util.getProcessedFiles());

}

I am kinda lost on how to properly check if the zip file has the right structure (files have to exist in the file). Currently I am just checking the paths, but this is so wrong and I know it. Can anyone enlighten me on how to properly test this kind of method?


问:
how can I create executable file for the program written on Java?
everyone, how can I create executable file for the program written on Java in Eclipse Helios? I mean to create small icon to be able start program only by double-clicking on its icon, thanks in advance
edited
I mean executable for Windows

答:
Export .jar in eclipse. (how to)

Use JSmooth (info) to make an .exe file. (how to)


问:
Java parsing last part of a string
I have three strings.

```<code>0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1
</code>```

I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:

```<code>0:0:1
1:2:0
3:2:1
</code>```

I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string

```<code>lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);
</code>```

I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.

```<code>String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];
</code>```

What is a way I could do this? Thanks

答:
Since your requirement concentrate around your need of acquiring the sub-string from the end till - appears first time.

So why not first get the index of last - that appeared in string. And after than extract the sub-string from here till end. Good option. :)

```<code>String str = "0:0:0-3:0:0-3:2:0-3:2:1";
String reqStr = str.substring(str.lastIndexOf('-')+1);
</code>```

reqStr contains the required string. You can use loop with this part of code to extract more such strings.

Title: Java parsing last part of a string

Body:
I have three strings.

0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1

I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:

0:0:1
1:2:0
3:2:1

I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string

lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);

I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.

String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];

What is a way I could do this? Thanks

Body:
Since your requirement concentrate around your need of acquiring the sub-string from the end till - appears first time.

So why not first get the index of last - that appeared in string. And after than extract the sub-string from here till end. Good option. :)

String str = "0:0:0-3:0:0-3:2:0-3:2:1";
String reqStr = str.substring(str.lastIndexOf('-')+1);

reqStr contains the required string. You can use loop with this part of code to extract more such strings.


问:
Cannot embed Git LFS .mp4 files in HTML page video tag?
In my github repository, I cannot access files stored in git lfs when writing up an HTML page, and I think it's because of the src= aspect of the tag.

So I recently installed git-lfs and it seems that the files are stored (when I do git lfs ls-files the file shows up. I am currently storing .mp4 files in my lfs, but when it comes to using the <video> tag in the HTML of my repositoryname.github.io page, it shows as "no video with the supported format and MIME type found" in the video element.

I've tried src="../file.mp4" and src="file.mp4" and src="https://repositoryname.github.io/file.mp4" and src="https://github.com/repositoryname/repositoryname.github.io.git/info/lfs/file.mp4" (where git lfs env says the endpoint is) but nothing has worked so far.

I don't want upload it to a video streaming site and then embed it in the page, and src="../file.mp4" and src="file.mp4" work for smaller video files that are not in git lfs storage.

Any possible solutions? I'm not sure if I missed something as to how to link/embed files, but I'm very, very, new to git and git-lfs, so please go easy on me .

答:
Getting the file

I'm not 100% sure it works for videos, but I noticed that on the current version of the web UI, you have a "Download" button instead of the "Raw" and "Blame" buttons for files tracked with LFS.

Clicking on the "Download" button takes you to a place different from what the output of git lfs env indicates.

In the case of an image, I see the following URL:

```<code>https://media.githubusercontent.com/media/{USER}/{REPO}/master/{PATH_TO_FILE}
</code>```

Some images: (sorry not enough reputation to embed them)

Check this link to see how the toolbar looks for files stored with Git LFS

Check this link to see how the toolbar looks for files stored with plain Git

About entrypoint URL you get with git lfs env

If I get it right, the Git LFS protocol says that blobs and not files should be fetched from here, using the sha256 and size of real files.

Further more, the server API specifications seem to indicate that this entrypoint is a public API which reads JSON requests (containing information about the file to fetch) rather than using the document path from the HTTP request…

Body:
Getting the file

I'm not 100% sure it works for videos, but I noticed that on the current version of the web UI, you have a "Download" button instead of the "Raw" and "Blame" buttons for files tracked with LFS.

Clicking on the "Download" button takes you to a place different from what the output of git lfs env indicates.

In the case of an image, I see the following URL:

https://media.githubusercontent.com/media/{USER}/{REPO}/master/{PATH_TO_FILE}

Some images: (sorry not enough reputation to embed them)

Check this link to see how the toolbar looks for files stored with Git LFS

Check this link to see how the toolbar looks for files stored with plain Git

About entrypoint URL you get with git lfs env

If I get it right, the Git LFS protocol says that blobs and not files should be fetched from here, using the sha256 and size of real files.

Further more, the server API specifications seem to indicate that this entrypoint is a public API which reads JSON requests (containing information about the file to fetch) rather than using the document path from the HTTP request…


问:
(Python/TFTP-Server) how to listen to an non (yet) existing IP-address (RNDIS)?
Hy folks,

my problem: I want to start a (tftp) server for an non-existing IP-address.
the server is meant for USB/RNDIS where its IP-address by nature only is existing when there is actual network-traffic going on -- but I want to start the server 'early' (e.g. when Windows starts).

idea was to bind() the socket to 0.0.0.0 - and then to check each request for "valid" addresses.

problem with that approach: recfrom() only returns the source-address (client), but not the destination (server)!

how do I get the IP-address this client has talked to?
(I could of course check for the same subnet at least, but I need the real server-address this client was talking to!)

or, are there by chance any options to let bind() use a non-existing IP-address?

cheers.

p.s.
this is for the Python tftpy server...
-- at the moment I need to ping from client side when starting the server, which is quite meh...

答:
There's no way to get the local address directly but there's a trick that will usually work for you.

Let's say that you just obtained a buffer and client address from recvfrom. Now you create a new auxiliary UDP socket, connect it to the client's address, and then use getsockname to obtain the local address on this new socket. (With UDP, connect doesn't actually send anything to the peer, it just does address resolution.)

So in this way, you can discover the IP address that the server system would use as source were it to send a datagram back to the client system. That's usually the same address that the client used to target the server.

```<code>>>> cbytes, caddr = server_sock.recvfrom(2048)
>>> print(caddr)                           # Client IP and port
('192.168.0.11', 38869)

>>> aux_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> aux_socket.connect((caddr[0], 9999))   # Connect back to client (port doesn't matter)
>>> saddr = aux_socket.getsockname()       # Get local IP and port (ignore port here too)
>>> print(saddr)
('192.168.0.12', 39753)
</code>```

This works on linux. I'm not 100% sure it would work the same way on Windows but it seems reasonable to expect that it would.

Body:
There's no way to get the local address directly but there's a trick that will usually work for you.

Let's say that you just obtained a buffer and client address from recvfrom. Now you create a new auxiliary UDP socket, connect it to the client's address, and then use getsockname to obtain the local address on this new socket. (With UDP, connect doesn't actually send anything to the peer, it just does address resolution.)

So in this way, you can discover the IP address that the server system would use as source were it to send a datagram back to the client system. That's usually the same address that the client used to target the server.

>>> cbytes, caddr = server_sock.recvfrom(2048)
>>> print(caddr)                           # Client IP and port
('192.168.0.11', 38869)

>>> aux_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> aux_socket.connect((caddr[0], 9999))   # Connect back to client (port doesn't matter)
>>> saddr = aux_socket.getsockname()       # Get local IP and port (ignore port here too)
>>> print(saddr)
('192.168.0.12', 39753)

This works on linux. I'm not 100% sure it would work the same way on Windows but it seems reasonable to expect that it would.


问:
How to properly close an alert box javafx

I am trying to create an alert box type window that is like a user registration panel. Now when I close the window using the top-right button (I do not have a cancel/close button implemented) and re-open it there's this error that pops up:

```<code>Caused by: java.lang.IllegalStateException: Cannot set modality once stage has been set visible
at javafx.stage.Stage.initModality(Stage.java:525)
at elibraryserver.NewStudentController.initRegister(NewStudentController.java:150)
at elibraryserver.serverController.addStudentButtonAction(serverController.java:71)
... 53 more
</code>```

I do not understand since I closed the window shouldn't it reset and open another one? What I can see from the error is that it thinks the window is still open. Or am I wrong?

Here is the code for the stage:

```<code>public void initRegister() throws IOException {
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("newStudent.fxml"));
    Parent root = loader.load();

    Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
    registerStage.setX((screenBounds.getWidth() - registerStage.getWidth()) / 2);
    registerStage.setY((screenBounds.getHeight() - registerStage.getHeight()) / 2);

    Scene scene = new Scene(root);
    registerStage.setScene(scene);
    registerStage.setTitle("Register Student");
    registerStage.initModality(Modality.APPLICATION_MODAL);
    registerStage.showAndWait();
}

public void addStudentButtonAction(ActionEvent event) throws IOException {
    NewStudentController nsc = new NewStudentController();
    nsc.initRegister();
}
</code>```

答:
Not sure what exactly your issue is I think it is because you are not creating a new stage when you initialize your new window

Here is some example code

```<code>import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        Button button = new Button("Open Test window");
        VBox vbox = new VBox();
        vbox.getChildren().addAll(button);
        Scene scene = new Scene(vbox);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

        button.setOnAction(event -> {
            try {
                openAction();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void openAction() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("Test.fxml"));
        Parent root = loader.load();

        Stage stage = new Stage();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("Register Student");
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}
</code>```

testFXML Controller

```<code>import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.*;
import javafx.scene.paint.Paint;

import java.net.URL;
import java.util.ResourceBundle;

public class TestFXMLController implements Initializable{
    public ColorPicker colorPicker;
    public VBox vBox;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        colorPicker.setOnAction(event -> {
            Paint fill = colorPicker.getValue();
            BackgroundFill backgroundFill =
                    new BackgroundFill(fill,
                            CornerRadii.EMPTY,
                            Insets.EMPTY);
            Background background = new Background(backgroundFill);
            vBox.setBackground(background);
        });
    }
}
</code>```

Test.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ColorPicker?>
<?import javafx.scene.layout.VBox?>
<VBox fx:id="vBox" alignment="CENTER" prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="TestFXMLController">
   <children>
      <ColorPicker fx:id="colorPicker" opacity="0.5" VBox.vgrow="ALWAYS" />
   </children>
</VBox>
</code>```

Body:
I am trying to create an alert box type window that is like a user registration panel. Now when I close the window using the top-right button (I do not have a cancel/close button implemented) and re-open it there's this error that pops up:

Caused by: java.lang.IllegalStateException: Cannot set modality once stage has been set visible
at javafx.stage.Stage.initModality(Stage.java:525)
at elibraryserver.NewStudentController.initRegister(NewStudentController.java:150)
at elibraryserver.serverController.addStudentButtonAction(serverController.java:71)
... 53 more

I do not understand since I closed the window shouldn't it reset and open another one? What I can see from the error is that it thinks the window is still open. Or am I wrong?

Here is the code for the stage:

public void initRegister() throws IOException {
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("newStudent.fxml"));
    Parent root = loader.load();

    Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
    registerStage.setX((screenBounds.getWidth() - registerStage.getWidth()) / 2);
    registerStage.setY((screenBounds.getHeight() - registerStage.getHeight()) / 2);

    Scene scene = new Scene(root);
    registerStage.setScene(scene);
    registerStage.setTitle("Register Student");
    registerStage.initModality(Modality.APPLICATION_MODAL);
    registerStage.showAndWait();
}

public void addStudentButtonAction(ActionEvent event) throws IOException {
    NewStudentController nsc = new NewStudentController();
    nsc.initRegister();
}

Body:
Not sure what exactly your issue is I think it is because you are not creating a new stage when you initialize your new window

Here is some example code

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        Button button = new Button("Open Test window");
        VBox vbox = new VBox();
        vbox.getChildren().addAll(button);
        Scene scene = new Scene(vbox);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.show();

        button.setOnAction(event -> {
            try {
                openAction();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void openAction() throws IOException {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("Test.fxml"));
        Parent root = loader.load();

        Stage stage = new Stage();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("Register Student");
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}

testFXML Controller

import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.*;
import javafx.scene.paint.Paint;

import java.net.URL;
import java.util.ResourceBundle;

public class TestFXMLController implements Initializable{
    public ColorPicker colorPicker;
    public VBox vBox;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        colorPicker.setOnAction(event -> {
            Paint fill = colorPicker.getValue();
            BackgroundFill backgroundFill =
                    new BackgroundFill(fill,
                            CornerRadii.EMPTY,
                            Insets.EMPTY);
            Background background = new Background(backgroundFill);
            vBox.setBackground(background);
        });
    }
}

Test.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ColorPicker?>
<?import javafx.scene.layout.VBox?>
<VBox fx:id="vBox" alignment="CENTER" prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="TestFXMLController">
   <children>
      <ColorPicker fx:id="colorPicker" opacity="0.5" VBox.vgrow="ALWAYS" />
   </children>
</VBox>


问:
Sum integer list when next integer is the same value
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

```<code>input1 = [int(i) for i in str(1234441122)]
x= 0
</code>```

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

答:
Try this one too:

```<code>input1 = [int(i) for i in str(1234441122)]
x= 0
res = [input1[i] for i in range(len(input1)-1) if input1[i+1]==input1[i]]
print(res)
print(sum(res))
</code>```

Output:

```<code>[4, 4, 1, 2]
11
</code>```

Body:
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

input1 = [int(i) for i in str(1234441122)]
x= 0

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

Body:
Try this one too:

input1 = [int(i) for i in str(1234441122)]
x= 0
res = [input1[i] for i in range(len(input1)-1) if input1[i+1]==input1[i]]
print(res)
print(sum(res))

Output:

[4, 4, 1, 2]
11