问:
Is it crazy to use Azure for Intranet Site containing sensitive data
is it absolute insanity to start hosting new intranet web apps in Azure using an on-premise sql instance and ADFS 2.0 (via Azure Connect)? My concern is that instead of the site being behind a firewall, being hosted in Azure has the side effect of anyone who discovers the URL can hack away at it.

Thoughts???

thanks

答:
Do their trial.... and see how fast you can get up to speed with locking the security down.  Hey, at least your not asking about Amazon's Cloud.  Don't do it because it is the cool thing to do.  Research the pro's and con's.  Gmail is a cloud based Email service that I and many have used for years.  All in all it works pretty well.  The future is more cloud, where more businesses have dumb terminals with virtual use of cloud services.  The personal pc is bound to become make less important.

Microsoft has invested a lot into Azure, if you follow their security guidelines you should be just fine.


来源: stackexchange

问:
Outlook VSTO Add-in not visible in Outlook
I have an Outlook Add-in(under development) which was working fine on my old system. I decided to migrate to a new system(for better performance), when I have done so(IN DEBUG MODE), I saw that after some time the Add-in is not visible in Outlook(neither in COM AND disabled window).

Specifications I am using:

System type is 64-bit OS, x64-based processor

Microsoft Visual Studio Community 2019 Version 16.5 with .NET framework 4.7.2

Microsoft Office 365(16.012730.20144) 32-bit

Troubleshoots I tried:

1) Checked Build Office solutions, for verifying all items are generating and working properly.

Registry entry is generating correctly.

VSTO file(bin/debug) is getting installed successfully(when I manually double click that)

2) Troubleshooting by Event Viewer:

No error's related to Outlook(as a source).

Possibly related error's:

i) Source - DistributedCOM : The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
{6B3B8D23-FA8D-40B9-8DBD-B950333E2C52}
 and APPID
{4839DDB7-58C2-48F5-8283-E1D1807D0D7D}
 to the user NT AUTHORITY\LOCAL SERVICE SID (S-1-5-19) from address LocalHost (Using LRPC) running in the application container Unavailable SID (Unavailable). This security permission can be modified using the Component Services administrative tool.

ii) Other Errors are from source PerfNet and NDIS(Which I suppose is not related to this topic)

3) Troubleshooting by Process Explorer:

Their is no outlook Add-in DLL present in process explorer.

4) Troubleshooting by Process Monitor:

I am new with procmon, so just used some basics like, applied a filter with Outlook process name(including registry, file system, Network, process and thread activities).
And the results were SUCCESS, BUFFER TOO SMALL, NAME NOT FOUND, NO MORE ENTERIES other. Their was nothing I can relate with my issue.

Other Information

After this issue, I made a same new project and it worked fine, but the same happened(Add-in not visible) after some time. And I have done this(Created new project) four times till now. What I observed is, when I create a new Add-in with same name, the issue is same, so I have to choose different name every-time.

I am not able to find any error description for this. So can anybody please tell me what is the issue here OR how I can troubleshoot more(with above tools or new one).

Thanks in advance.

答:
If you don't see your add-in listed in the COM add-ins dialog of Office applications, the problem is related to Windows registry keys required. Read more about them in the Registry entries for VSTO Add-ins article.

It seems something is wrong with your add-in registry entries (maybe permissions). And the issue can be related to Windows/Office bitness. Most probably you had another Office edition (bitness) installed on the old system (or Windows).

ContentLicense: CC BY-SA 4.0


问:
How to convert format list to json in output child process nodejs?
I have an output from running a python script from child process nodejs, and output of python script is array tolist() and i want convert to json with status response like this output array:

```<code>[
    759864000,
    740308000,
    724748000,
    725208000,
    729592000,
    732272000,
    728356000,
    728452000,
    724544000,
    720584000,
    716880000,
    709264000,
    712784000
]
</code>```

to json with status response like this :

```<code>{
    "status": true,
    "message": "",
    "data": [
        759864000,
        740308000,
        724748000,
        725208000,
        729592000,
        732272000,
        728356000,
        728452000,
        724544000,
        720584000,
        716880000,
        709264000,
        712784000
    ]
}
</code>```

I have used this method to change to json :

```<code>coba: async(req, res)=>{
      var spawn = require("child_process").spawn;
      var process = spawn('python',["./coba.py"]);
      process.stdout.on('data', function(data) {
          console.log(data);
          // res.send(data.toString());
          res.send(JSON.parse(data.toString()));
          // res.send(JSON.stringify(data.toString()));
      } )
      process.stderr.on('data', (data) => {
          console.log(`error:${data}`);
      });
       process.stderr.on('close', () => {
          console.log("Closed");
       });},
</code>```

Can you help me with this? thanks..

答:
May you should try
res.json({status: true,
    message: "",
    data}) ;

instead of:
res.send(JSON.parse(data.toString()))

Body:
I have an output from running a python script from child process nodejs, and output of python script is array tolist() and i want convert to json with status response like this output array:

[
    759864000,
    740308000,
    724748000,
    725208000,
    729592000,
    732272000,
    728356000,
    728452000,
    724544000,
    720584000,
    716880000,
    709264000,
    712784000
]

to json with status response like this :

{
    "status": true,
    "message": "",
    "data": [
        759864000,
        740308000,
        724748000,
        725208000,
        729592000,
        732272000,
        728356000,
        728452000,
        724544000,
        720584000,
        716880000,
        709264000,
        712784000
    ]
}

I have used this method to change to json :

coba: async(req, res)=>{
      var spawn = require("child_process").spawn;
      var process = spawn('python',["./coba.py"]);
      process.stdout.on('data', function(data) {
          console.log(data);
          // res.send(data.toString());
          res.send(JSON.parse(data.toString()));
          // res.send(JSON.stringify(data.toString()));
      } )
      process.stderr.on('data', (data) => {
          console.log(`error:${data}`);
      });
       process.stderr.on('close', () => {
          console.log("Closed");
       });},

Can you help me with this? thanks..


问:
C# RSA encryption/decryption with transmission
I've seen plenty of encryption/decryption tutorials and examples on the net in C# that use the System.Security.Cryptography.RSACryptoServiceProvider, but what I'm hoping to be able to do is:

Create an RSA public/private keypair

Transmit the public key (or for proof of concept, just move it in a string variable)

Create a new RSA crypto provider and encrypt a string with the public key

Transmit the encrypted string (or data) back to the original crypto provider and decrypt the string

Could anyone point me to a useful resource for this?

答:
I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference.
My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications.
Here is main part used for signature verification:</p>

```<code>        ...
        var signature = Get(url); // base64_encoded signature received from server
        var inputtext= "inputtext"; // this is main text signature was created for
        bool result = VerifySignature(inputtext, signature);
        ...

    private bool VerifySignature(string input, string signature)
    {
        var result = false;
        using (var cps=new RSACryptoServiceProvider())
        {
            // converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
            byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
            byte[] signatureBytes  = Convert.FromBase64String(signature);

            cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
            result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes  );
        }

        return result;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference.
My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications.
Here is main part used for signature verification:

        ...
        var signature = Get(url); // base64_encoded signature received from server
        var inputtext= "inputtext"; // this is main text signature was created for
        bool result = VerifySignature(inputtext, signature);
        ...

    private bool VerifySignature(string input, string signature)
    {
        var result = false;
        using (var cps=new RSACryptoServiceProvider())
        {
            // converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
            byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
            byte[] signatureBytes  = Convert.FromBase64String(signature);

            cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
            result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes  );
        }

        return result;
    }


问:
How to use shouldSelect on Hint for React-Bootstrap-Typeahead to detect "enter" and "," keystrokes
I have been trying to figure out a way to select hint on "Enter" or "," keystroke but am unable to find any documentation on it. Additionally, I get the following warning, during compilation "Warning: [react-bootstrap-typeahead] The selectHintOnEnter prop is deprecated. Use the shouldSelect prop on the Hint component to define which keystrokes can select the hint." Is there any examples on how to use the shouldSelect on 'Hint'?

答:
The shouldSelect prop has the following signature:

```<code>(shouldSelect: boolean, SyntheticKeyboardEvent<HTMLInputElement>) => boolean
</code>```

You can use it to define the conditions under which the hint should be selected. In your case you'd want something like the following:

```<code><Hint
  shouldSelect={(shouldSelect, e) => {
    // Select the hint if the user hits 'enter' or ','
    return e.keyCode === 13 || e.keyCode === 188 || shouldSelect;
  }}>
  ...
</Hint>
</code>```

Here's a working example: https://codesandbox.io/s/rbt-shouldselect-example-51s7n

Body:
The shouldSelect prop has the following signature:

(shouldSelect: boolean, SyntheticKeyboardEvent<HTMLInputElement>) => boolean

You can use it to define the conditions under which the hint should be selected. In your case you'd want something like the following:

<Hint
  shouldSelect={(shouldSelect, e) => {
    // Select the hint if the user hits 'enter' or ','
    return e.keyCode === 13 || e.keyCode === 188 || shouldSelect;
  }}>
  ...
</Hint>

Here's a working example: https://codesandbox.io/s/rbt-shouldselect-example-51s7n


问:
gps not getting user location
I am trying to get the current user location (latitude and longitude ) but onLocationChanged method is not getting called
but other methods like public void onProviderDisabled(String provider). Please help, what can be the problem ?
I have a class:

```<code>package com.javacodegeeks.android.lbs;

import android.app.Activity;
import android.os.Bundle;

 import android.app.Activity;

 import android.content.Context;

 import android.location.Location;

 import android.location.LocationListener;

 import android.location.LocationManager;

 import android.os.Bundle;

 import android.view.View;

 import android.view.View.OnClickListener;

 import android.widget.Button;

 import android.widget.Toast;

 public class LbsGeocodingActivity extends Activity {

     private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters

     private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

     protected LocationManager locationManager;

     protected Button retrieveLocationButton;

     @Override

     public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.main);

     retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

     locationManager.requestLocationUpdates(

             LocationManager.GPS_PROVIDER,

             MINIMUM_TIME_BETWEEN_UPDATES,

             MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,

             new MyLocationListener()

     );

 retrieveLocationButton.setOnClickListener(new OnClickListener() {

         @Override

         public void onClick(View v) {

             showCurrentLocation();

         }

 });

 }

 protected void showCurrentLocation() {

     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

     if (location != null) {

         String message = String.format(

                 "Current Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message,

                 Toast.LENGTH_LONG).show();

     }

 }

 private class MyLocationListener implements LocationListener {

     public void onLocationChanged(Location location) {

         String message = String.format(

                 "New Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();

     }

     public void onStatusChanged(String s, int i, Bundle b) {

         Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderDisabled(String s) {
         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider disabled by the user. GPS turned off",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderEnabled(String s) {

         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider enabled by the user. GPS turned on",

                 Toast.LENGTH_LONG).show();

     }
 }
 }
</code>```

答:
```<code>public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
 public LocationManager mLocManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    mContext=this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homelayout);

    mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            this);
    mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
            0, this);
    locationUpdate();
    ((Button) this.findViewById(R.id.ButtonHome))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {

                        startActivity(new Intent(HomeActivity.this,
                                DefaultDisplay.class));

                }
            });

    ((Button) this.findViewById(R.id.ButtonProfile))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                MyProfile.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","MyProfile");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonNotifications))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                ShowAllNotificationActiviry.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","ShowAllNotificationActiviry");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonFavorites))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                FavoritesActivity.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","FavoritesActivity");
                        startActivity(intent);
                    }
                }
            });

            ((Button) this.findViewById(R.id.ButtonMore))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                        startActivity(new Intent(HomeActivity.this,
                                MoreListActivity.class));
                }
            });

}

public void locationUpdate()
{
    CellLocation.requestLocationUpdate();
}

public void getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String add = obj.getAddressLine(0);
        GUIStatics.currentAddress = obj.getSubAdminArea() + ","
                + obj.getAdminArea();
        GUIStatics.latitude = obj.getLatitude();
        GUIStatics.longitude = obj.getLongitude();
        GUIStatics.currentCity= obj.getSubAdminArea();
        GUIStatics.currentState= obj.getAdminArea();
        add = add + "\n" + obj.getCountryName();
        add = add + "\n" + obj.getCountryCode();
        add = add + "\n" + obj.getAdminArea();
        add = add + "\n" + obj.getPostalCode();
        add = add + "\n" + obj.getSubAdminArea();
        add = add + "\n" + obj.getLocality();
        add = add + "\n" + obj.getSubThoroughfare();

        Log.v("IGA", "Address" + add);
        // Toast.makeText(this, "Address=>" + add,
        // Toast.LENGTH_SHORT).show();

        // TennisAppActivity.showDialog(add);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    GUIStatics.latitude=location.getLatitude();
    GUIStatics.longitude= location.getLongitude();
    Log.v("Test", "IGA" + "Lat" + latitude + "   Lng" + longitude);
    //mLocManager.r

    getAddress(latitude, longitude);
    if(location!=null)
    {

    mLocManager.removeUpdates(this);
    }
    // Toast.makeText(this, "Lat" + latitude + "   Lng" + longitude,
    // Toast.LENGTH_SHORT).show();
}

public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
}

public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
     if(arg1 ==
            LocationProvider.TEMPORARILY_UNAVAILABLE) {
                                    Toast.makeText(HomeActivity.this,
            "LocationProvider.TEMPORARILY_UNAVAILABLE",
            Toast.LENGTH_SHORT).show();
                        }
                        else if(arg1== LocationProvider.OUT_OF_SERVICE) {
                                    Toast.makeText(HomeActivity.this,
            "LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
                        }

}
</code>```

}
This is the my code i am using this for getting user current location.
Read it carefully the check what the mistake you have done in your code.
and also check all the permission in mainfest file related to gps.

```<code><uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

I hope this is help.

Title: gps not getting user location

Body:
I am trying to get the current user location (latitude and longitude ) but onLocationChanged method is not getting called
but other methods like public void onProviderDisabled(String provider). Please help, what can be the problem ?
I have a class:

package com.javacodegeeks.android.lbs;

import android.app.Activity;
import android.os.Bundle;

 import android.app.Activity;

 import android.content.Context;

 import android.location.Location;

 import android.location.LocationListener;

 import android.location.LocationManager;

 import android.os.Bundle;

 import android.view.View;

 import android.view.View.OnClickListener;

 import android.widget.Button;

 import android.widget.Toast;

 public class LbsGeocodingActivity extends Activity {

     private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters

     private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

     protected LocationManager locationManager;

     protected Button retrieveLocationButton;

     @Override

     public void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);

     setContentView(R.layout.main);

     retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

     locationManager.requestLocationUpdates(

             LocationManager.GPS_PROVIDER,

             MINIMUM_TIME_BETWEEN_UPDATES,

             MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,

             new MyLocationListener()

     );

 retrieveLocationButton.setOnClickListener(new OnClickListener() {

         @Override

         public void onClick(View v) {

             showCurrentLocation();

         }

 });

 }

 protected void showCurrentLocation() {

     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

     if (location != null) {

         String message = String.format(

                 "Current Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message,

                 Toast.LENGTH_LONG).show();

     }

 }

 private class MyLocationListener implements LocationListener {

     public void onLocationChanged(Location location) {

         String message = String.format(

                 "New Location \n Longitude: %1$s \n Latitude: %2$s",

                 location.getLongitude(), location.getLatitude()

         );

         Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();

     }

     public void onStatusChanged(String s, int i, Bundle b) {

         Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderDisabled(String s) {
         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider disabled by the user. GPS turned off",

                 Toast.LENGTH_LONG).show();

     }

     public void onProviderEnabled(String s) {

         Toast.makeText(LbsGeocodingActivity.this,

                 "Provider enabled by the user. GPS turned on",

                 Toast.LENGTH_LONG).show();

     }
 }
 }

Body:
public class HomeActivity extends Activity implements LocationListener{
public static Context mContext;
private double latitude, longitude;
 public LocationManager mLocManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    mContext=this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homelayout);

    mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            this);
    mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
            0, this);
    locationUpdate();
    ((Button) this.findViewById(R.id.ButtonHome))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {

                        startActivity(new Intent(HomeActivity.this,
                                DefaultDisplay.class));

                }
            });

    ((Button) this.findViewById(R.id.ButtonProfile))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                MyProfile.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","MyProfile");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonNotifications))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                ShowAllNotificationActiviry.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","ShowAllNotificationActiviry");
                        startActivity(intent);
                    }
                }
            });

    ((Button) this.findViewById(R.id.ButtonFavorites))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    if (GUIStatics.boolLoginStatus) {
                        startActivity(new Intent(HomeActivity.this,
                                FavoritesActivity.class));
                    } else {
                        Intent intent=new Intent(HomeActivity.this,
                                Login.class);
                        intent.putExtra("moveTo","FavoritesActivity");
                        startActivity(intent);
                    }
                }
            });

            ((Button) this.findViewById(R.id.ButtonMore))
            .setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                        startActivity(new Intent(HomeActivity.this,
                                MoreListActivity.class));
                }
            });

}

public void locationUpdate()
{
    CellLocation.requestLocationUpdate();
}

public void getAddress(double lat, double lng) {
    Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String add = obj.getAddressLine(0);
        GUIStatics.currentAddress = obj.getSubAdminArea() + ","
                + obj.getAdminArea();
        GUIStatics.latitude = obj.getLatitude();
        GUIStatics.longitude = obj.getLongitude();
        GUIStatics.currentCity= obj.getSubAdminArea();
        GUIStatics.currentState= obj.getAdminArea();
        add = add + "\n" + obj.getCountryName();
        add = add + "\n" + obj.getCountryCode();
        add = add + "\n" + obj.getAdminArea();
        add = add + "\n" + obj.getPostalCode();
        add = add + "\n" + obj.getSubAdminArea();
        add = add + "\n" + obj.getLocality();
        add = add + "\n" + obj.getSubThoroughfare();

        Log.v("IGA", "Address" + add);
        // Toast.makeText(this, "Address=>" + add,
        // Toast.LENGTH_SHORT).show();

        // TennisAppActivity.showDialog(add);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    GUIStatics.latitude=location.getLatitude();
    GUIStatics.longitude= location.getLongitude();
    Log.v("Test", "IGA" + "Lat" + latitude + "   Lng" + longitude);
    //mLocManager.r

    getAddress(latitude, longitude);
    if(location!=null)
    {

    mLocManager.removeUpdates(this);
    }
    // Toast.makeText(this, "Lat" + latitude + "   Lng" + longitude,
    // Toast.LENGTH_SHORT).show();
}

public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub
    Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
}

public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
     if(arg1 ==
            LocationProvider.TEMPORARILY_UNAVAILABLE) {
                                    Toast.makeText(HomeActivity.this,
            "LocationProvider.TEMPORARILY_UNAVAILABLE",
            Toast.LENGTH_SHORT).show();
                        }
                        else if(arg1== LocationProvider.OUT_OF_SERVICE) {
                                    Toast.makeText(HomeActivity.this,
            "LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
                        }

}

}
This is the my code i am using this for getting user current location.
Read it carefully the check what the mistake you have done in your code.
and also check all the permission in mainfest file related to gps.

<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I hope this is help.


问:
Cannot focus on TextField in new page after navigating in Flutter
For some reason, I cannot focus on a TextField after on the next page after navigating. The keyboard would automatically dismiss when the TextField is selected. If I set autofocus: true on the TextField, then the keyboard will infinitely popup and immediately dismiss over and over again.

I encountered this when my app was a reasonable size but I was able to recreate this in a minimal example app.

I am using Dart 2.0.0-dev.55.0 with Flutter beta v0.3.2.

Code for main page:

```<code>import 'package:flutter/material.dart';
import 'settings.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Helpful text.',),
            // ===== Where navigation happens =====
            RaisedButton(
              onPressed: () {
                Navigator.push(context, PageRouteBuilder(
                  pageBuilder: (_, __, ___) => SettingsPage()));
              },
              child: Text('Go to input page'),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Here is the code for the page with the TextField.

```<code>import 'package:flutter/material.dart';

class SettingsPage extends StatefulWidget {
  SettingsPage({Key key}) :
   super(key: key);

  @override
  _SettingsPage createState() => new _SettingsPage();
}

class _SettingsPage extends State<SettingsPage> {

  @override
  Widget build(BuildContext context) {
    final key = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: key,
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Settings"),
      ),
      body: ListView(
        children: <Widget>[
          Text("Enter something"),
          // Can't focus on this widget
          TextField(),
        ],
      ),
    );
  }
}
</code>```

I can focus fine on TextField on the main page if I put one there, but can't on the one in the Settings page. I assume it has something to do with the keyboard not taking priority over the popped up page? Or what is going on? How I can get the app to just focus on input fields on a navigated page?

答:
Not sure what your issue is since I can't reproduce it any more. I just tried your code in Flutter Channel beta, 1.18.0-11.1.pre and everything worked as it should without modifying your original code.

It looks more as if it was Flutter's bug rather.

Body:
For some reason, I cannot focus on a TextField after on the next page after navigating. The keyboard would automatically dismiss when the TextField is selected. If I set autofocus: true on the TextField, then the keyboard will infinitely popup and immediately dismiss over and over again.

I encountered this when my app was a reasonable size but I was able to recreate this in a minimal example app.

I am using Dart 2.0.0-dev.55.0 with Flutter beta v0.3.2.

Code for main page:

import 'package:flutter/material.dart';
import 'settings.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Helpful text.',),
            // ===== Where navigation happens =====
            RaisedButton(
              onPressed: () {
                Navigator.push(context, PageRouteBuilder(
                  pageBuilder: (_, __, ___) => SettingsPage()));
              },
              child: Text('Go to input page'),
            ),
          ],
        ),
      ),
    );
  }
}

Here is the code for the page with the TextField.

import 'package:flutter/material.dart';

class SettingsPage extends StatefulWidget {
  SettingsPage({Key key}) :
   super(key: key);

  @override
  _SettingsPage createState() => new _SettingsPage();
}

class _SettingsPage extends State<SettingsPage> {

  @override
  Widget build(BuildContext context) {
    final key = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: key,
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("Settings"),
      ),
      body: ListView(
        children: <Widget>[
          Text("Enter something"),
          // Can't focus on this widget
          TextField(),
        ],
      ),
    );
  }
}

I can focus fine on TextField on the main page if I put one there, but can't on the one in the Settings page. I assume it has something to do with the keyboard not taking priority over the popped up page? Or what is going on? How I can get the app to just focus on input fields on a navigated page?


问:
VB.NET Can't hide login button after doing login successfully
I already tried different methods, but I can't hide the button.
The objective is to only show login button and when we do the login successfully, the button goes Invisible and the other buttons show.

Here is Form "Inicio":

```<code>    Public LoginDone As String = "0"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        hideSubmenu()

        If LoginDone = "0" Then
            btnLogin1.Visible = True
            btnInicio.Visible = False
            btnConta.Visible = False
        Else
            btnLogin1.Visible = False
            btnInicio.Visible = True
            btnConta.Visible = True
        End If

    End Sub
</code>```

Form "Login":

```<code>  If table.Rows.Count = 0 Then

            MessageBox.Show("Login Inválido") 'Failed login

        Else

            MessageBox.Show("Iniciada sessão com sucesso") 'Sucess login

            Inicio.LoginDone = "1"

            Me.Hide()

        End If
</code>```

答:
Form "Inicio":

```<code>Public Sub LoginState(ByVal result As Boolean)
    hideSubmenu()

    If result = True Then
        btnLogin1.Visible = True
        btnInicio.Visible = False
        btnConta.Visible = False
    Else
        btnLogin1.Visible = False
        btnInicio.Visible = True
        btnConta.Visible = True
    End If
    Me.Show()
End Sub
</code>```

Form "Login":

```<code>If table.Rows.Count = 0 Then
    MessageBox.Show("Login Inválido") 'Failed login
    Login.LoginState(False)
Else
    MessageBox.Show("Iniciada sessão com sucesso") 'Sucess login
    Login.LoginState(True)
    Me.Hide()
End If
</code>```

Body:
I already tried different methods, but I can't hide the button.
The objective is to only show login button and when we do the login successfully, the button goes Invisible and the other buttons show.

Here is Form "Inicio":

    Public LoginDone As String = "0"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        hideSubmenu()

        If LoginDone = "0" Then
            btnLogin1.Visible = True
            btnInicio.Visible = False
            btnConta.Visible = False
        Else
            btnLogin1.Visible = False
            btnInicio.Visible = True
            btnConta.Visible = True
        End If

    End Sub

Form "Login":

  If table.Rows.Count = 0 Then

            MessageBox.Show("Login Inválido") 'Failed login

        Else

            MessageBox.Show("Iniciada sessão com sucesso") 'Sucess login

            Inicio.LoginDone = "1"

            Me.Hide()

        End If

Body:
Form "Inicio":

Public Sub LoginState(ByVal result As Boolean)
    hideSubmenu()

    If result = True Then
        btnLogin1.Visible = True
        btnInicio.Visible = False
        btnConta.Visible = False
    Else
        btnLogin1.Visible = False
        btnInicio.Visible = True
        btnConta.Visible = True
    End If
    Me.Show()
End Sub

Form "Login":

If table.Rows.Count = 0 Then
    MessageBox.Show("Login Inválido") 'Failed login
    Login.LoginState(False)
Else
    MessageBox.Show("Iniciada sessão com sucesso") 'Sucess login
    Login.LoginState(True)
    Me.Hide()
End If


问:
Saving and Retrieving Boolean Value from Windows Registry
I'm attempting to save/retrieve a Boolean value from the Windows Registry using Delphi Rio (Firemonkey).  No matter which state I save, true or false, the code always returns a true value.  Here is a sample project that illustrates my method:

```<code>uses
  System.IniFiles, System.Win.Registry;

const
  AppRegKey = 'Software\Mycroft\TestApp';

procedure TForm2.btnReadClick(Sender: TObject);
var
  Reg: TCustomIniFile;
  checked: boolean;
begin
  Reg := TRegistryIniFile.Create('');
  checked := False;
  if Reg.SectionExists(AppRegKey + '\State\BoxChecked') then begin
    checked := Reg.ReadBool(AppRegKey,'Show', True);
  end;
  if checked then
    ShowMessage('Checked')
  else
    ShowMessage('Unchecked');
end;

procedure TForm2.btnSaveClick(Sender: TObject);
var
  Reg: TCustomIniFile;

begin
  Reg := TRegistryIniFile.Create('');
  Reg.WriteBool(AppRegKey + '\State\BoxChecked', 'Show', chkBrandNew.IsChecked);
end;
</code>```

It appears the value is being updated in the Registry, so I'm not sure why it always returns a True value.  Can someone please point me in the proper direction?

答:
You are not passing the same key name to Reg.ReadBool() that you pass to Reg.WriteBool().

You are also leaking the TRegistryIniFile objects.

Try this instead:

uses
  System.IniFiles, System.Win.Registry;

const
  AppRegKey = 'Software\Mycroft\TestApp';
  AppRegKey_BoxChecked = AppRegKey + '\State\BoxChecked';

procedure TForm2.btnReadClick(Sender: TObject);
var
  Reg: TCustomIniFile;
  checked: boolean;
begin
  Reg := TRegistryIniFile.Create('');
  try
    checked := False;
    if Reg.SectionExists(AppRegKey_BoxChecked) then
    begin
      checked := Reg.ReadBool(AppRegKey_BoxChecked, 'Show', True);
    end;
    if checked then
      ShowMessage('Checked')
    else
      ShowMessage('Unchecked');
  finally
    Reg.Free;
  end;
end;

procedure TForm2.btnSaveClick(Sender: TObject);
var
  Reg: TCustomIniFile;
begin
  Reg := TRegistryIniFile.Create('');
  try
    Reg.WriteBool(AppRegKey_BoxChecked, 'Show', chkBrandNew.IsChecked);
  finally
    Reg.Free;
  end;
end;
```

<p>That said, <code>TRegistryIniFile</code> is meant for backwards compatibility with old code that used to save configs using <code>TIniFile</code> and then migrated to the Registry. New code should not be using <code>TRegistryIniFile</code> at all.</p>

<pre class="lang-pascal prettyprint-override"><code>uses
  System.Win.Registry;

const
  AppRegKey = 'Software\Mycroft\TestApp';
  AppRegKey_BoxChecked = AppRegKey + '\State\BoxChecked';

procedure TForm2.btnReadClick(Sender: TObject);
var
  Reg: TRegistry;
  checked: boolean;
begin
  Reg := TRegistry.Create;
  //Reg := TRegistry.Create(KEY_QUERY_VALUE);
  try
    checked := False;
    if Reg.OpenKeyReadOnly(AppRegKey_BoxChecked) then
    // if Reg.OpenKey(AppRegKey_BoxChecked, False) then
    begin
      if Reg.ValueExists('Show') then
        checked := Reg.ReadBool('Show')
      else
        checked := True;
      Reg.CloseKey;
    end;
    if checked then
      ShowMessage('Checked')
    else
      ShowMessage('Unchecked');
  finally
    Reg.Free;
  end;
end;

procedure TForm2.btnSaveClick(Sender: TObject);
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create(KEY_SET_VALUE);
  try
    if Reg.OpenKey(AppRegKey_BoxChecked, True) then
    begin
      Reg.WriteBool('Show', chkBrandNew.IsChecked);
      Reg.CloseKey;
    end;
  finally
    Reg.Free;
  end;
end;
</code>```

Body:
I'm attempting to save/retrieve a Boolean value from the Windows Registry using Delphi Rio (Firemonkey).  No matter which state I save, true or false, the code always returns a true value.  Here is a sample project that illustrates my method:

uses
  System.IniFiles, System.Win.Registry;

const
  AppRegKey = 'Software\Mycroft\TestApp';

procedure TForm2.btnReadClick(Sender: TObject);
var
  Reg: TCustomIniFile;
  checked: boolean;
begin
  Reg := TRegistryIniFile.Create('');
  checked := False;
  if Reg.SectionExists(AppRegKey + '\State\BoxChecked') then begin
    checked := Reg.ReadBool(AppRegKey,'Show', True);
  end;
  if checked then
    ShowMessage('Checked')
  else
    ShowMessage('Unchecked');
end;

procedure TForm2.btnSaveClick(Sender: TObject);
var
  Reg: TCustomIniFile;

begin
  Reg := TRegistryIniFile.Create('');
  Reg.WriteBool(AppRegKey + '\State\BoxChecked', 'Show', chkBrandNew.IsChecked);
end;

It appears the value is being updated in the Registry, so I'm not sure why it always returns a True value.  Can someone please point me in the proper direction?

Body:
You are not passing the same key name to Reg.ReadBool() that you pass to Reg.WriteBool().

You are also leaking the TRegistryIniFile objects.

Try this instead:

uses
  System.IniFiles, System.Win.Registry;

const
  AppRegKey = 'Software\Mycroft\TestApp';
  AppRegKey_BoxChecked = AppRegKey + '\State\BoxChecked';

procedure TForm2.btnReadClick(Sender: TObject);
var
  Reg: TCustomIniFile;
  checked: boolean;
begin
  Reg := TRegistryIniFile.Create('');
  try
    checked := False;
    if Reg.SectionExists(AppRegKey_BoxChecked) then
    begin
      checked := Reg.ReadBool(AppRegKey_BoxChecked, 'Show', True);
    end;
    if checked then
      ShowMessage('Checked')
    else
      ShowMessage('Unchecked');
  finally
    Reg.Free;
  end;
end;

procedure TForm2.btnSaveClick(Sender: TObject);
var
  Reg: TCustomIniFile;
begin
  Reg := TRegistryIniFile.Create('');
  try
    Reg.WriteBool(AppRegKey_BoxChecked, 'Show', chkBrandNew.IsChecked);
  finally
    Reg.Free;
  end;
end;

That said, TRegistryIniFile is meant for backwards compatibility with old code that used to save configs using TIniFile and then migrated to the Registry. New code should not be using TRegistryIniFile at all.

uses
  System.Win.Registry;

const
  AppRegKey = 'Software\Mycroft\TestApp';
  AppRegKey_BoxChecked = AppRegKey + '\State\BoxChecked';

procedure TForm2.btnReadClick(Sender: TObject);
var
  Reg: TRegistry;
  checked: boolean;
begin
  Reg := TRegistry.Create;
  //Reg := TRegistry.Create(KEY_QUERY_VALUE);
  try
    checked := False;
    if Reg.OpenKeyReadOnly(AppRegKey_BoxChecked) then
    // if Reg.OpenKey(AppRegKey_BoxChecked, False) then
    begin
      if Reg.ValueExists('Show') then
        checked := Reg.ReadBool('Show')
      else
        checked := True;
      Reg.CloseKey;
    end;
    if checked then
      ShowMessage('Checked')
    else
      ShowMessage('Unchecked');
  finally
    Reg.Free;
  end;
end;

procedure TForm2.btnSaveClick(Sender: TObject);
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create(KEY_SET_VALUE);
  try
    if Reg.OpenKey(AppRegKey_BoxChecked, True) then
    begin
      Reg.WriteBool('Show', chkBrandNew.IsChecked);
      Reg.CloseKey;
    end;
  finally
    Reg.Free;
  end;
end;


问:
Current line number from a System.Xml.XmlReader (C# & .Net)
Does anyone know how I can get the current line number of an System.Xml.XmlReader?  I am trying to record where in a file I find Xml elements.</p>

答:
Take advantage of the IXmlLineInfo interface supported by an XmlReader:

```<code>IXmlLineInfo xmlInfo = (IXmlLineInfo)reader;
int lineNumber = xmlInfo.LineNumber;
</code>```

OwnerDisplayName: Danielb

ContentLicense: CC BY-SA 2.5

Body:
Take advantage of the IXmlLineInfo interface supported by an XmlReader:

IXmlLineInfo xmlInfo = (IXmlLineInfo)reader;
int lineNumber = xmlInfo.LineNumber;

OwnerDisplayName: Daniel L

LastEditorDisplayName: Daniel L


问:
What does it mean for an element to be 'Self-Contained'
I'm very new to HTML.  I'm following an online tutorial.   I need to put some images on the page and I need to enclose these images in
 tags.  The tutorial doesn't explain why I need to do this.  In fact, it gives no information about the
 tag at all.  So, I googled it and this is what I found:

The HTML  (Figure With Optional Caption) element represents self-contained content, potentially with an optional caption, which is specified using the (
) element. The figure, its caption, and its contents are referenced as a single unit.

Emphasis mine.

This explanation doesn't help me.  Please could someone explain what is meant by 'self-contained content'?  Isn't all content essentially 'self-contained'?  If it wasn't then any adjustment to any element would affect every other element.  Is 'self-contained content' some kind of reserved term with a special meaning in web design?  I just don't understand what it means for content to be 'self-contained' in this context.  As a consequence, I can't understand the point of the

 tags.

Many thanks.

答:
self-contained means that the element's clearly defined its contents, for example
 and  doesn't tell you about itself a lot like a
,
, etc... which are also known as HTML Semantic Elements

self-contained elements like table define a set of styles itself like display:table, and for its inner children (rows and cells for example)

other self-contained elements like  or  are for clean-code and developer-friendly tag naming

For
, An article should make sense on its own, and it should be possible to read it independently from the rest of the web site.

Also, HTML semantics are good for SEO, like header tags
,
, ...

This article define how can these elements help to better define the page's content for search engines, What HTML5 Means For SEO.

As of the purpose of
 tags check these answers on the question What is the purpose of the 'figure' tag in html?

Body:
self-contained means that the element's clearly defined its contents, for example <div> and <span> doesn't tell you about itself a lot like a <table>, <article>, etc... which are also known as HTML Semantic Elements

self-contained elements like table define a set of styles itself like display:table, and for its inner children (rows and cells for example)

other self-contained elements like <main> or <footer> are for clean-code and developer-friendly tag naming

For <article>, An article should make sense on its own, and it should be possible to read it independently from the rest of the web site.

Also, HTML semantics are good for SEO, like header tags <h1>, <h2>, ...

This article define how can these elements help to better define the page's content for search engines, What HTML5 Means For SEO.

As of the purpose of <figure> tags check these answers on the question What is the purpose of the 'figure' tag in html?


问:
Why does this greatest subsequential sum code work?
Rosetta Code has the following task, described here:

"Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence."

This isn't a very complicated problem, and can be comfortably solved in ten lines or less. However, their R solution confused me. I've reproduced it below:

```<code>max.subseq <- function(x) {
  cumulative <- cumsum(x)
  min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
  end <- which.max(cumulative-min.cumulative.so.far)
  begin <- which.min(c(0, cumulative[1:end]))
  if (end >= begin) x[begin:end] else x[c()]
}
</code>```

In particular, I can't see why the min.cumulative.so.far variable is needed and the final line's idea of checking if the index of some maximum is greater than the index of a minimum is very strange to me indeed.

So why does this code work? I understand every individual function and its output, but I have no idea why putting them together like this would work, or why it would be picked over a simpler "generate a list of valid subsequences, and pick the one with the greatest sum" approach.

答:
Let's break it down starting at the result of cumulative.

min.cumulative.so.far will provide you with the minimum cumulative before the current index for all indexes.

In the next step we calculate the cumulative of the best sub-sequence for every element of the sequence, from the min.cumulative.so.far to the value at each index. end will be the end of the best subsequence which can be 1.

This is where it gets interesting: if all values are negative, end will be 1 and all values for cumulative[1:end] will be negative, so the result of which.min() will be 2 as the value is less than 0 (the value at index 1). This will now result in begin being larger than end and the function will return an empty vector. Otherwise begin will be set to the first index after the lowest value before the index end which, as we have already established is the last element of the largest sub-sequence based on cumulative at index begin. This is why 0 is added to the vector. If the relevant min.so.far is negative, start with the next value in the vector. If all the cumulative values are positive, simply start at the beginning (the added 0 will be the lowest value). The only thing that happens in this step is actually finding the index with the minimum cumulative up to index end.

The return is then trivial. Empty if all values are negative as described above, otherwise x from the beginning to the end of the sub-sequence with the largest sum.

Edge case: all values negative

```<code>> x <-  -(1:10)
> cumulative <- cumsum(x)
> cumulative
 [1]  -1  -3  -6 -10 -15 -21 -28 -36 -45 -55
> min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
> min.cumulative.so.far
 [1]  -1  -3  -6 -10 -15 -21 -28 -36 -45 -55
> end <- which.max(cumulative-min.cumulative.so.far)
> end
[1] 1
> begin <- which.min(c(0, cumulative[1:end]))
# c(0, cumulative[1:end]) is c(0, -1) in this case as 1:end = 1:1
> begin
[1] 2
> if (end >= begin) x[begin:end] else x[c()]
integer(0)
</code>```

Standard Case

```<code>> x <- c(1, 5, -9, 3, 7, 1, 2, 4, 5, -6)
> cumulative <- cumsum(x)
> cumulative
 [1]  1  6 -3  0  7  8 10 14 19 13
> min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
> min.cumulative.so.far
 [1]  1  1 -3 -3 -3 -3 -3 -3 -3 -3
> end <- which.max(cumulative-min.cumulative.so.far)
> end
[1] 9
> begin <- which.min(c(0, cumulative[1:end]))
> begin
[1] 4
> if (end >= begin) x[begin:end] else x[c()]
[1] 3 7 1 2 4 5
</code>```

Body:
Rosetta Code has the following task, described here:

"Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be the empty sequence."

This isn't a very complicated problem, and can be comfortably solved in ten lines or less. However, their R solution confused me. I've reproduced it below:

max.subseq <- function(x) {
  cumulative <- cumsum(x)
  min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
  end <- which.max(cumulative-min.cumulative.so.far)
  begin <- which.min(c(0, cumulative[1:end]))
  if (end >= begin) x[begin:end] else x[c()]
}

In particular, I can't see why the min.cumulative.so.far variable is needed and the final line's idea of checking if the index of some maximum is greater than the index of a minimum is very strange to me indeed.

So why does this code work? I understand every individual function and its output, but I have no idea why putting them together like this would work, or why it would be picked over a simpler "generate a list of valid subsequences, and pick the one with the greatest sum" approach.

Body:
Let's break it down starting at the result of cumulative.

min.cumulative.so.far will provide you with the minimum cumulative before the current index for all indexes.

In the next step we calculate the cumulative of the best sub-sequence for every element of the sequence, from the min.cumulative.so.far to the value at each index. end will be the end of the best subsequence which can be 1.

This is where it gets interesting: if all values are negative, end will be 1 and all values for cumulative[1:end] will be negative, so the result of which.min() will be 2 as the value is less than 0 (the value at index 1). This will now result in begin being larger than end and the function will return an empty vector. Otherwise begin will be set to the first index after the lowest value before the index end which, as we have already established is the last element of the largest sub-sequence based on cumulative at index begin. This is why 0 is added to the vector. If the relevant min.so.far is negative, start with the next value in the vector. If all the cumulative values are positive, simply start at the beginning (the added 0 will be the lowest value). The only thing that happens in this step is actually finding the index with the minimum cumulative up to index end.

The return is then trivial. Empty if all values are negative as described above, otherwise x from the beginning to the end of the sub-sequence with the largest sum.

Edge case: all values negative

> x <-  -(1:10)
> cumulative <- cumsum(x)
> cumulative
 [1]  -1  -3  -6 -10 -15 -21 -28 -36 -45 -55
> min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
> min.cumulative.so.far
 [1]  -1  -3  -6 -10 -15 -21 -28 -36 -45 -55
> end <- which.max(cumulative-min.cumulative.so.far)
> end
[1] 1
> begin <- which.min(c(0, cumulative[1:end]))
# c(0, cumulative[1:end]) is c(0, -1) in this case as 1:end = 1:1
> begin
[1] 2
> if (end >= begin) x[begin:end] else x[c()]
integer(0)

Standard Case

> x <- c(1, 5, -9, 3, 7, 1, 2, 4, 5, -6)
> cumulative <- cumsum(x)
> cumulative
 [1]  1  6 -3  0  7  8 10 14 19 13
> min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
> min.cumulative.so.far
 [1]  1  1 -3 -3 -3 -3 -3 -3 -3 -3
> end <- which.max(cumulative-min.cumulative.so.far)
> end
[1] 9
> begin <- which.min(c(0, cumulative[1:end]))
> begin
[1] 4
> if (end >= begin) x[begin:end] else x[c()]
[1] 3 7 1 2 4 5


问:
Core plot x-axis labels are not shown
This is my code. X-Axis labels are not shown. I am using core plot.

```<code>scatterGraph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = nil;
[scatterGraph applyTheme:theme];
hostView.hostedGraph = scatterGraph;
hostView.backgroundColor = [UIColor clearColor];
hostView.collapsesLayers = NO;

scatterGraph.paddingTop = 25.0;
scatterGraph.paddingRight = 25.0;
scatterGraph.paddingLeft = 25.0;
scatterGraph.paddingBottom = 25;
scatterGraph.plotAreaFrame.masksToBorder = NO;
CPXYPlotSpace *scatterPlot = (CPXYPlotSpace *) scatterGraph.defaultPlotSpace;
scatterPlot.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromInt(yCount)];
float xx = [self findMax:LivePriceFeedArray] - [self findMin:LivePriceFeedArray]+1.0;
scatterPlot.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat([self findMin:LivePriceFeedArray]-0.5) length:CPDecimalFromFloat(xx)];

CPXYAxisSet *axisSet =(CPXYAxisSet *) scatterGraph.axisSet;
CPXYAxis *xAxis = axisSet.xAxis;
axisSet.delegate = self;
xAxis.title = @"Days";
xAxis.titleLocation = CPDecimalFromFloat(4.0f);
xAxis.orthogonalCoordinateDecimal = CPDecimalFromFloat(0.0f);
xAxis.majorIntervalLength = CPDecimalFromFloat(5.0f);
xAxis.labelingPolicy = CPAxisLabelingPolicyNone;

NSUInteger labelLocation = 0;
NSMutableArray *customArray = [[NSMutableArray alloc] initWithCapacity:[xAxisLabels count]];
for (NSNumber *i in customLocations) {
    CPAxisLabel *iLabel = [[CPAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation++] textStyle:xAxis.labelTextStyle];
    iLabel.tickLocation = [i decimalValue];
    [customArray addObject:iLabel];
    [iLabel release];
}

xAxis.axisLabels = [NSSet setWithArray:customArray];
xAxis.majorTickLocations = [NSSet setWithArray:customLocations ];
CPLineStyle *majorGridLineStyle = [CPLineStyle lineStyle];
xAxis.majorGridLineStyle = [CPLineStyle lineStyle];

CPXYAxis *yAxis = axisSet.yAxis;
yAxis.title = @"Sales Target";
yAxis.majorIntervalLength = CPDecimalFromFloat(1.0f);
yAxis.labelOffset = -5.0f;
yAxis.orthogonalCoordinateDecimal = CPDecimalFromFloat(0.0f);
CPScatterPlot *graphPlot = [[[CPScatterPlot alloc]init] autorelease];
CPMutableLineStyle *lineStyle = [[graphPlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.0f;
lineStyle.lineColor =  [CPColor whiteColor];
graphPlot.dataLineStyle = lineStyle;
graphPlot.dataSource = self;
[scatterGraph addPlot:graphPlot];
graphPlot.backgroundColor = [UIColor clearColor];
CPLineStyle *minorGridLineStyle = majorGridLineStyle;
xAxis.minorGridLineStyle = minorGridLineStyle;
yAxis.majorGridLineStyle = majorGridLineStyle;
yAxis.minorGridLineStyle = minorGridLineStyle;
</code>```

Why are the x-axis labels not shown?

答:
I solved the issue. There was a problem with orthogonal coordinates.

I solved it like this:

scatterPlot.yRange = [CPPlotRange
  plotRangeWithLocation:
  CPDecimalFromFloat (min)
  length:CPDecimalFromFloat(xx)];
  xAxis.orthogonalCoordinateDecimal =
  CPDecimalFromFloat(min);

Here plotRangeWithLocation for y-axis and orthogonalCoordinateDecimal for x-axis should be the same.

Thanks for the help, Krishnabhadra :)

Title: Core plot x-axis labels are not shown

Body:
This is my code. X-Axis labels are not shown. I am using core plot.

scatterGraph = [[CPXYGraph alloc] initWithFrame:CGRectZero];
CPTheme *theme = nil;
[scatterGraph applyTheme:theme];
hostView.hostedGraph = scatterGraph;
hostView.backgroundColor = [UIColor clearColor];
hostView.collapsesLayers = NO;

scatterGraph.paddingTop = 25.0;
scatterGraph.paddingRight = 25.0;
scatterGraph.paddingLeft = 25.0;
scatterGraph.paddingBottom = 25;
scatterGraph.plotAreaFrame.masksToBorder = NO;
CPXYPlotSpace *scatterPlot = (CPXYPlotSpace *) scatterGraph.defaultPlotSpace;
scatterPlot.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0.0) length:CPDecimalFromInt(yCount)];
float xx = [self findMax:LivePriceFeedArray] - [self findMin:LivePriceFeedArray]+1.0;
scatterPlot.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat([self findMin:LivePriceFeedArray]-0.5) length:CPDecimalFromFloat(xx)];

CPXYAxisSet *axisSet =(CPXYAxisSet *) scatterGraph.axisSet;
CPXYAxis *xAxis = axisSet.xAxis;
axisSet.delegate = self;
xAxis.title = @"Days";
xAxis.titleLocation = CPDecimalFromFloat(4.0f);
xAxis.orthogonalCoordinateDecimal = CPDecimalFromFloat(0.0f);
xAxis.majorIntervalLength = CPDecimalFromFloat(5.0f);
xAxis.labelingPolicy = CPAxisLabelingPolicyNone;

NSUInteger labelLocation = 0;
NSMutableArray *customArray = [[NSMutableArray alloc] initWithCapacity:[xAxisLabels count]];
for (NSNumber *i in customLocations) {
    CPAxisLabel *iLabel = [[CPAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation++] textStyle:xAxis.labelTextStyle];
    iLabel.tickLocation = [i decimalValue];
    [customArray addObject:iLabel];
    [iLabel release];
}

xAxis.axisLabels = [NSSet setWithArray:customArray];
xAxis.majorTickLocations = [NSSet setWithArray:customLocations ];
CPLineStyle *majorGridLineStyle = [CPLineStyle lineStyle];
xAxis.majorGridLineStyle = [CPLineStyle lineStyle];

CPXYAxis *yAxis = axisSet.yAxis;
yAxis.title = @"Sales Target";
yAxis.majorIntervalLength = CPDecimalFromFloat(1.0f);
yAxis.labelOffset = -5.0f;
yAxis.orthogonalCoordinateDecimal = CPDecimalFromFloat(0.0f);
CPScatterPlot *graphPlot = [[[CPScatterPlot alloc]init] autorelease];
CPMutableLineStyle *lineStyle = [[graphPlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 3.0f;
lineStyle.lineColor =  [CPColor whiteColor];
graphPlot.dataLineStyle = lineStyle;
graphPlot.dataSource = self;
[scatterGraph addPlot:graphPlot];
graphPlot.backgroundColor = [UIColor clearColor];
CPLineStyle *minorGridLineStyle = majorGridLineStyle;
xAxis.minorGridLineStyle = minorGridLineStyle;
yAxis.majorGridLineStyle = majorGridLineStyle;
yAxis.minorGridLineStyle = minorGridLineStyle;

Why are the x-axis labels not shown?


问:
How to remove empty error div from DOM in formik form?
I have the following code in the authentication page to control alert messages:

```<code><div className="messages-wrapper">
  {formik.errors.email &&
    <div className="alert alert-danger">
      <ErrorMessage name="email" />
    </div>
  }
  {formik.errors.password &&
    <div className="alert alert-danger">
      <ErrorMessage name="password" />
    </div>
  }
  {error && <div className="alert alert-danger">{error}</div>}
</div>
</code>```

I realize that sometimes in DOM it has:

```<code><div class="alert alert-danger"></div>
</code>```

As a consequence, there is a pink bar in the display.

Does anyone know how to implement such that we only display an alert bar when it has text?

答:
All you need to do is make use of touched property of FormikState:

```<code>export interface FormikState<Values> {
    values: Values;
    errors: FormikErrors<Values>;
    touched: FormikTouched<Values>;   // <=== This one
    isSubmitting: boolean;
    isValidating: boolean;
    status?: any;
    submitCount: number;
}
</code>```

Here is how to get access to touched state for form:

```<code><Formik
  initialValues={{ email: '', password: '' } as IForm}
  validate={(values) => {
    const errors = {} as IForm
    if (!values.email) {
      errors.email = 'Email Required'
    }
    return errors
  }}
  onSubmit={(values, { setSubmitting }) => {
    // ... submit handler
  }}
>
  {({ values, errors, touched, handleChange, handleBlur, handleSubmit,
isSubmitting }) => (
                //  above ^ one
    <form onSubmit={handleSubmit}>
    // ... ...

</code>```

And then use it when showing errors (note the usage of touched.email and touched.password):

```<code><div className="messages-wrapper">
  {errors.email && touched.email && (
    <div className="alert alert-danger">
      <ErrorMessage name="email" />
    </div>
  )}

  {errors.password && touched.password && (
    <div className="alert alert-danger">
      <ErrorMessage name="password" />
    </div>
  )}
</div>
</code>```

To see all of it (Problem + Solution) in action: Playground

Snapshot: No empty div in DOM inside wrapper:

Body:
I have the following code in the authentication page to control alert messages:

  {formik.errors.email &&

      <ErrorMessage name="email" />

  }
  {formik.errors.password &&

      <ErrorMessage name="password" />

  }
  {error &&
{error}
}

I realize that sometimes in DOM it has:

As a consequence, there is a pink bar in the display.

Does anyone know how to implement such that we only display an alert bar when it has text?

Body:
All you need to do is make use of touched property of FormikState:

export interface FormikState<Values> {
    values: Values;
    errors: FormikErrors<Values>;
    touched: FormikTouched<Values>;   // <=== This one
    isSubmitting: boolean;
    isValidating: boolean;
    status?: any;
    submitCount: number;
}

Here is how to get access to touched state for form:

<Formik
  initialValues={{ email: '', password: '' } as IForm}
  validate={(values) => {
    const errors = {} as IForm
    if (!values.email) {
      errors.email = 'Email Required'
    }
    return errors
  }}
  onSubmit={(values, { setSubmitting }) => {
    // ... submit handler
  }}
>
  {({ values, errors, touched, handleChange, handleBlur, handleSubmit,
isSubmitting }) => (
                //  above ^ one
    <form onSubmit={handleSubmit}>
    // ... ...

And then use it when showing errors (note the usage of touched.email and touched.password):

<div className="messages-wrapper">
  {errors.email && touched.email && (
    <div className="alert alert-danger">
      <ErrorMessage name="email" />
    </div>
  )}

  {errors.password && touched.password && (
    <div className="alert alert-danger">
      <ErrorMessage name="password" />
    </div>
  )}
</div>

To see all of it (Problem + Solution) in action: Playground

Snapshot: No empty div in DOM inside wrapper:


问:
React Router and passing props to other component
I have a button in one component and on click I want to go to other component and pass to this component the state.

It's something like this:

```<code>import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import AddNewQuestionPage from 'AddNewQuestionPage';

class AddQuestions extends Component {
  state = {
    questions: []
  };

  routeChange = () => {
    let path = `/admin/add-new-question`;
    this.props.history.push(path);
  }

  render() {
    return (
      <>
       <button onClick={this.routeChange}>
          Add new question
       </button>
       <BrowserRouter>
        <Route exact={true} path='/admin/add-new-question' component={AddNewQuestionPage}/>
       </BrowserRouter>
      </>
    )
  }
}
</code>```

And it doesn't work. On click I go to add-new-question url but the component AddNewQuestionPage doesn't render. It works if I put Route not in AddQuestions component, but in App component. It's the main component of the whole app and using Switch, there are set also other routes.

However I don't know how I can pass the state questions to AddNewQuestionPage component if it's rendered from App component? I can't just do:

```<code><Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={questions} />
</code>```

because it doesn't know what is "questions". Lifting the state up to the main component doesn't seem a good solution for me. I was searching and I can't find how to do it...

答:
You should use the this keyword on the question you're passing to the component.

So something like this

<Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={this.state.questions} />

```

Body:
I have a button in one component and on click I want to go to other component and pass to this component the state.

It's something like this:

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import AddNewQuestionPage from 'AddNewQuestionPage';

class AddQuestions extends Component {
  state = {
    questions: []
  };

  routeChange = () => {
    let path = `/admin/add-new-question`;
    this.props.history.push(path);
  }

  render() {
    return (
      <>
       <button onClick={this.routeChange}>
          Add new question
       </button>
       <BrowserRouter>
        <Route exact={true} path='/admin/add-new-question' component={AddNewQuestionPage}/>
       </BrowserRouter>
      </>
    )
  }
}

And it doesn't work. On click I go to add-new-question url but the component AddNewQuestionPage doesn't render. It works if I put Route not in AddQuestions component, but in App component. It's the main component of the whole app and using Switch, there are set also other routes.

However I don't know how I can pass the state questions to AddNewQuestionPage component if it's rendered from App component? I can't just do:

<Route path='/admin/add-new-question' render={(props) => <AddNewQuestionPage {...props} questions={questions} />

because it doesn't know what is "questions". Lifting the state up to the main component doesn't seem a good solution for me. I was searching and I can't find how to do it...


问:
How to print matching all names given as a argument?
I want to write a script for any name given as an argument and prints the list of paths
to home directories of people with the name.
I am new at scripts. Is there any simple way to do this with awk or egrep command?

Example:

$ show names jakub anna (as an argument)

```<code>/home/users/jakubo
/home/students/j_luczka
/home/students/kubeusz
/home/students/jakub5z
/home/students/qwertinx
/home/users/lazinska
/home/students/annalaz
</code>```

Here is the my friend's code but I have to write it from a different way and it has to be simple like this code

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

for name in $@
do
        awk -v n="$name" -F ':' 'BEGIN{IGNORECASE=1};$5~n{print $6}' /etc/passwd  | while read line
        do
                echo $line
        done
done
</code>```

答:
Since at present the question as a whole is unclear, this is more of a long comment, and only a partial answer.

There is one easy simplification, since the sample code includes:

```<code> ... | while read line
       do
             echo $line
       done
</code>```

All of the code shown above after and including the | is needless, and does nothing, (like a UUoC), and should therefore be removed.  (Actually echo $line with an unquoted $line would remove formatting and repeated spaces, but that's not relevant to the task at hand, so we can say the code above does nothing.)

Body:
I want to write a script for any name given as an argument and prints the list of paths
to home directories of people with the name.
I am new at scripts. Is there any simple way to do this with awk or egrep command?

Example:

$ show names jakub anna (as an argument)

/home/users/jakubo
/home/students/j_luczka
/home/students/kubeusz
/home/students/jakub5z
/home/students/qwertinx
/home/users/lazinska
/home/students/annalaz

Here is the my friend's code but I have to write it from a different way and it has to be simple like this code

#!/bin/bash

for name in $@
do
        awk -v n="$name" -F ':' 'BEGIN{IGNORECASE=1};$5~n{print $6}' /etc/passwd  | while read line
        do
                echo $line
        done
done

Body:
Since at present the question as a whole is unclear, this is more of a long comment, and only a partial answer.

There is one easy simplification, since the sample code includes:

 ... | while read line
       do
             echo $line
       done

All of the code shown above after and including the | is needless, and does nothing, (like a UUoC), and should therefore be removed.  (Actually echo $line with an unquoted $line would remove formatting and repeated spaces, but that's not relevant to the task at hand, so we can say the code above does nothing.)


问:
How to get current Button text color in Android?
I cant figure out how to get the current color of the text of a Button. I know its probably this but cant quite figure out the parameters.

```<code>public static int getTextColor (Context context, TypedArray attrs, int def)...
</code>```

Basically Im trying to do this

```<code>if(text is RED)
{make text BLACK}
else
{make text RED}
</code>```

I know how to set the text color.

答:
try this</p>

```<code>ColorStateList mList = mButton.getTextColors();
int color = mList.getDefaultColor();

switch(color)
{
case Color.RED:
mButton.setTextColor(Color.BLACK);
break;

case Color.BLACK:
mButton.setTextColor(Color.RED);
break;

}
</code>```

Body:
I cant figure out how to get the current color of the text of a Button. I know its probably this but cant quite figure out the parameters.

public static int getTextColor (Context context, TypedArray attrs, int def)...

Basically Im trying to do this

if(text is RED)
{make text BLACK}
else
{make text RED}

I know how to set the text color.

Body:
try this

ColorStateList mList = mButton.getTextColors();
int color = mList.getDefaultColor();

switch(color)
{
case Color.RED:
mButton.setTextColor(Color.BLACK);
break;

case Color.BLACK:
mButton.setTextColor(Color.RED);
break;

}


问:
How can I peek the tail of a java.util.PriorityQueue?
So I am playing with the source code of the java.util.PriorityQueue. You can check it here: http://kickjava.com/src/java/util/PriorityQueue.java.htm

I am in need to peek the tail of the queue. This class only offers peeking the head of the queue. Is there an easy way that I can modify this class to allow me to pick the tail?

I am looking for any change / smart hack in this class to allow me to do that. My first try was to peek queue[size] but it did not work.

答:
How about use toArray() method and access the last position?</p>

```<code>PriorityQueue<Integer> pq = new PriorityQueue<>(3);
pq.offer(1); pq.offer(2); pq.offer(3);
System.out.println((int) pq.toArray()[pq.size()-1]);
</code>```

Body:
How about use toArray() method and access the last position?

PriorityQueue<Integer> pq = new PriorityQueue<>(3);
pq.offer(1); pq.offer(2); pq.offer(3);
System.out.println((int) pq.toArray()[pq.size()-1]);


问:
Button that changes a boolean value tkinter
I have a button in Tkinter  that acts as the first button in a game so I want it to start the game and also destroy itself so the player can start playing, but I can't seem to get it to work.

Here is my code so far, any help would be much appreciated:

```<code>from tkinter import *
from random import seed
from random import randint
from tkinter import font as font
import time

root = Tk()
myFont = font.Font(size=25)
root.title("Python Guessing Game")
root.geometry("600x600")

ready = False;

if ready == True:
  print('Hello! What is your name ?')
  destroyBtn()

button_start = Button(root, text="Start Game", font=myFont, bg='#0052cc', fg='#ffffff', command=ready
   = True, height=1, width=20).place(relx=0.5, rely=0.5, anchor=CENTER)

def destroyBtn():
   button_start.destroy()
</code>```

答:
Hello I've coded a quick sample of what I believe you are looking for. If this does not solve this issue please expand on what you are looking for. </p>

```<code>from tkinter import *

gameStarted = False

def startGame():
    gameStarted = True
    print("The game status is now:" + str(gameStarted))
    myButton.destroy()
    print("The button is now destroyed.")

root = Tk()
myButton = Button(root, text="start game", command=startGame)
myButton.pack(fill=BOTH)
root.mainloop()
</code>```

Body:
I have a button in Tkinter  that acts as the first button in a game so I want it to start the game and also destroy itself so the player can start playing, but I can't seem to get it to work.

Here is my code so far, any help would be much appreciated:

from tkinter import *
from random import seed
from random import randint
from tkinter import font as font
import time

root = Tk()
myFont = font.Font(size=25)
root.title("Python Guessing Game")
root.geometry("600x600")

ready = False;

if ready == True:
  print('Hello! What is your name ?')
  destroyBtn()

button_start = Button(root, text="Start Game", font=myFont, bg='#0052cc', fg='#ffffff', command=ready
   = True, height=1, width=20).place(relx=0.5, rely=0.5, anchor=CENTER)

def destroyBtn():
   button_start.destroy()

Body:
Hello I've coded a quick sample of what I believe you are looking for. If this does not solve this issue please expand on what you are looking for.

from tkinter import *

gameStarted = False

def startGame():
    gameStarted = True
    print("The game status is now:" + str(gameStarted))
    myButton.destroy()
    print("The button is now destroyed.")

root = Tk()
myButton = Button(root, text="start game", command=startGame)
myButton.pack(fill=BOTH)
root.mainloop()


问:
How to pass BufReader to another function in rust?
new to rust, I'm asking this to hopefully understand how to work with the language better..

Heres me trying to read a file, pass the file handle to a different function and print the lines from there:

```<code>use std::fs::File;
use std::io::{self, BufReader};
use std::io::BufRead;
use async_std::task;

async fn scrape<R: BufRead>(reader: &mut R) {
    reader.lines().for_each(|line| println!(line));
}

fn main() -> io::Result<()> {
    let file = File::open("wlist.txt")?;
    let reader = BufReader::new(file);

    // print_type_of(&reader); // prints std::io::buffered::BufReader<std::fs::File>
    task::block_on(scrape(&mut reader));

    Ok(())
}

// helper functions
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}
</code>```

Would love some insights regarding what concepts i'm missing and how this should be done properly !

答:
This version atleast compiles, but there's no async in the playground so I coudn't add async.

You have to catch errors in scrape by using try_for_each function, inside you parse io::Result<String> via and_then. In your main you have to catch all errors explicitly, not allowed to let io::Error slip through ? operator

```<code>use std::fs::File;
use std::io::{self, BufReader};
use std::io::BufRead;
//use async_std::task;

fn scrape<R: BufRead>(reader: &mut R) -> io::Result<()> {
    reader.lines()
        .try_for_each(|lineResult| lineResult.and_then(|line| Ok(println!("{}", line))))?;
    Ok(())
}

fn main() {
    //let fileResult = File::open("wlist.txt");
    //let mut file;
    //match fileResult {
    //    Ok(f) => file = f,
    //    Err(e) => println!("File open error! {}", e),
    //}
    let mut file = b"hello\nworld\nhow\nare\nyou\ndoing" as &[u8]; // no file in playground, so just a buffer
    let mut reader = BufReader::new(file);

    // print_type_of(&reader); // prints std::io::buffered::BufReader<std::fs::File>
    match scrape(&mut reader) {
        Ok(_) => println!("Scraping is done!"),
        Err(e) => println!("File read error! {}", e),
    }
}

// helper functions
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}
</code>```

Body:
new to rust, I'm asking this to hopefully understand how to work with the language better..

Heres me trying to read a file, pass the file handle to a different function and print the lines from there:

use std::fs::File;
use std::io::{self, BufReader};
use std::io::BufRead;
use async_std::task;

async fn scrape<R: BufRead>(reader: &mut R) {
    reader.lines().for_each(|line| println!(line));
}

fn main() -> io::Result<()> {
    let file = File::open("wlist.txt")?;
    let reader = BufReader::new(file);

    // print_type_of(&reader); // prints std::io::buffered::BufReader<std::fs::File>
    task::block_on(scrape(&mut reader));

    Ok(())
}

// helper functions
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

Would love some insights regarding what concepts i'm missing and how this should be done properly !

Body:
This version atleast compiles, but there's no async in the playground so I coudn't add async.

You have to catch errors in scrape by using try_for_each function, inside you parse io::Result<String> via and_then. In your main you have to catch all errors explicitly, not allowed to let io::Error slip through ? operator

use std::fs::File;
use std::io::{self, BufReader};
use std::io::BufRead;
//use async_std::task;

fn scrape<R: BufRead>(reader: &mut R) -> io::Result<()> {
    reader.lines()
        .try_for_each(|lineResult| lineResult.and_then(|line| Ok(println!("{}", line))))?;
    Ok(())
}

fn main() {
    //let fileResult = File::open("wlist.txt");
    //let mut file;
    //match fileResult {
    //    Ok(f) => file = f,
    //    Err(e) => println!("File open error! {}", e),
    //}
    let mut file = b"hello\nworld\nhow\nare\nyou\ndoing" as &[u8]; // no file in playground, so just a buffer
    let mut reader = BufReader::new(file);

    // print_type_of(&reader); // prints std::io::buffered::BufReader<std::fs::File>
    match scrape(&mut reader) {
        Ok(_) => println!("Scraping is done!"),
        Err(e) => println!("File read error! {}", e),
    }
}

// helper functions
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}


问:
How do you reference a Key from Azure Key Vault in a function app?
I've used quite a few secrets for Azure Functions in the past, and now I am trying to use a Key, RSA encrypted , 4096 bits. It's a private PuTTy .ppk key, which I've exported to a .pem type to match Azure's requirements. I have a Python 3.7 App in which I have deployed the needed function and I have tried to reference in the Application Settings the needed key with the following statement :

@Microsoft.KeyVault(SecretUri=https://{thevault-address}.vault.azure.net/keys/{thekey-name}/)

as well as

@Microsoft.KeyVault(SecretUri=https://{thevault-address}.vault.azure.net/keys/{thekey-name}/latestVersionHash)

But when I try to save it , it says that the reference could not be resolved.

The application has Identity On and the Vault has access policies for the Function configured for secrets as Get and List and for Keys as everything (initially just Get and List but added the rest just in case, because I thought that it might be an 'encription/decription' issue).

And idea why am I getting the Status:InvalidSyntax and Error Details:
Key Vault reference was not able to be resolved because invalid Key Vault reference syntax found ? Thanks !

答: Unfortunately App Services / Azure Functions only support referencing secrets, not keys or certificates. In fact, Key Vault won't let you access the private half of a key at all, so you'll need to store it as a secret if you need to access it, or use the Key Vault SDK if you just want to do encryption/decryption using the saved key.</p>


问:
Jest: Spy on other function in module being tested
I'm trying to test a module using jest. In the module, I have a function which works as a kind of front to two other functions, and delegates to them based on its parameter. I'm trying to figure out if these functions have indeed been called.

I have tried using a spy function, but it is never called. Instead, the actual function is called, bypassing my spy.

All examples I have found with mocking and spies involve mocking and spying on another module than the one being tested, but in this case I am trying to spy on a function from the module being tested. Is this even possible? Is there a better way to do this?

Example code:

// funcs.js

const decide = obj => {
  if (obj.a !== undefined) {
    return funcA(obj);
  } else {
    return funcB(obj);
  }
};

const funcA = obj => obj.a;
const funcB = obj => obj.b;

export { decide, funcA, funcB };
```

<pre class="lang-js prettyprint-override"><code>// funcs.test.js

import * as fns from "./funcs";

describe("decide", () => {
  it("should delegate to 'funcA' when the parameter has an 'a' property", () => {
    const spy = jest.spyOn(fns, "funcA");
    fns.decide({ a: "Cake" });
    expect(spy).toHaveBeenCalled(); // Error! Number of calls: 0
  });
});
</code>```

答:
There's no way to spy or mock a function that is called in the same ES module it is defined.

This is possible for CommonJS modules but only if functions are consistently referred as methods:

```<code>exports.decide = obj => {
  ...
  exports.funcA(obj);
  ...
};

exports.funcA = obj => obj.a;
</code>```

It's possible to adopt this recipe to ES modules but this discards their benefits:

```<code>const exports = {};
export default exports;

// same as CommonJS
</code>```

funcA and funcB should be either moved to separate module for testability purposes and be spied or mocked with jest.mock, or all of them should be tested as a single unit.

Body:
I'm trying to test a module using jest. In the module, I have a function which works as a kind of front to two other functions, and delegates to them based on its parameter. I'm trying to figure out if these functions have indeed been called.

I have tried using a spy function, but it is never called. Instead, the actual function is called, bypassing my spy.

All examples I have found with mocking and spies involve mocking and spying on another module than the one being tested, but in this case I am trying to spy on a function from the module being tested. Is this even possible? Is there a better way to do this?

Example code:

// funcs.js

const decide = obj => {
  if (obj.a !== undefined) {
    return funcA(obj);
  } else {
    return funcB(obj);
  }
};

const funcA = obj => obj.a;
const funcB = obj => obj.b;

export { decide, funcA, funcB };

// funcs.test.js

import * as fns from "./funcs";

describe("decide", () => {
  it("should delegate to 'funcA' when the parameter has an 'a' property", () => {
    const spy = jest.spyOn(fns, "funcA");
    fns.decide({ a: "Cake" });
    expect(spy).toHaveBeenCalled(); // Error! Number of calls: 0
  });
});

Body:
There's no way to spy or mock a function that is called in the same ES module it is defined.

This is possible for CommonJS modules but only if functions are consistently referred as methods:

exports.decide = obj => {
  ...
  exports.funcA(obj);
  ...
};

exports.funcA = obj => obj.a;

It's possible to adopt this recipe to ES modules but this discards their benefits:

const exports = {};
export default exports;

// same as CommonJS

funcA and funcB should be either moved to separate module for testability purposes and be spied or mocked with jest.mock, or all of them should be tested as a single unit.


答:
The best way to use react-router dom is :

Always make  as a parent component for all.

The best way to change the path by clicking on a sort of component (button ...) is You label

Please check this guide out : https://reacttraining.com/react-router/web/guides/quick-start

Title: React Router and passing props to other component


问:
How can I put this DRY code into a for loop?
I am formatting a legend in pyplot, and have successfully gotten the output I want. However, I'm trying to figure out how to format this code into a for loop.

This is the code I am trying to loop:

```<code>L.get_texts()[0].set_text('Global')
L.get_texts()[1].set_text('Bangkok')
L.get_texts()[2].set_text('NYC')
L.get_texts()[3].set_text('Perth')
L.get_texts()[4].set_text('Quito')
L.get_texts()[5].set_text('Santiago')
L.get_texts()[6].set_text('Singapore')
L.get_texts()[7].set_text('Tianjin')
</code>```

I can loop for each index[0,7], but I can't figure out how to loop for the set_text('argument') as well. This is what I have tried so far:

```<code>legend_labels = ['Global', 'Bangkok', 'NYC', 'Perth', 'Quito', 'Santiago',
'Singapore', 'Tianjin']

for i in range(8):
L.get_texts()[i].set_text(legend_labels)
</code>```

I made the list, legend_labels, that I want to loop through. I've tried a few different nested for loops, but can't seem to get it working.

From the code that I am trying now this is the output I get:
Notice only 'Tianjin' gets printed on the legend.

This is my desired output: Each item in list is printed on the legend.

答:
You can use enumerate that will give you both, the index i as well as the label

```<code>for i, label in enumerate(legend_labels):
    L.get_texts()[i].set_text(label)
</code>```

Body:
I am formatting a legend in pyplot, and have successfully gotten the output I want. However, I'm trying to figure out how to format this code into a for loop.

This is the code I am trying to loop:

L.get_texts()[0].set_text('Global')
L.get_texts()[1].set_text('Bangkok')
L.get_texts()[2].set_text('NYC')
L.get_texts()[3].set_text('Perth')
L.get_texts()[4].set_text('Quito')
L.get_texts()[5].set_text('Santiago')
L.get_texts()[6].set_text('Singapore')
L.get_texts()[7].set_text('Tianjin')

I can loop for each index[0,7], but I can't figure out how to loop for the set_text('argument') as well. This is what I have tried so far:

legend_labels = ['Global', 'Bangkok', 'NYC', 'Perth', 'Quito', 'Santiago',
'Singapore', 'Tianjin']

for i in range(8):
L.get_texts()[i].set_text(legend_labels)

I made the list, legend_labels, that I want to loop through. I've tried a few different nested for loops, but can't seem to get it working.

From the code that I am trying now this is the output I get:
Notice only 'Tianjin' gets printed on the legend.

This is my desired output: Each item in list is printed on the legend.

Body:
You can use enumerate that will give you both, the index i as well as the label

for i, label in enumerate(legend_labels):
    L.get_texts()[i].set_text(label)