问:
Authenticating Users for Multiple Applications on same host name but different paths
I have two mvc 5 applications setup using OWIN-MixedAuth deployed to the same server. Each application is inside a separate folder and configured with its own app pool as follows:

```<code>xyz.domain.com/MySiteA

xyz.domain.com/MySiteB
</code>```

Web config for each is as follows

MySiteA:

```<code><system.web>
   <customErrors mode="Off"/>
   <authentication mode="None" />
   <compilation debug="true" targetFramework="4.5.2" />
   <httpRuntime targetFramework="4.5.2" />
</system.web>
<!-- Enable Mixed Auth -->
<location path="MySiteA/MixedAuth">
   <system.webServer>
       <security>
        <authentication>
            <windowsAuthentication enabled="true" />
        </authentication>
       </security>
    </system.webServer>
</location>
<system.webServer>
    <modules>
        <remove name="FormsAuthentication" />
    </modules>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>`
</code>```

MySiteB:

```<code> <system.web>
   <customErrors mode="Off"/>
   <authentication mode="None" />
   <compilation debug="true" targetFramework="4.5.2" />
   <httpRuntime targetFramework="4.5.2" />
</system.web>
<!-- Enable Mixed Auth -->
<location path="MySiteB/MixedAuth">
   <system.webServer>
       <security>
        <authentication>
            <windowsAuthentication enabled="true" />
        </authentication>
       </security>
    </system.webServer>
</location>
<system.webServer>
    <modules>
        <remove name="FormsAuthentication" />
    </modules>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>`
</code>```

When a user logs into one applications, the user is automatically logged into the second application as well even though they are not a registered user in the second application.

similarly loggin out of one application automatically logs the user out of the second application.

This is happening if I authenticate using a Form or windows. How can I prevent this happening?

This is my login code on both applications:

```<code>    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        // If user is already logged in
        if (HttpContext.Request.IsAuthenticated)
        {
            return RedirectToAction("Index", "Manage");
        }

        ViewBag.ReturnUrl = returnUrl;
        return View();
    }
</code>```

And this is what I have in startup.auth:

```<code>var cookieOptions = new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        };

        app.UseCookieAuthentication(cookieOptions);
</code>```

Is there an option to change the cookie name?

答:
Add CookieName to startup.auth:</p>

```<code> var cookieOptions = new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        CookieName = "MySiteA",
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            // Enables the application to validate the security stamp when the user logs in.
            // This is a security feature which is used when you change a password or add an external login to your account.
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    };

    app.UseCookieAuthentication(cookieOptions);
</code>```

Body:
I have two mvc 5 applications setup using OWIN-MixedAuth deployed to the same server. Each application is inside a separate folder and configured with its own app pool as follows:

xyz.domain.com/MySiteA

xyz.domain.com/MySiteB

Web config for each is as follows

MySiteA:

<system.web>
   <customErrors mode="Off"/>
   <authentication mode="None" />
   <compilation debug="true" targetFramework="4.5.2" />
   <httpRuntime targetFramework="4.5.2" />
</system.web>

<location path="MySiteA/MixedAuth">
   <system.webServer>
       <security>
        <authentication>
            <windowsAuthentication enabled="true" />
        </authentication>
       </security>
    </system.webServer>
</location>
<system.webServer>
    <modules>
        <remove name="FormsAuthentication" />
    </modules>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>`

MySiteB:

 <system.web>
   <customErrors mode="Off"/>
   <authentication mode="None" />
   <compilation debug="true" targetFramework="4.5.2" />
   <httpRuntime targetFramework="4.5.2" />
</system.web>

<location path="MySiteB/MixedAuth">
   <system.webServer>
       <security>
        <authentication>
            <windowsAuthentication enabled="true" />
        </authentication>
       </security>
    </system.webServer>
</location>
<system.webServer>
    <modules>
        <remove name="FormsAuthentication" />
    </modules>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>`

When a user logs into one applications, the user is automatically logged into the second application as well even though they are not a registered user in the second application.

similarly loggin out of one application automatically logs the user out of the second application.

This is happening if I authenticate using a Form or windows. How can I prevent this happening?

This is my login code on both applications:

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        // If user is already logged in
        if (HttpContext.Request.IsAuthenticated)
        {
            return RedirectToAction("Index", "Manage");
        }

        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

And this is what I have in startup.auth:

var cookieOptions = new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        };

        app.UseCookieAuthentication(cookieOptions);

Is there an option to change the cookie name?

Body:
Add CookieName to startup.auth:

 var cookieOptions = new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        CookieName = "MySiteA",
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            // Enables the application to validate the security stamp when the user logs in.
            // This is a security feature which is used when you change a password or add an external login to your account.
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    };

    app.UseCookieAuthentication(cookieOptions);


来源: stackexchange

问:
JSP session is not null
I'm newbie to JSP and on particular page of my webapp I'm trying to determine whether user is logged in. To do this, I'm checking for session existance. If session does not exist then I will redirect user to the login page.

I'm confused by the fact that the following code

```<code><%
if (null == session)
    out.println("session is null");
else
    out.println("session is not null");

if (null == request.getSession(false))
    out.println("request.getSession() is null");
else
    out.println("request.getSession() is not null");
%>
</code>```

under any circumstances produces the following output:

```<code>session is not null request.getSession() is not null
</code>```

I don't understand why the session exists even when I didn't create it. How do I check whether user is logged in or not?

Thanks in advance.

答:
I would like to add one more point on @jdevelop 's answer:

Once you write <%@ page session="false" %> in your JSP page, session object becomes unavailable directly. That is why you will have to use request.getSession(false) (of-course you will have to add null check) to access the session object.

ContentLicense: CC BY-SA 3.0

Title: JSP session is not null

Body:
I'm newbie to JSP and on particular page of my webapp I'm trying to determine whether user is logged in. To do this, I'm checking for session existance. If session does not exist then I will redirect user to the login page.

I'm confused by the fact that the following code

<%
if (null == session)
    out.println("session is null");
else
    out.println("session is not null");

if (null == request.getSession(false))
    out.println("request.getSession() is null");
else
    out.println("request.getSession() is not null");
%>

under any circumstances produces the following output:

session is not null request.getSession() is not null

I don't understand why the session exists even when I didn't create it. How do I check whether user is logged in or not?

Thanks in advance.


问:
using type alias doesn't work with "const" pointer
Here, const pointer hold the address of const variable. like :

```<code>#include <iostream>

int main()
{
    const int i = 5;
    const int* ptr = &i;
}
</code>```

It's working fine.

But, If I use using (Type alias) like:

```<code>#include <iostream>

using intptr = int*;

int main() {
    const int i = 5;
    const intptr ptr = &i;
}
</code>```

GCC compiler gives an error. [Live demo]

Why pointer does not work with using Type alias?

答:
const intptr ptr is an equivalent of int * const ptr - const pointer to non-const int, not const int * ptr - non-const pointer to const int.

If you find such right-to-left reading order for pointer declarations confusing you can utilize Straight declarations library which supplies alias templates to declare pointer types with left-to-right reading order:

```<code>const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int
</code>```

Body:
Here, const pointer hold the address of const variable. like :

#include <iostream>

int main()
{
    const int i = 5;
    const int* ptr = &i;
}

It's working fine.

But, If I use using (Type alias) like:

#include <iostream>

using intptr = int*;

int main() {
    const int i = 5;
    const intptr ptr = &i;
}

GCC compiler gives an error. [Live demo]

Why pointer does not work with using Type alias?

Body:
const intptr ptr is an equivalent of int * const ptr - const pointer to non-const int, not const int * ptr - non-const pointer to const int.

If you find such right-to-left reading order for pointer declarations confusing you can utilize Straight declarations library which supplies alias templates to declare pointer types with left-to-right reading order:

const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int


问:
Getting Current Location instead of Cache ios
I have searched a lot and didn't get any satisfactory answer, I have a scenario where I am showing a list of sellers based on user's current location. I am getting a location for the first time and when I run my App afterward whenever I try to get the location I am getting a cache location data. I did try after some time even after every 24 hours but still getting the cache location where my current location is changed as well. Following is the code I am using for reference. please advise.

Property defined in Header file

```<code>@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];

}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}
</code>```

答:
You can do something like,

```<code>-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

for(int i=0;i<locations.count;i++){
    CLLocation * newLocation = [locations objectAtIndex:i];
    CLLocationCoordinate2D theLocation = newLocation.coordinate;
    CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;

    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

    if (locationAge > 5.0)
    {
        continue;
    }

       // do your all stuff here and then

       break;

    }

}
</code>```

Your code will not executes if your location age is more than 5 seconds. You can decide location age lie 10 seconds or 20 seconds!

Update :

Just replace your property declaration

```<code> @property (nonatomic,retain) CLLocationManager *locationManager;
</code>```

with

```<code> @property (nonatomic,strong) CLLocationManager *locationManager;
</code>```

or

just declare it as instance variable like,

```<code> CLLocationManager *locationManager;
</code>```

and remove self from avery instance of it!

Second thing,

You should do first,

```<code>  [self.locationManager requestWhenInUseAuthorization];
</code>```

and then start update of location,

```<code>  [self.locationManager startUpdatingLocation];
</code>```

Body:
I have searched a lot and didn't get any satisfactory answer, I have a scenario where I am showing a list of sellers based on user's current location. I am getting a location for the first time and when I run my App afterward whenever I try to get the location I am getting a cache location data. I did try after some time even after every 24 hours but still getting the cache location where my current location is changed as well. Following is the code I am using for reference. please advise.

Property defined in Header file

@property (nonatomic,retain) CLLocationManager *locationManager;

- (void)startSingleLocationRequest
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [self.locationManager startUpdatingLocation];
    [self.locationManager requestWhenInUseAuthorization];

}

#pragma mark --didUpdateLocations
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    self.latitudeValue =  locations.lastObject.coordinate.latitude;
    self.longitudeValue =  locations.lastObject.coordinate.longitude;
// location set for simulation to UK
    if(self.latitudeValue != 51.509979 && self.longitudeValue != -0.133700){
         [MBProgressHUD hideHUDForView:self.outletSearchNearBy animated:YES];
           [self.locationManager stopUpdatingLocation];
        abc *slv =[self.storyboard instantiateViewControllerWithIdentifier:@"abc"];
        slv.receivedLatitudeValue = self.latitudeValue;
        slv.receivedLongitudeValue = self.longitudeValue;

        [self.navigationController pushViewController:slv animated:YES];
    }
    else{}

}

Body:
You can do something like,

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

for(int i=0;i<locations.count;i++){
    CLLocation * newLocation = [locations objectAtIndex:i];
    CLLocationCoordinate2D theLocation = newLocation.coordinate;
    CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;

    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

    if (locationAge > 5.0)
    {
        continue;
    }

       // do your all stuff here and then

       break;

    }

}

Your code will not executes if your location age is more than 5 seconds. You can decide location age lie 10 seconds or 20 seconds!

Update :

Just replace your property declaration

 @property (nonatomic,retain) CLLocationManager *locationManager;

with

 @property (nonatomic,strong) CLLocationManager *locationManager;

or

just declare it as instance variable like,

 CLLocationManager *locationManager;

and remove self from avery instance of it!

Second thing,

You should do first,

  [self.locationManager requestWhenInUseAuthorization];

and then start update of location,

  [self.locationManager startUpdatingLocation];


问:
jquery - bug with displaying select options
I have multiple select menus where the pattern is :

```<code><select name='device$num' id='device$num' size='8' multiple='multiple' >"
</code>```

I want to display the values out when any one of these select changes.

I tried this but sometimes I get undefined values from the alert. what is wrong?

```<code><script>
    \$("select[id^=device]").change(function () {
        \$("#paramselection").html(" ");
        \$("#voltageselection").html(" ");

        // IF THE DATA HAS CHANGED, FIND OUT WHICH DATA SECTIONS ARE STILL VALID

        \$("select[id^=device] :selected").val(function(index, value) {
            alert(value);
        });
    });
</script>
</code>```

Another question, how do i pattern match such that id^=device\d+? Sorry, I am more familar with perl

答:
Change your alert to this to get the selected text:</p>

```<code>\$("select[id^='device'] option:selected").each(function() {
     alert($(this).text());
  });
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have multiple select menus where the pattern is :

<select name='device$num' id='device$num' size='8' multiple='multiple' >"

I want to display the values out when any one of these select changes.

I tried this but sometimes I get undefined values from the alert. what is wrong?

Another question, how do i pattern match such that id^=device\d+? Sorry, I am more familar with perl

Body:
Change your alert to this to get the selected text:

\$("select[id^='device'] option:selected").each(function() {
     alert($(this).text());
  });


问:
Database design and structure for product variants
I have a variants for products for example Variant: Size, it has values like Small, Medium, Large. Then Color, values: Red, Orange, blue. Then Material, values: Cotton, Lawn. So I want a database design that have same price, sku for one variant e.g Small Red Cotton have same price and sku and this will repeat for others with different prices.</p>

答:
The obvious solution would be to have a Product table, with three fields (ID, Price, SKU) as well as three foreign keys to lookup tables for size, colour and material.

However, it all depends on what other requirements you have, and what this is all going to be used for. If this isn't a stand-alone structure, it is very likely that the obvious solution is not the best one.


答: Note that for const intptr, const is a top-level qualifier on intptr. So const is qualified on the pointer itself, then const intptr means int* const (i.e. const pointer to non-const int), not const int* (i.e. non-const pointer to const int).

Title: using type alias doesn't work with "const" pointer


问:
Invitation system (push) for web app
I am creating an web app and a user can start a game with multiple players (your friends). This game is played on 1 device. Is it possible that all invited players get a notification on their device where they can accept or decline the invitation ?

So in steps

Player 1 creates a game and invites player 2 and 3

Player 2 receives a notification on his mobile device and presses accept, he is added as player of that game

Player 3 doesn't have a device and enters his PIN to accept his participation.

The step that I want to have is step2.
I have read about OneSignal who can send push notifications to specific users, but I could not find if you can send a response back (accept or decline). Or is there an other way (without to have a native app).

答:
your question is understood but at this moment a little too broad. But. I will try to answer in concept also :)

Now...you said you already know how to send target specific notification with OneSignal.

What you need to do from now one it cloud be like this:

Attach a link or click or action to that invite. Or when such invite
arrived open a particular view in the app/web/application that you are developing and revives the link.

Attach the session/game/user/object ID to that link and send the call
to you API (which is based on your server). If you have an API, if you don't you can have a very simple API build to handle only such requests with URL xxxx.com/path/to/api/call/var1/var2/var3/etc

From there you can catch the request and reply or adapt accordingly on your server side.

Maybe this Framework can help you to speed up the API dev in PHP. Lumen can do that trick.

You can follow this tutorial here for a fast API development with it.

Title: Invitation system (push) for web app


问:
Get Signature from Exchange
For some accounts of my company I can't get the email signature. I use the following code to retrieve signatures:

```<code>OWAConfig = UserConfiguration.Bind(_service, "OWA.UserOptions", WellKnownFolderName.Root, UserConfigurationProperties.Dictionary);
</code>```

Normally it works fine but for some accounts, it throws :

The specified object was not found in the store., The configuration object was not found. Name = OWA.UserOptions.

答:
That error will occur for accounts where they have never logged onto OWA before.
The UserConfiguration object won't exist for those accounts and you won't be able to bind to it in code.

You can check for the UserConfiguration object first and then create it, if it doesn't exist:

```<code>SearchFilter sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Configuration.OWA.UserOptions");
ItemView iv = new ItemView(1);
iv.Traversal = ItemTraversal.Associated;
FindItemsResults<Item> fiResults = Root.FindItems(sf, iv);
UserConfiguration OWAConfig  =null;
if (fiResults.Items.Count == 0)
{
   OWAConfig = new UserConfiguration(service);
   OWAConfig.Save("OWA.UserOptions", Root.ParentFolderId);
}
</code>```

Note: Creating a new UserConfiguration object may cause issues as it doesn't set the first time OWA logon settings, Regional settings etc.
You will need to test the affected accounts for this and rectify them accordingly.

Title: Get Signature from Exchange

Body:
For some accounts of my company I can't get the email signature. I use the following code to retrieve signatures:

OWAConfig = UserConfiguration.Bind(_service, "OWA.UserOptions", WellKnownFolderName.Root, UserConfigurationProperties.Dictionary);

Normally it works fine but for some accounts, it throws :

The specified object was not found in the store., The configuration object was not found. Name = OWA.UserOptions.

Body:
That error will occur for accounts where they have never logged onto OWA before.
The UserConfiguration object won't exist for those accounts and you won't be able to bind to it in code.

You can check for the UserConfiguration object first and then create it, if it doesn't exist:

SearchFilter sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Configuration.OWA.UserOptions");
ItemView iv = new ItemView(1);
iv.Traversal = ItemTraversal.Associated;
FindItemsResults<Item> fiResults = Root.FindItems(sf, iv);
UserConfiguration OWAConfig  =null;
if (fiResults.Items.Count == 0)
{
   OWAConfig = new UserConfiguration(service);
   OWAConfig.Save("OWA.UserOptions", Root.ParentFolderId);
}

Note: Creating a new UserConfiguration object may cause issues as it doesn't set the first time OWA logon settings, Regional settings etc.
You will need to test the affected accounts for this and rectify them accordingly.


问:
mvn spring-boot:run vs java -jar
I know it may sound silly question but I am unable to understand the difference between mvn spring-boot:run and java -jar (.jar file generated with mvn install)

I have a spring boot application with jsp pages in /src/main/resources/META-INF/resources/WEB-INF/. If I use mvn spring-boot:run these pages are served. But If I use java -jar these pages are not found by application.

The application that I am working on is at https://github.com/ArslanAnjum/angularSpringApi

UPDATE:
It works with spring boot 1.4.2.RELEASE while I intend to use the latest version i.e., 1.5.8.RELEASE.

UPDATE:
Well I solved the problem by putting jsps in src/main/webapp/WEB-INF/views/ and changing packaging type to war and then running this war using java -jar target/myapp.war and its working fine now.

答: Have you tried creating a jar file using mvn package instead of mvn install when you are running jar file using java -jar? package will create a jar/war as per your POM file whereas install will install generated jar file to the local repository for other dependencies if present.

Title: mvn spring-boot:run vs java -jar


问:
parsing a cv file
I want to write a code either in Java or PHP (Codeigniter) to extract information such as email and phone number of a user uploading hbis resume or cv to the site. Basically I want to build a cv parser.

Need help for this.

thanks

EDIT
The cv format will be in doc.

答:
you should use python and write your own scraper, its easy and it can be done really quickly in your case with modules like beautiful soup, urllib2 ...

what its this all about

beautiful soup documentation

Title: parsing a cv file


问:
Check all parameters of an object contains empty value in scala
I have a object called Address and it has few number of string parameters:

```<code>class Address(addressLine1: String, addressLine1: String, city: String, state: String) {

}
</code>```

Now I want to create a methods which checks if all address parameters contains empty value:

```<code>def validateAddressNotEmpty(address: Address) : Boolean = {

//return true if any object parameter has non empty string

//return true if all object parameters contains  empty string

//NOTE: no parameter will contain NULL values
  }
</code>```

One way of doing this is to check each parameter separately. I am trying to find out is there any alternative to achieve the same.

答:
case class has an method productIterator to get all elements

```<code>address.productIterator.forall {
  case s: String => s.nonEmpty
  case _         => false
}
</code>```

Body:
I have a object called Address and it has few number of string parameters:

class Address(addressLine1: String, addressLine1: String, city: String, state: String) {

}

Now I want to create a methods which checks if all address parameters contains empty value:

def validateAddressNotEmpty(address: Address) : Boolean = {

//return true if any object parameter has non empty string

//return true if all object parameters contains  empty string

//NOTE: no parameter will contain NULL values
  }

One way of doing this is to check each parameter separately. I am trying to find out is there any alternative to achieve the same.

Body:
case class has an method productIterator to get all elements

address.productIterator.forall {
  case s: String => s.nonEmpty
  case _         => false
}


问:
How to aggregate data in Spark using Scala?
I have a data set test1.txt. It contain data like below

```<code>2::1::3
1::1::2
1::2::2
2::1::5
2::1::4
3::1::2
3::1::1
3::2::2
</code>```

I have created data-frame using the below code.

```<code>case class Test(userId: Int, movieId: Int, rating: Float)
def pRating(str: String): Rating = {
val fields = str.split("::")
assert(fields.size == 3)
Test(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/test/Desktop/test1.txt").map(pRating).toDF()
2,1,3
1,1,2
1,2,2
2,1,5
2,1,4
3,1,2
3,1,1
3,2,2
</code>```

But I want to print output like below I.e. removing duplicate combinations and instead of field(2) value sum of values1,1, 2.0.

```<code>1,1,2.0
1,2,2.0
2,1,12.0
3,1,3.0
3,2,2.0
</code>```

Please help me on this, how can achieve this.

Body:
I have a data set test1.txt. It contain data like below

2::1::3
1::1::2
1::2::2
2::1::5
2::1::4
3::1::2
3::1::1
3::2::2

I have created data-frame using the below code.

case class Test(userId: Int, movieId: Int, rating: Float)
def pRating(str: String): Rating = {
val fields = str.split("::")
assert(fields.size == 3)
Test(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/test/Desktop/test1.txt").map(pRating).toDF()
2,1,3
1,1,2
1,2,2
2,1,5
2,1,4
3,1,2
3,1,1
3,2,2

But I want to print output like below I.e. removing duplicate combinations and instead of field(2) value sum of values1,1, 2.0.

1,1,2.0
1,2,2.0
2,1,12.0
3,1,3.0
3,2,2.0

Please help me on this, how can achieve this.

Body: ratings.groupBy("userId","movieId").sum(rating)


问:
Matching specific pattern in Angular Router
Rather than structure my component's url like this mysite.com/map/cell/3/7  I want to structure it like this mysite.com/map/3,7 and be able to retrieve the first value as "row" and the second as "cell".

How would I achieve this?

PS: If possible I also need to know how to get Express to understand this so my Universal app will render it correctly.

答:
The answer is simple. In the route's definition, you should define a matcher instead of a url.

```<code>export const MyRouteMatcher = segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult {
  // 1: Check it matches your pattern, if not then return null
  const parameterValues: { [key: string]: UrlSegment } = {};
  parameterValues['row'] = new UrlSegment(valueForRow, null);
  parameterValues['cell'] = new UrlSegment(valueForCell, null);

  return {
    consumed: segments,
    posParams: parameterValues
  }
}
</code>```

Body:
The answer is simple. In the route's definition, you should define a matcher instead of a url.

export const MyRouteMatcher = segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult {
  // 1: Check it matches your pattern, if not then return null
  const parameterValues: { [key: string]: UrlSegment } = {};
  parameterValues['row'] = new UrlSegment(valueForRow, null);
  parameterValues['cell'] = new UrlSegment(valueForCell, null);

  return {
    consumed: segments,
    posParams: parameterValues
  }
}


问:
Check if value exists in the list
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

```<code> df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]
</code>```

In SQL I would use:

```<code>select mpls, source from df where source = 192.168.10.10
</code>```

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

答:
df is not a dataframe. It is a list of dictionaries.

As such, your only option is a loop and an if condition:

```<code>for connection in df:
    if connection['source'] == '192.168.10.10':
        print(connection['mpls'])
        print(connection['destination'])
        # do whatever with connection. Can also break if it is guaranteed to be unique.
</code>```

However, if df is a dataframe, you can use pandas indexing syntax:

```<code>relevant_rows = df[df['source'] == '192.168.10.10']
</code>```

relevant_rows will then be a new dataframe whose rows are those where source equals '192.168.10.10'.

```<code>import pandas as pd

data = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]

df = pd.DataFrame(data)

print(df)

#         destination     mpls         source
#     0  12.168.100.10  123-0-1  192.168.10.10
#     1  10.12.129.200  123-0-1  192.168.10.15

relevant_rows = df[df['source'] == '192.168.10.10']

print(relevant_rows)

#         destination     mpls         source
#    0  12.168.100.10  123-0-1  192.168.10.10
</code>```

Title: Check if value exists in the list

Body:
Let’s say I have 123-0-1 and I want to check if this value exists inside the list. Below is the list that I have:

 df = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]

In SQL I would use:

select mpls, source from df where source = 192.168.10.10

From the list, I would like extract mpls 123-0-1 from the source 192.168.10.10 such that I can get the correct destination 12.168.100.10.

Body:
df is not a dataframe. It is a list of dictionaries.

As such, your only option is a loop and an if condition:

for connection in df:
    if connection['source'] == '192.168.10.10':
        print(connection['mpls'])
        print(connection['destination'])
        # do whatever with connection. Can also break if it is guaranteed to be unique.

However, if df is a dataframe, you can use pandas indexing syntax:

relevant_rows = df[df['source'] == '192.168.10.10']

relevant_rows will then be a new dataframe whose rows are those where source equals '192.168.10.10'.

import pandas as pd

data = [
       {'mpls': '123-0-1', 'source': '192.168.10.10', 'destination' : '12.168.100.10'},
       {'mpls': '123-0-1', 'source': '192.168.10.15', 'destination': '10.12.129.200'}
      ]

df = pd.DataFrame(data)

print(df)

#         destination     mpls         source
#     0  12.168.100.10  123-0-1  192.168.10.10
#     1  10.12.129.200  123-0-1  192.168.10.15

relevant_rows = df[df['source'] == '192.168.10.10']

print(relevant_rows)

#         destination     mpls         source
#    0  12.168.100.10  123-0-1  192.168.10.10


问:
changing maildir order
I recently asked this question and worked out that the reason a single email message is displaying out of order is not in fact because of the date, but because of the order of the messages. I would like to modify my script to make sure all messages are in the correct order, but am unsure how to do this. Is it just based on the order in which the files appear, or is there a special part of the maildir headers which specify this?

Here is an example of what I mean: Example

In general, every MUA I use, including Thunderbird, Evolution and mail2web.com can order by date, but will be default order by the "message number". I am on a shared host which I believe uses qmail. The message number tag information must be kept somewhere.

edit: I tried moving all files to a temp directory and back again, which has shown that it is the file order which is responsible for the message number. I am however unsure as to why the messages from a few days in December have been moved to a much lower number than the numbers of messages on either side of those date. The filenames are timestamps and should be sequential, so unless mv movied the files in a strange order, I do not understand why the message numbers would not be restored for these particular files.

答:
With maildirs, there is no inherent order for the messages. The program that displays them can show them in the order it wishes, which may be random, but can also be based, for example, on the Date header.

Your example does not identify the program that shows them, and it's anybody's guess how it orders the mails. You need to figure out what it does and fix it to order the mails in the order you want.

EDIT: The Maildir specification may be useful for digging out. If your MTA actually creates unique filenames by putting reliable timestamps, you can perhaps make do with ordering by filename. Even such filenames aren't guaranteed, it may be good enough for you.

Title: changing maildir order


问:
Can't figure out how to read file from nmake
I am doing something like this:

```<code>all:
    @SET /p filecontent= < somefile.txt
    @echo %filecontent%
</code>```

However the filecontent variable does not seem to hold the contents of the file somefile.txt.

答:
Simply ensure somefile.txt is in acceptable nmake syntax, and then !include it. Thus:

```<code>c:>type somefile.txt
PASSWORD=secret
c:>type makefile
!INCLUDE somefile.txt
!MESSAGE Password is [$(PASSWORD)]
c:>nmake -nologo
Password is [secret]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am doing something like this:

all:
    @SET /p filecontent= < somefile.txt
    @echo %filecontent%

However the filecontent variable does not seem to hold the contents of the file somefile.txt.

Body:
Simply ensure somefile.txt is in acceptable nmake syntax, and then !include it. Thus:

c:>type somefile.txt
PASSWORD=secret
c:>type makefile
!INCLUDE somefile.txt
!MESSAGE Password is [$(PASSWORD)]
c:>nmake -nologo
Password is [secret]


问:
LDAP implementation in ALM, issue with existing users having DB authentication
The existing ALM implementation has users with DB authentication. How can the LDAP authentication implemented since ALM already have users and this will result in conflict while importing LDAP user list.</p>

答: While importing we will have option as Merge / Skip. If we select Merge then the ID will be merged and no conflicts will arise.</p>


问:
i need to combine unique keys and their values grouping as list in python
mylist=[{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]

i need like this

Heading

mylist=[{'apple':[1,3],'mango':[2,15],'orange':[0,10]}]

答:
Something like this??</p>

```<code>example = [{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]

new = {}
for d in example:
    for k,v in d.iteritems():
        new.setdefault(k, []).append(v)

print new
</code>```

Body:
Something like this??

example = [{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]

new = {}
for d in example:
    for k,v in d.iteritems():
        new.setdefault(k, []).append(v)

print new


问:
Conditional Argument Expansion in Function Call
I want to conditionally replace a single line in a file, depending on some pre-conditions and write the new content.
The way i choose was:

```<code>n_file = []
For line in file.getlines():
    n_file.append( line.replace(
            *("foo", "bar") if False else
            *("baz", "bam") if True else
            # ...
            *("", "") # no replacement
    ))
new_file.write(n_file)
</code>```

But i encoutered a Problem, that i dont understand.
The Problems are the asterisks. Whenever there are asterisks at the non-first position of the replace() function, it gives me a syntax error and i have absolutely no idea why.

You can try it for yourself. Its the same in Python 2 or 3.

```<code>def tf(a,b): print( str(a) +" "+ str(b) )

tf( *(1,1) if False else (2,2) if False else (3,3) )
# prints '3 3' as expec... intended

tf( *(1,1) if False else *(2,2) if False else *(3,3) )
# invalid syntax         ^

tf( (1,1) if False else (2,2) if False else (3,3) )
# missing 1 required positional argument: 'b'
</code>```

Though i found the solution for my particular problem. I still dont understand why it has to be that way.
My best guess is that it has something to do with the position of to-expand arguments but its still no explanation why the asteriks has to be at the first item only.

Kind regards.

ps.
This is my first question here and im not sure if the title is fitting (or how to specifically call this if-thingy, happening in replace()-args).
The search for answers about this problem was troublesome, so if u have a better title or tag suggestions, please let me know.

答:
You need to wrap the entire cascade of ternaries with parentheses so those are evaluated first, then proceed to unpack the result of the expression. The splat operator stays outside the parens:

```<code>tf( *((1,1) if False else (2,2) if False else (3,3)) ) #-> 3 3
</code>```

More specifically:

```<code>...
n_file.append( line.replace(
            **(("foo", "bar") if False else
               ("baz", "bam") if True else
                ...
               ("", "")) # no replacement
    ))
</code>```

OTOH, code gets quite unreadable when you're cascading ternaries like so. Would be more readable to use a vanilla if clause, assign to a variable and then unpack the variable.

Body:
I want to conditionally replace a single line in a file, depending on some pre-conditions and write the new content.
The way i choose was:

n_file = []
For line in file.getlines():
    n_file.append( line.replace(
            *("foo", "bar") if False else
            *("baz", "bam") if True else
            # ...
            *("", "") # no replacement
    ))
new_file.write(n_file)

But i encoutered a Problem, that i dont understand.
The Problems are the asterisks. Whenever there are asterisks at the non-first position of the replace() function, it gives me a syntax error and i have absolutely no idea why.

You can try it for yourself. Its the same in Python 2 or 3.

def tf(a,b): print( str(a) +" "+ str(b) )

tf( *(1,1) if False else (2,2) if False else (3,3) )
# prints '3 3' as expec... intended

tf( *(1,1) if False else *(2,2) if False else *(3,3) )
# invalid syntax         ^

tf( (1,1) if False else (2,2) if False else (3,3) )
# missing 1 required positional argument: 'b'

Though i found the solution for my particular problem. I still dont understand why it has to be that way.
My best guess is that it has something to do with the position of to-expand arguments but its still no explanation why the asteriks has to be at the first item only.

Kind regards.

ps.
This is my first question here and im not sure if the title is fitting (or how to specifically call this if-thingy, happening in replace()-args).
The search for answers about this problem was troublesome, so if u have a better title or tag suggestions, please let me know.

Body:
You need to wrap the entire cascade of ternaries with parentheses so those are evaluated first, then proceed to unpack the result of the expression. The splat operator stays outside the parens:

tf( *((1,1) if False else (2,2) if False else (3,3)) ) #-> 3 3

More specifically:

...
n_file.append( line.replace(
            **(("foo", "bar") if False else
               ("baz", "bam") if True else
                ...
               ("", "")) # no replacement
    ))

OTOH, code gets quite unreadable when you're cascading ternaries like so. Would be more readable to use a vanilla if clause, assign to a variable and then unpack the variable.


问:
Parse RSS Feeds or Websites Source Code
I would like to make an app in C#, where to generate some graphics about football teams, for the most important championships.
Ex: FC Barcelona, or Real Madrid... in Primera Division...

For this, I need the last updated data, from internet, about teams like, name of team, points, ranking...

Which is the most common way to do this?

Do I have to find a RSS Feed for this? Do you have any information about this?

Do I have to find a website and from there to parse its source code?

答:
If you could find the RSS feed for the information you want, that would be the best solution.

Otherwise, You could use the HTML Agility Pack, http://html-agility-pack.net/ (also available on NuGet). This makes it really easy to parse out relevant content from a messy html-page. You can (with some creative coding) write selectors that targets the content you want, on a dynamic site where the structure might change a bit. Really handy to get content of the web.

Title: Parse RSS Feeds or Websites Source Code


问:
Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code)
Visual Studio 2017 breaks in debug mode and displays the message:

Your app has entered a break state, but there is no code to show
  because all threads were executing external code (typically system or
  framework code).

The message is in the Break Mode Window.

What to do?

答: In my case I just need to restore the list of exception settings to the default settings.


问:
How to call javascript function from Django template tag
I'm trying to get the tab history length into url tag to pass it as parameter.
What I tried in template (and didn't work out) is this:

```<code><li><a href="{% url 'polls:load_zip' javascript:history.length %}">Query</a></li>
</code>```

I also tried to create a javascript function and call it from the url tag but it didn't work out as well:

```<code><script>
function history_len(){
    return history.length;
}
</script>
</code>```

and

```<code><li><a href="{% url 'polls:load_zip' history_len() %}">Query</a></li>
</code>```

Any suggestions?

答:
if you want to use anything like that in URL then you have to add URL hardcoded.

```<code><li><a class="ref_link" href="#">Query</a></li>

<script>
      $('.ref_link').attr("href",'/example/url'+history.length);
</script>
</code>```

you can use something like this.

Body:
I'm trying to get the tab history length into url tag to pass it as parameter.
What I tried in template (and didn't work out) is this:

Query

I also tried to create a javascript function and call it from the url tag but it didn't work out as well:

and

Query

Any suggestions?

Body:
if you want to use anything like that in URL then you have to add URL hardcoded.

<li><a class="ref_link" href="#">Query</a></li>

<script>
      $('.ref_link').attr("href",'/example/url'+history.length);
</script>

you can use something like this.


问:
Provide border if div has overflow text
What would be the best way to implement a design that want div-containers be provides with a border, if the content of the div causes vertical scroll of the div?

CSS

```<code>div {
  max-height: 100px;
  overflow-y: auto;
  // if content exceeds 100 px show border
  border: solid 1px;
}
</code>```

HTML

```<code><div>
   // Text ..
</div>
</code>```

答:
Set border if overflow.

var div = document.querySelector('div');
if (div.scrollHeight > div.clientHeight) {
  div.style.border = '1px solid';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  max-height: 100px;
  overflow-y: auto;
}</code>```

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Title: Provide border if div has overflow text

Body:
What would be the best way to implement a design that want div-containers be provides with a border, if the content of the div causes vertical scroll of the div?

CSS

div {
  max-height: 100px;
  overflow-y: auto;
  // if content exceeds 100 px show border
  border: solid 1px;
}

HTML

   // Text ..

Body:
Set border if overflow.

var div = document.querySelector('div');
if (div.scrollHeight > div.clientHeight) {
  div.style.border = '1px solid';
}

div {
  max-height: 100px;
  overflow-y: auto;
}

<div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
  eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>


答:
To drop duplicates, use df.distinct. To aggregate you first groupBy and then agg. Putting this all together:

case class Rating(userId: Int, movieId: Int, rating: Float)

def pRating(str: String): Rating = {
  val fields = str.split("::")
  assert(fields.size == 3)
  Rating(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/test/Desktop/test1.txt").map(pRating)
val totals = ratings.distinct
  .groupBy('userId, 'movieId)
  .agg(sum('rating).as("rating"))
  .as[Rating]
```

I am not sure you'd want the final result as Dataset[Rating] and whether the distinct and sum logic is exactly as you'd want it as the example in the question is not very clear but, hopefully, this will give you what you need.

Title: How to aggregate data in Spark using Scala?

Body:
To drop duplicates, use df.distinct. To aggregate you first groupBy and then agg. Putting this all together:

case class Rating(userId: Int, movieId: Int, rating: Float)

def pRating(str: String): Rating = {
  val fields = str.split("::")
  assert(fields.size == 3)
  Rating(fields(0).toInt, fields(1).toInt, fields(2).toFloat)
}

val ratings = spark.read.textFile("C:/Users/test/Desktop/test1.txt").map(pRating)
val totals = ratings.distinct
  .groupBy('userId, 'movieId)
  .agg(sum('rating).as("rating"))
  .as[Rating]

I am not sure you'd want the final result as Dataset[Rating] and whether the distinct and sum logic is exactly as you'd want it as the example in the question is not very clear but, hopefully, this will give you what you need.


问:
Android : Google Photos like Grid View with Zoom Functionality
I am using Recycle view and GridLayoutManager to display images in a grid.I would like to add functionality like Google photos where the Grid will be auto arranged and resizes images in Gridview when user pinch zooms.I am looking for sample code reference or procedure how to achieve it. TIA.</p>

答: I'm not sure if it's possible but the easiest way would be to create an ontouchlistener with pinch to zoom in the onBindViewHolder, you should also add android:clipToPadding="false" on the ImageView and all its parents & android:clipChildren="false" on all the parents.


问:
login to ssh and check ssh login of another server python

This code only logins to a server and checks the connection.

I need to login to a server, say (A) and check ssh login to server(B) and from (B) I need to check ssh for (C). Please help me to convert this code or a new one to do the above. TIA.

```<code>#!/usr/bin/python

import subprocess
import sys

HOST="MYIP"
COMMAND="uname -a"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result
print ("PASS")
</code>```

答:
What you want is something like the paramiko module

```<code>import sys, paramiko

if len(sys.argv) < 5:
    print "args missing"
    sys.exit(1)

hostname = sys.argv[1]
password = sys.argv[2]
source = sys.argv[3]
dest = sys.argv[4]

username = "YOUR USER NAME"
port = "YOUR PORT"

try:
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.get(source, dest)

finally:
    t.close()
</code>```

you can also pass cmd commands into it like

```<code>def sshCommand(host,port,user,pwd, commands):
sshClient = initSSHClient()
try:
    sshClient.connect(host,port,user,pwd)
    for command in commands:
        print(command)
        stdin, stdout, stderr = sshClient.exec_command(command)
    print(stdout.read())
    return 1
except:
    print("No Connection on port",port)
    return 0
</code>```

Where commands is a list of commands that should be executed (ls or chmod)

Body:
This code only logins to a server and checks the connection.

I need to login to a server, say (A) and check ssh login to server(B) and from (B) I need to check ssh for (C). Please help me to convert this code or a new one to do the above. TIA.

#!/usr/bin/python

import subprocess
import sys

HOST="MYIP"
COMMAND="uname -a"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result
print ("PASS")

Body:
What you want is something like the paramiko module

import sys, paramiko

if len(sys.argv) < 5:
    print "args missing"
    sys.exit(1)

hostname = sys.argv[1]
password = sys.argv[2]
source = sys.argv[3]
dest = sys.argv[4]

username = "YOUR USER NAME"
port = "YOUR PORT"

try:
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.get(source, dest)

finally:
    t.close()

you can also pass cmd commands into it like

def sshCommand(host,port,user,pwd, commands):
sshClient = initSSHClient()
try:
    sshClient.connect(host,port,user,pwd)
    for command in commands:
        print(command)
        stdin, stdout, stderr = sshClient.exec_command(command)
    print(stdout.read())
    return 1
except:
    print("No Connection on port",port)
    return 0

Where commands is a list of commands that should be executed (ls or chmod)


问:
Fatal error: Call to a member function bind_param() on a non-object using Update Query
I have just gotten into using premade statements to help with SQL protections.
My script checks to see if the User exists in the Users table and if it does already exist it runs:

```<code>$stmt = $Con->prepare("UPDATE `HA00`.`Users` SET `Unix` = ?,`4690` = ?,`LastIP` = ?,`LastLogin` = CURRENT_TIME( ) WHERE `Users`.`User` = ?;");

$stmt->bind_param('ssss',$PUnix,$P46,$IP,$PAD);
$PAD = $AD;
$PUnix = $Unix;
$IP = $_SERVER['REMOTE_ADDR'];
$P46 = $CTR;
$stmt->execute();
</code>```

If the user doesn't exist theirs is a nearly identical Insert SQL Query that works fine. I am positive I am missing something simple. I have checked the other pages but I am not finding the issue.

Edit:

"var_dump($stmt);" shows bool(false)

答:
It cant see parameters $PUnix,$P46,$IP,$PAD.

Try putting $stmt->bind_param('ssss',$PUnix,$P46,$IP,$PAD); below those variables.

Body:
I have just gotten into using premade statements to help with SQL protections.
My script checks to see if the User exists in the Users table and if it does already exist it runs:

$stmt = $Con->prepare("UPDATE `HA00`.`Users` SET `Unix` = ?,`4690` = ?,`LastIP` = ?,`LastLogin` = CURRENT_TIME( ) WHERE `Users`.`User` = ?;");

$stmt->bind_param('ssss',$PUnix,$P46,$IP,$PAD);
$PAD = $AD;
$PUnix = $Unix;
$IP = $_SERVER['REMOTE_ADDR'];
$P46 = $CTR;
$stmt->execute();

If the user doesn't exist theirs is a nearly identical Insert SQL Query that works fine. I am positive I am missing something simple. I have checked the other pages but I am not finding the issue.

Edit:

"var_dump($stmt);" shows bool(false)


问:
swap div when click button jquery
How can I use jquery to swap div , I want to if i click botton it'll desplay lay-out-sw and if I click en it should swap

In my html

```<code>    <div class="layout-sw">
sw
    </div>
    <div class="layout-en">
en
    </div>
     <div class="btn-group" role="group" aria-label="...">
      <button type="button" class="btn btn-info  btn-language btn-sw">SW</button>
      <button type="button" class="btn btn-default  btn-language btn-en">EN</button>
    </div>
</code>```

I use this jquery but i got some error

```<code><script type="text/javascript">
    $(function() {
        $('.layout-en').hide();
        $('.btn-language').on('click',function(e){
            $('.btn-language').removeClass('btn-info').addClass('btn-default');
            $(this).removeClass('btn-default').addClass('btn-info');
            $('.layout-sw,.layout-en').hide();
            ($(this).text()=='SW') ? $('.layout-sw').show() : $('.layout-en').show();
        })

        $('.btn-on-off').on('click',function(e){
            $(this).closest('.btn-on-off-widget').find('.btn-value').val($(this).attr('value'));
            $(this).next('.btn-on-off').removeClass('btn-primary btn-gray').addClass('btn-default');
            $(this).prev('.btn-on-off').removeClass('btn-primary btn-gray').addClass('btn-default');
            if($(this).attr('value')==0){
                $(this).removeClass('btn-default').addClass('btn-gray');

            }else{
                $(this).removeClass('btn-default').addClass('btn-primary');
            }
        })

    });

</script>
</code>```

答:
You can simply use show() and hide() function of jQuery as below.

$(document).ready(function() {
  $('.layout-en').hide();
  $('.btn-sw').click(function() {
    $('.layout-sw').show();
    $('.layout-en').hide();
  });
  $('.btn-en').click(function() {
    $('.layout-en').show();
    $('.layout-sw').hide();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="layout-sw">
  sw
</div>
<div class="layout-en">
  en
</div>
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-info  btn-language btn-sw">SW</button>
  <button type="button" class="btn btn-default  btn-language btn-en">EN</button>
</div></code>```

Title: swap div when click button jquery

Body:
How can I use jquery to swap div , I want to if i click botton it'll desplay lay-out-sw and if I click en it should swap

In my html

sw

en

      <button type="button" class="btn btn-info  btn-language btn-sw">SW</button>
      <button type="button" class="btn btn-default  btn-language btn-en">EN</button>

I use this jquery but i got some error

Body:
You can simply use show() and hide() function of jQuery as below.

$(document).ready(function() {
  $('.layout-en').hide();
  $('.btn-sw').click(function() {
    $('.layout-sw').show();
    $('.layout-en').hide();
  });
  $('.btn-en').click(function() {
    $('.layout-en').show();
    $('.layout-sw').hide();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="layout-sw">
  sw
</div>
<div class="layout-en">
  en
</div>
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-info  btn-language btn-sw">SW</button>
  <button type="button" class="btn btn-default  btn-language btn-en">EN</button>
</div>


问:
Redirect sys.stdout from ping results to a wx.TextCtrl widget
I'm trying to redirect the sys.stdout stream to a wx.TextCtrl widget. In this code, i used ping but how to redirect results to wx.textctrl or statictext widgets. I can send variable from my input to wx.statictext but not able to get the stdout from ping results. hope someone here can help.

I'm using python 3.6.0 with wx 2.8.12.1

```<code>import wx
import os

class RandomPanel(wx.Panel):

    def __init__(self, parent, color):

        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(color)

class MainPanel(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent)

        topSplitter = wx.SplitterWindow(self)
        vSplitter = wx.SplitterWindow(topSplitter)

        panelOne = RandomPanel(vSplitter, "white")

        self.txt = wx.TextCtrl(panelOne,
                    style=wx.TE_PROCESS_ENTER,
                    pos=(7, 8), size=(330, 30))
        self.txt.SetFocus()
        self.txt.Bind(wx.EVT_TEXT_ENTER, self.ping)

        panelTwo = RandomPanel(vSplitter, "white")
        vSplitter.SplitVertically(panelOne, panelTwo)
        vSplitter.SetSashGravity(0.5)

        panelThree = RandomPanel(topSplitter, "black")
        topSplitter.SplitHorizontally(vSplitter, panelThree)
        topSplitter.SetSashGravity(0.5)
        self.term = wx.StaticText(panelThree, -1, '', pos=(6, 100))
        self.term.SetForegroundColour((255, 255, 255))  #set font color
        self.term.SetBackgroundColour((0, 0, 0)) #set background color

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

    def ping(self, event):
        put = self.txt.GetValue()
        self.p = os.system("ping -n 1 "+put)
        self.term.SetLabel(put)
        self.p.AppendText('>>> ')
        self.p.AppendText(event)

class MainFrame(wx.Frame):

    def __init__(self):
           wx.Frame.__init__(self, None, title="ping tool",
                          size=(800, 600))
        panel = MainPanel(self)
        self.Show()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()
</code>```

答:
Replace import os with from subprocess import call, Popen, PIPE, STDOUT
Then replace

```<code>self.p = os.system("ping -n 1 "+put)
self.term.SetLabel(put)
self.p.AppendText('>>> ')
self.p.AppendText(event)
</code>```

with

```<code>comm = Popen(['ping',put],stdout=PIPE,stderr=STDOUT,universal_newlines=True)
for i in iter(comm.stdout.readline, b''):
    if i != '': pass
    else: break
    self.term.SetLabel(str(i))
    wx.Yield()
</code>```

This will read the output from the ping command, output it and then call Yield to allow the wx.App() mainloop to update the screen from within the for loop

You will probably want to put a stop mechanism in there at some point.

Edit:
To create a set of rolling results, I would change self.term from a StaticText to a TextCtrl

```<code>self.term = wx.TextCtrl(panelThree, -1, '',size=(400,200),style=wx.TE_MULTILINE)
</code>```

and then in the ping routine change SetLabel to AppendText

```<code>def ping(self, event):
    put = self.txt.GetValue()
    comm = Popen(['ping',put],stdout=PIPE,stderr=STDOUT,universal_newlines=True)
    for i in iter(comm.stdout.readline, b''):
        if i != '': pass
        else: break
        self.term.AppendText(str(i))
        wx.Yield()
</code>```

Body:
I'm trying to redirect the sys.stdout stream to a wx.TextCtrl widget. In this code, i used ping but how to redirect results to wx.textctrl or statictext widgets. I can send variable from my input to wx.statictext but not able to get the stdout from ping results. hope someone here can help.

I'm using python 3.6.0 with wx 2.8.12.1

import wx
import os

class RandomPanel(wx.Panel):

    def __init__(self, parent, color):

        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(color)

class MainPanel(wx.Panel):

    def __init__(self, parent):

        wx.Panel.__init__(self, parent)

        topSplitter = wx.SplitterWindow(self)
        vSplitter = wx.SplitterWindow(topSplitter)

        panelOne = RandomPanel(vSplitter, "white")

        self.txt = wx.TextCtrl(panelOne,
                    style=wx.TE_PROCESS_ENTER,
                    pos=(7, 8), size=(330, 30))
        self.txt.SetFocus()
        self.txt.Bind(wx.EVT_TEXT_ENTER, self.ping)

        panelTwo = RandomPanel(vSplitter, "white")
        vSplitter.SplitVertically(panelOne, panelTwo)
        vSplitter.SetSashGravity(0.5)

        panelThree = RandomPanel(topSplitter, "black")
        topSplitter.SplitHorizontally(vSplitter, panelThree)
        topSplitter.SetSashGravity(0.5)
        self.term = wx.StaticText(panelThree, -1, '', pos=(6, 100))
        self.term.SetForegroundColour((255, 255, 255))  #set font color
        self.term.SetBackgroundColour((0, 0, 0)) #set background color

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

    def ping(self, event):
        put = self.txt.GetValue()
        self.p = os.system("ping -n 1 "+put)
        self.term.SetLabel(put)
        self.p.AppendText('>>> ')
        self.p.AppendText(event)

class MainFrame(wx.Frame):

    def __init__(self):
           wx.Frame.__init__(self, None, title="ping tool",
                          size=(800, 600))
        panel = MainPanel(self)
        self.Show()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

Body:
Replace import os with from subprocess import call, Popen, PIPE, STDOUT
Then replace

self.p = os.system("ping -n 1 "+put)
self.term.SetLabel(put)
self.p.AppendText('>>> ')
self.p.AppendText(event)

with

comm = Popen(['ping',put],stdout=PIPE,stderr=STDOUT,universal_newlines=True)
for i in iter(comm.stdout.readline, b''):
    if i != '': pass
    else: break
    self.term.SetLabel(str(i))
    wx.Yield()

This will read the output from the ping command, output it and then call Yield to allow the wx.App() mainloop to update the screen from within the for loop

You will probably want to put a stop mechanism in there at some point.

Edit:
To create a set of rolling results, I would change self.term from a StaticText to a TextCtrl

self.term = wx.TextCtrl(panelThree, -1, '',size=(400,200),style=wx.TE_MULTILINE)

and then in the ping routine change SetLabel to AppendText

def ping(self, event):
    put = self.txt.GetValue()
    comm = Popen(['ping',put],stdout=PIPE,stderr=STDOUT,universal_newlines=True)
    for i in iter(comm.stdout.readline, b''):
        if i != '': pass
        else: break
        self.term.AppendText(str(i))
        wx.Yield()


问:
Fetching multiple rows by foreign key column
I have an Address table that contains multiple addresses

```<code>Address:
| Id   |   details   | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |    ...        |
| 2    |  details |    ...        |
| 3    |  details |    ...        |
| 4    |  details |    ...        |
</code>```

Then i have a site table, that contains address.id as FK to represent Billing or Shipping address,

```<code>Site:
| Id   |   details   | Ship_Address_id  |  Bill_Address_id | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |          1           |        2          |     |
| 2    |  details |          1           |        3          |     |
| 3    |  details |          4           |        4          |     |
| 4    |  details |          2           |        3          |     |
</code>```

is there a way to join both the tables so that single row from site table may fetch two rows of address table, even in the case of same address of both columns.
i was expecting to use multiple join of site with address but that is not working:

This is what i tried:

```<code>SELECT CASE
        WHEN ship.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Ship'
        WHEN bill.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Bill'
        ELSE '' END
FROM Address as Adr
LEFT JOIN Site ship ON ship.Ship_Address_id = Adr.id
LEFT JOIN Site bill ON bill.Bill_Address_id = Adr.id
</code>```

Even if i don't use the CASE it does not fetch two rows for each address with respect to site.

Please advise.

EDIT
Here is the desired output table:
as in Site table we have two different ids of address table (Ship/Bill) so the result table should display two rows for each site.id

for example i'm fetching records for site.id 1 and 3 then

```<code>Result_Table:
| Address.ID | Address Details | TYPE | ... |
--------------------------------------------
| 1         | Other Details    | Ship | ... |
| 2         | Other Details    | Bill | ... |
| 4         | Other Details    | Ship | ... |
| 4         | Other Details    | Bill | ... |
</code>```

答:
It looks as though you're looking for UNION ALL, and also that your tables are backwards. I think you're looking for something more like this:

```<code>SELECT ship.id Site_id, CASE
        WHEN ship.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Ship'
        ELSE 'No Ship' END AddressPresent
FROM Site ship
LEFT JOIN Address Adr ON ship.Ship_Address_id = Adr.id

UNION ALL

SELECT bill.id Site_id, CASE
        WHEN bill.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Bill'
        ELSE 'No Bill' END AddressPresent
FROM Site bill
LEFT JOIN Address Adr ON bill.Bill_Address_id = Adr.id
</code>```

I'm also wondering if you have a 'CRM_Address_Internal_Id_Bill' column that should be in the second part of the query?

Body:
I have an Address table that contains multiple addresses

Address:
| Id   |   details   | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |    ...        |
| 2    |  details |    ...        |
| 3    |  details |    ...        |
| 4    |  details |    ...        |

Then i have a site table, that contains address.id as FK to represent Billing or Shipping address,

Site:
| Id   |   details   | Ship_Address_id  |  Bill_Address_id | ... |
 - - - - - - - - -  - - - - - - -
| 1    |  details |          1           |        2          |     |
| 2    |  details |          1           |        3          |     |
| 3    |  details |          4           |        4          |     |
| 4    |  details |          2           |        3          |     |

is there a way to join both the tables so that single row from site table may fetch two rows of address table, even in the case of same address of both columns.
i was expecting to use multiple join of site with address but that is not working:

This is what i tried:

SELECT CASE
        WHEN ship.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Ship'
        WHEN bill.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Bill'
        ELSE '' END
FROM Address as Adr
LEFT JOIN Site ship ON ship.Ship_Address_id = Adr.id
LEFT JOIN Site bill ON bill.Bill_Address_id = Adr.id

Even if i don't use the CASE it does not fetch two rows for each address with respect to site.

Please advise.

EDIT
Here is the desired output table:
as in Site table we have two different ids of address table (Ship/Bill) so the result table should display two rows for each site.id

for example i'm fetching records for site.id 1 and 3 then

Result_Table:
| Address.ID | Address Details | TYPE | ... |
--------------------------------------------
| 1         | Other Details    | Ship | ... |
| 2         | Other Details    | Bill | ... |
| 4         | Other Details    | Ship | ... |
| 4         | Other Details    | Bill | ... |

Body:
It looks as though you're looking for UNION ALL, and also that your tables are backwards. I think you're looking for something more like this:

SELECT ship.id Site_id, CASE
        WHEN ship.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Ship'
        ELSE 'No Ship' END AddressPresent
FROM Site ship
LEFT JOIN Address Adr ON ship.Ship_Address_id = Adr.id

UNION ALL

SELECT bill.id Site_id, CASE
        WHEN bill.CRM_Address_Internal_Id_Ship IS NOT NULL THEN 'Bill'
        ELSE 'No Bill' END AddressPresent
FROM Site bill
LEFT JOIN Address Adr ON bill.Bill_Address_id = Adr.id

I'm also wondering if you have a 'CRM_Address_Internal_Id_Bill' column that should be in the second part of the query?


答:
I think that using Python for this specific task will not be the best.

Therefore I suggest you to use this simple bash script:

```<code>ssh -q user@server exit
result=$(echo $?)

if [ $result -eq 0 ]; then
    echo "ok"
else
    echo "ko"
fi
</code>```

Save this script on Server A and then +x and run it:

```<code>ssh user@serverB ssh user@serverC exit
result=$(echo $?)

if [ $result -eq 0 ]; then
    echo "ok"
else
    echo "ko"
fi
</code>```

Title: login to ssh and check ssh login of another server python

Body:
I think that using Python for this specific task will not be the best.

Therefore I suggest you to use this simple bash script:

ssh -q user@server exit
result=$(echo $?)

if [ $result -eq 0 ]; then
    echo "ok"
else
    echo "ko"
fi

Save this script on Server A and then +x and run it:

ssh user@serverB ssh user@serverC exit
result=$(echo $?)

if [ $result -eq 0 ]; then
    echo "ok"
else
    echo "ko"
fi


问:
Query Parameter in retrofit with ? in android google maps
I have problem with retrofit when I use query parameter in retrofit to access link url like first link and I got the link url like second link url https://maps.googleapis.com/maps/api/geocode/json?latlng=11.531887,104.937726

https://maps.googleapis.com/maps/api/geocode/json?geocode=json&latlng=11.531887,104.937726

```<code>public interface AddressService{
        @GET("geocode/json")
        Call<AddressResponse> getAddressWithCoordinator(@Query("latlng") String latlng);
}
</code>```

Thank u!

答:
Create a class of latlong

```<code>class LatLng {
  private double lat;
  private double lng;

  @Override public String toString() {
    return String.format("%.1f,%.1f", lat, lng);
  }
}
</code>```

Service like

```<code>public interface AddressService{
    @GET("geocode/json")
    Call<AddressResponse> getAddressWithCoordinator(@Query("latlng") LatLng latlng);
}
</code>```

Call request

```<code>Call<AddressResponse> requestCall =  restAdapter.getAddressWithCoordinator(LatLng.valueOf(31.26, -94.74));
</code>```

Model Should look like

```<code>import com.google.gson.annotations.SerializedName;

import java.util.List;

public class AddressResponse{

    @SerializedName("results")
    private List<ResultsItem> results;

    @SerializedName("status")
    private String status;

    public void setResults(List<ResultsItem> results){
        this.results = results;
    }

    public List<ResultsItem> getResults(){
        return results;
    }

    public void setStatus(String status){
        this.status = status;
    }

    public String getStatus(){
        return status;
    }

    public class AddressComponentsItem{

        @SerializedName("types")
        private List<String> types;

        @SerializedName("short_name")
        private String shortName;

        @SerializedName("long_name")
        private String longName;

        public void setTypes(List<String> types){
            this.types = types;
        }

        public List<String> getTypes(){
            return types;
        }

        public void setShortName(String shortName){
            this.shortName = shortName;
        }

        public String getShortName(){
            return shortName;
        }

        public void setLongName(String longName){
            this.longName = longName;
        }

        public String getLongName(){
            return longName;
        }
    }

    public class Geometry{

        @SerializedName("viewport")
        private Viewport viewport;

        @SerializedName("location")
        private Location location;

        @SerializedName("location_type")
        private String locationType;

        public void setViewport(Viewport viewport){
            this.viewport = viewport;
        }

        public Viewport getViewport(){
            return viewport;
        }

        public void setLocation(Location location){
            this.location = location;
        }

        public Location getLocation(){
            return location;
        }

        public void setLocationType(String locationType){
            this.locationType = locationType;
        }

        public String getLocationType(){
            return locationType;
        }
    }

    public class Location{

        @SerializedName("lng")
        private double lng;

        @SerializedName("lat")
        private double lat;

        public void setLng(double lng){
            this.lng = lng;
        }

        public double getLng(){
            return lng;
        }

        public void setLat(double lat){
            this.lat = lat;
        }

        public double getLat(){
            return lat;
        }
    }

    public class ResultsItem{

        @SerializedName("formatted_address")
        private String formattedAddress;

        @SerializedName("types")
        private List<String> types;

        @SerializedName("geometry")
        private Geometry geometry;

        @SerializedName("address_components")
        private List<AddressComponentsItem> addressComponents;

        @SerializedName("place_id")
        private String placeId;

        public void setFormattedAddress(String formattedAddress){
            this.formattedAddress = formattedAddress;
        }

        public String getFormattedAddress(){
            return formattedAddress;
        }

        public void setTypes(List<String> types){
            this.types = types;
        }

        public List<String> getTypes(){
            return types;
        }

        public void setGeometry(Geometry geometry){
            this.geometry = geometry;
        }

        public Geometry getGeometry(){
            return geometry;
        }

        public void setAddressComponents(List<AddressComponentsItem> addressComponents){
            this.addressComponents = addressComponents;
        }

        public List<AddressComponentsItem> getAddressComponents(){
            return addressComponents;
        }

        public void setPlaceId(String placeId){
            this.placeId = placeId;
        }

        public String getPlaceId(){
            return placeId;
        }
    }

    public class Viewport{

        @SerializedName("southwest")
        private Location southwest;

        @SerializedName("northeast")
        private Location northeast;

        public void setSouthwest(Location southwest){
            this.southwest = southwest;
        }

        public Location getSouthwest(){
            return southwest;
        }

        public void setNortheast(Location northeast){
            this.northeast = northeast;
        }

        public Location getNortheast(){
            return northeast;
        }
    }

}
</code>```

Body:
I have problem with retrofit when I use query parameter in retrofit to access link url like first link and I got the link url like second link url https://maps.googleapis.com/maps/api/geocode/json?latlng=11.531887,104.937726

https://maps.googleapis.com/maps/api/geocode/json?geocode=json&latlng=11.531887,104.937726

public interface AddressService{
        @GET("geocode/json")
        Call<AddressResponse> getAddressWithCoordinator(@Query("latlng") String latlng);
}

Thank u!

Body:
Create a class of latlong

class LatLng {
  private double lat;
  private double lng;

  @Override public String toString() {
    return String.format("%.1f,%.1f", lat, lng);
  }
}

Service like

public interface AddressService{
    @GET("geocode/json")
    Call<AddressResponse> getAddressWithCoordinator(@Query("latlng") LatLng latlng);
}

Call request

Call<AddressResponse> requestCall =  restAdapter.getAddressWithCoordinator(LatLng.valueOf(31.26, -94.74));

Model Should look like

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class AddressResponse{

    @SerializedName("results")
    private List<ResultsItem> results;

    @SerializedName("status")
    private String status;

    public void setResults(List<ResultsItem> results){
        this.results = results;
    }

    public List<ResultsItem> getResults(){
        return results;
    }

    public void setStatus(String status){
        this.status = status;
    }

    public String getStatus(){
        return status;
    }

    public class AddressComponentsItem{

        @SerializedName("types")
        private List<String> types;

        @SerializedName("short_name")
        private String shortName;

        @SerializedName("long_name")
        private String longName;

        public void setTypes(List<String> types){
            this.types = types;
        }

        public List<String> getTypes(){
            return types;
        }

        public void setShortName(String shortName){
            this.shortName = shortName;
        }

        public String getShortName(){
            return shortName;
        }

        public void setLongName(String longName){
            this.longName = longName;
        }

        public String getLongName(){
            return longName;
        }
    }

    public class Geometry{

        @SerializedName("viewport")
        private Viewport viewport;

        @SerializedName("location")
        private Location location;

        @SerializedName("location_type")
        private String locationType;

        public void setViewport(Viewport viewport){
            this.viewport = viewport;
        }

        public Viewport getViewport(){
            return viewport;
        }

        public void setLocation(Location location){
            this.location = location;
        }

        public Location getLocation(){
            return location;
        }

        public void setLocationType(String locationType){
            this.locationType = locationType;
        }

        public String getLocationType(){
            return locationType;
        }
    }

    public class Location{

        @SerializedName("lng")
        private double lng;

        @SerializedName("lat")
        private double lat;

        public void setLng(double lng){
            this.lng = lng;
        }

        public double getLng(){
            return lng;
        }

        public void setLat(double lat){
            this.lat = lat;
        }

        public double getLat(){
            return lat;
        }
    }

    public class ResultsItem{

        @SerializedName("formatted_address")
        private String formattedAddress;

        @SerializedName("types")
        private List<String> types;

        @SerializedName("geometry")
        private Geometry geometry;

        @SerializedName("address_components")
        private List<AddressComponentsItem> addressComponents;

        @SerializedName("place_id")
        private String placeId;

        public void setFormattedAddress(String formattedAddress){
            this.formattedAddress = formattedAddress;
        }

        public String getFormattedAddress(){
            return formattedAddress;
        }

        public void setTypes(List<String> types){
            this.types = types;
        }

        public List<String> getTypes(){
            return types;
        }

        public void setGeometry(Geometry geometry){
            this.geometry = geometry;
        }

        public Geometry getGeometry(){
            return geometry;
        }

        public void setAddressComponents(List<AddressComponentsItem> addressComponents){
            this.addressComponents = addressComponents;
        }

        public List<AddressComponentsItem> getAddressComponents(){
            return addressComponents;
        }

        public void setPlaceId(String placeId){
            this.placeId = placeId;
        }

        public String getPlaceId(){
            return placeId;
        }
    }

    public class Viewport{

        @SerializedName("southwest")
        private Location southwest;

        @SerializedName("northeast")
        private Location northeast;

        public void setSouthwest(Location southwest){
            this.southwest = southwest;
        }

        public Location getSouthwest(){
            return southwest;
        }

        public void setNortheast(Location northeast){
            this.northeast = northeast;
        }

        public Location getNortheast(){
            return northeast;
        }
    }

}


问:
Angularjs 1.5 localstorage getting overwrite when i open application in new tab with some other credentials
In angularjs 1.5 I have used local storage to store session related information.
But when I open new tab with some other credentials, initial information is getting erased and getting replaced by the new one, is there any way to prevent this ?</p>

答:
Since you didn't provide any code sample it's hard to tell what is going on, but i guess when the app starts you set some value to localstorage, so each time you open a new tab you set it again and override the previous value.

All you need to do is check if the value exists in localstorage and if it does do nothing:

```<code>if (!localStorage.getItem('myItem')){
      localStorage.setItem('myItem', myValue));
}
</code>```

Body:
Since you didn't provide any code sample it's hard to tell what is going on, but i guess when the app starts you set some value to localstorage, so each time you open a new tab you set it again and override the previous value.

All you need to do is check if the value exists in localstorage and if it does do nothing:

if (!localStorage.getItem('myItem')){
      localStorage.setItem('myItem', myValue));
}


问:
How to get a list of tuple from freqDist in nltk
I have a dataframe with two column id and text

I want to add a new column that contains word count for the text per row.

I create a userdefinedFunction in which i implement word_tokenizer and freqDict from nltk

```<code>word = f.udf(lambda token: word_count)

def word_count(token):
    freq_dict = nltk.probability.FreqDist(token)
    return [(word, freq) for word, freq in freq_dict.most_common()]

df = df.withColumn('wordcount',word(nltk.word_tokenize(df['text']))
</code>```

After tokenizer i call word_count and hope to get a list of tuple with word and its freq. but instead in get this in the column

```<code>[[Ljava.lang.Object;@9b4c4d5, [Ljava.lang.Object;@6a5d7d39, ...
</code>```

答:
You need to specify the return type for the UDF.
Define a schema like this

```<code>schema = ArrayType(StructType([StructField("word",StringType(), True), StructField("freq",LongType(), True)]))
</code>```

and change the udf to

```<code>f.udf(word_count, schema)
</code>```

Body:
I have a dataframe with two column id and text

I want to add a new column that contains word count for the text per row.

I create a userdefinedFunction in which i implement word_tokenizer and freqDict from nltk

word = f.udf(lambda token: word_count)

def word_count(token):
    freq_dict = nltk.probability.FreqDist(token)
    return [(word, freq) for word, freq in freq_dict.most_common()]

df = df.withColumn('wordcount',word(nltk.word_tokenize(df['text']))

After tokenizer i call word_count and hope to get a list of tuple with word and its freq. but instead in get this in the column

[[Ljava.lang.Object;@9b4c4d5, [Ljava.lang.Object;@6a5d7d39, ...

Body:
You need to specify the return type for the UDF.
Define a schema like this

schema = ArrayType(StructType([StructField("word",StringType(), True), StructField("freq",LongType(), True)]))

and change the udf to

f.udf(word_count, schema)


问:
How to get no error, if a String value is entered or the number not related to the cases
How to get no error, if a String value is entered or the number not related to the cases.</p>

```<code>switch(optionIssues) {
   case 1 : healthIssues = "Dental Problem"; ;break;
   case 2 : healthIssues = "Respiratory Diphtheria";;break;
   case 3 : healthIssues = "Mosquitoes Infections";;break;
}
</code>```

答:
You can prevent errors if an String is entered by reading the option as a String or by catching the exception like as following:

```<code>int optionIssues;
try {
    optionIssues = new Scanner(System.in).nextInt();
}
catch (Exception e) {
    optionIssues = 0;
}
</code>```

And anyway, you should have a default case in your switch:

```<code>switch(optionIssues){
    case 1 : healthIssues = "Dental Problem"; break;
    case 2 : healthIssues = "Respiratory Diphtheria"; break;
    case 3 : healthIssues = "Mosquitoes Infections"; break;
    default: System.out.println("Invalid option.");
}
</code>```

Body:
How to get no error, if a String value is entered or the number not related to the cases.

switch(optionIssues) {
   case 1 : healthIssues = "Dental Problem"; ;break;
   case 2 : healthIssues = "Respiratory Diphtheria";;break;
   case 3 : healthIssues = "Mosquitoes Infections";;break;
}

Body:
You can prevent errors if an String is entered by reading the option as a String or by catching the exception like as following:

int optionIssues;
try {
    optionIssues = new Scanner(System.in).nextInt();
}
catch (Exception e) {
    optionIssues = 0;
}

And anyway, you should have a default case in your switch:

switch(optionIssues){
    case 1 : healthIssues = "Dental Problem"; break;
    case 2 : healthIssues = "Respiratory Diphtheria"; break;
    case 3 : healthIssues = "Mosquitoes Infections"; break;
    default: System.out.println("Invalid option.");
}


问:
How not to compile casting into enum type in C++?
I have this "better" enum class that

cannot contain invalid values, and

cannot be used until enum value is not set explicitly,

as follows:

```<code>class Symmetry
{
    public:
        enum Type {
            GENERAL, SYMMETRIC, HERMITIAN,
            SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
        };

        Symmetry() { t_ = UNINITIALIZED }
        explicit Symmetry(Type t) : t_(t) { checkArg(t); }
        Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }

        operator Type() const {
            if (t_ == UNINITIALIZED) throw runtime_error("error");
            return t_;
        }

    private:
        Type t_;

        void checkArg(Type t) {
            if ((unsigned)t >= (unsigned)UNINITIALIZED)
                throw runtime_error("error");
        }
};
</code>```

This allows me to write the following code:

```<code>Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws
</code>```

My problem is that a compiler allows constructs such as:

```<code>Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws
</code>```

I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?

答:
My attempt using templates: (tested. However, this can be further improved!)

```<code>template<int N>
struct Symmetry
{
    enum Type
    {
        GENERAL, SYMMETRIC, HERMITIAN,
        SKEW_SYMMETRIC, SKEW_HERMITIAN
    };
    template<Type e> struct allowed;
    template<> struct allowed<GENERAL>        { static const int value = GENERAL; };
    template<> struct allowed<SYMMETRIC>      { static const int value = SYMMETRIC; };
    template<> struct allowed<HERMITIAN>      { static const int value = HERMITIAN; };
    template<> struct allowed<SKEW_SYMMETRIC> { static const int value = SKEW_SYMMETRIC; };
    template<> struct allowed<SKEW_HERMITIAN> { static const int value = SKEW_HERMITIAN; };

    allowed<(Type)N> m_allowed;

    operator int()
    {
        return N;
    }
};

Symmetry<0> e0;                   //okay
Symmetry<1> e1;                   //okay
Symmetry<100> e4;                 //compilation error!
Symmetry<e0.SKEW_HERMITIAN> e3;   //okay
Symmetry<e0.SKEW_SYMMETRIC> e3;   //okay
</code>```

Usage:

```<code>int main()
{
    Symmetry<0> e0;
    Symmetry<e0.HERMITIAN> e1;

    switch (e1)
    {
    case e0.HERMITIAN:
        {
            cout << "It's working" << endl;
        }
        break;
    }
}
</code>```

Body:
I have this "better" enum class that

cannot contain invalid values, and

cannot be used until enum value is not set explicitly,

as follows:

class Symmetry
{
    public:
        enum Type {
            GENERAL, SYMMETRIC, HERMITIAN,
            SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
        };

        Symmetry() { t_ = UNINITIALIZED }
        explicit Symmetry(Type t) : t_(t) { checkArg(t); }
        Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }

        operator Type() const {
            if (t_ == UNINITIALIZED) throw runtime_error("error");
            return t_;
        }

    private:
        Type t_;

        void checkArg(Type t) {
            if ((unsigned)t >= (unsigned)UNINITIALIZED)
                throw runtime_error("error");
        }
};

This allows me to write the following code:

Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws

My problem is that a compiler allows constructs such as:

Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws

I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?

Body:
My attempt using templates: (tested. However, this can be further improved!)

template<int N>
struct Symmetry
{
    enum Type
    {
        GENERAL, SYMMETRIC, HERMITIAN,
        SKEW_SYMMETRIC, SKEW_HERMITIAN
    };
    template<Type e> struct allowed;
    template<> struct allowed<GENERAL>        { static const int value = GENERAL; };
    template<> struct allowed<SYMMETRIC>      { static const int value = SYMMETRIC; };
    template<> struct allowed<HERMITIAN>      { static const int value = HERMITIAN; };
    template<> struct allowed<SKEW_SYMMETRIC> { static const int value = SKEW_SYMMETRIC; };
    template<> struct allowed<SKEW_HERMITIAN> { static const int value = SKEW_HERMITIAN; };

    allowed<(Type)N> m_allowed;

    operator int()
    {
        return N;
    }
};

Symmetry<0> e0;                   //okay
Symmetry<1> e1;                   //okay
Symmetry<100> e4;                 //compilation error!
Symmetry<e0.SKEW_HERMITIAN> e3;   //okay
Symmetry<e0.SKEW_SYMMETRIC> e3;   //okay

Usage:

int main()
{
    Symmetry<0> e0;
    Symmetry<e0.HERMITIAN> e1;

    switch (e1)
    {
    case e0.HERMITIAN:
        {
            cout << "It's working" << endl;
        }
        break;
    }
}


问:
Can not delete User with FOSOAuthBundle enabled
I try to delete a user in my symfony 3 app. I use the FOSOAuthBundle and the FOSUserBundle.

I tried this code:

```<code>$em = $this->getDoctrine()->getManager();
$em->remove($user);
$em->flush();
</code>```

But I get this error:

```<code>An exception occurred while executing 'DELETE FROM user WHERE id = ?' with params [1]:\n\nSQLSTATE[23000]:
Integrity constraint violation: 1451 Cannot delete or update a parent row:
a foreign key constraint fails (`database`.`access_token`, CONSTRAINT `FK_B6A2DD68A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))
</code>```

I have this configuration:

```<code># FOSOAuthServerBundle configuration
fos_oauth_server:
    db_driver: orm
    client_class: OAuthBundle\Entity\Client
    access_token_class: OAuthBundle\Entity\AccessToken
    refresh_token_class: OAuthBundle\Entity\RefreshToken
    auth_code_class: OAuthBundle\Entity\AuthCode
    service:
        user_provider: fos_user.user_provider.username_email
        options:
            access_token_lifetime: 86400
            refresh_token_lifetime: 2.628e+6
</code>```

If I get a access token the user field is always null though in the database the correct id is saved and it is possible to login with this token.

答:
YOu need to configure cascade operations. You need to decide what do you want to happen on access_token table when you delete an user. You can delete de token or set the related user as null.

More info here

Body:
I try to delete a user in my symfony 3 app. I use the FOSOAuthBundle and the FOSUserBundle.

I tried this code:

$em = $this->getDoctrine()->getManager();
$em->remove($user);
$em->flush();

But I get this error:

An exception occurred while executing 'DELETE FROM user WHERE id = ?' with params [1]:\n\nSQLSTATE[23000]:
Integrity constraint violation: 1451 Cannot delete or update a parent row:
a foreign key constraint fails (`database`.`access_token`, CONSTRAINT `FK_B6A2DD68A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`))

I have this configuration:

# FOSOAuthServerBundle configuration
fos_oauth_server:
    db_driver: orm
    client_class: OAuthBundle\Entity\Client
    access_token_class: OAuthBundle\Entity\AccessToken
    refresh_token_class: OAuthBundle\Entity\RefreshToken
    auth_code_class: OAuthBundle\Entity\AuthCode
    service:
        user_provider: fos_user.user_provider.username_email
        options:
            access_token_lifetime: 86400
            refresh_token_lifetime: 2.628e+6

If I get a access token the user field is always null though in the database the correct id is saved and it is possible to login with this token.